902. Self-healing browser agent selectors
Why it matters Browser agents break when a site renames a button. Fallback selectors plus a cache of what last worked is a simple, testable form of self-healing.
A browser agent clicks elements by CSS selector. Sites change, so each step lists fallback selectors, and the agent remembers which selector worked last time (a cache). This is a small "self-healing" loop.
Write run_browser_steps(steps, page, cache).
- steps: list of dicts {"name": str, "candidates": list of selector strings}.
- page: dict mapping each selector present on the current page to an element id (str).
- cache: dict step name -> selector that worked before (may be empty). Do not modify the input dict; work on a copy.
- For each step, try selectors in this order: the cached selector for the step (if any), then the candidates in order, skipping one equal to the cached selector. Each try is one lookup in page and counts as an attempt. The first selector present wins.
- Status: "ok" if the winner is the cached selector, or there is no cache entry and the winner is the first candidate. Otherwise "healed". Store the winner in the cache.
- If no selector is present, the step is "failed" and every later step is "not_run" (with selector None and no attempts).
Return a dict {"results": list of [name, status, selector or None], "cache": the updated cache dict, "attempts": total lookups}.
def run_browser_steps(steps, page, cache)Example 1
Input: run_browser_steps([{'name': 'login', 'candidates': ['#login', 'button.signin']}, {'name': 'submit', 'candidates': ['#submit', 'form button']}], {'button.signin': 'e1', '#submit': 'e2'}, {})
Output: {'results': [['login', 'healed', 'button.signin'], ['submit', 'ok', '#submit']], 'cache': {'login': 'button.signin', 'submit': '#submit'}, 'attempts': 3}
Example 2
Input: steps = [{'name': 'login', 'candidates': ['#login', 'button.signin']}], page = {'button.signin': 'e1'}, cache = {'login': 'button.signin'}
Output: {'results': [['login', 'ok', 'button.signin']], 'cache': {'login': 'button.signin'}, 'attempts': 1}
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Copy the cache before changing it.
Hint 2
Build the try order: cached selector, then candidates without the duplicate.
Hint 3
After a failure, mark the rest not_run and stop counting attempts.
Common mistakes
- Mutating the caller's cache.
- Trying the cached selector twice.
- Marking a cache hit on a non-first candidate as healed.
Understand the idea
Trying the cached selector first makes the common case one lookup. When it fails, falling back through the candidates heals the step and the new winner replaces the cache entry, so the next run is fast again. Stopping after a failed step matters: clicking later steps on the wrong page can do real damage, such as submitting a half-filled form.
Shapes and data flow
Lists and dicts in, dict out.