Repository navigation
test(backend): ratchet tiny real-clock budgets in tests - #22797
Conversation
Three times on 2026-10-20 a backend unit test that shrank a production budget to tens of milliseconds raced a loaded CI runner (#22758, #22767, and the legacy-retire change C10). Add a static AST ratchet over backend/tests/**/*.py that flags budget/deadline/timeout names set to a literal in (0, 0.5) s via attribute assignment, setattr/patch.object/ patch, setenv/os.environ/patch.dict, or keyword arguments to code under test. Harness waits (wait_for, Event.wait, get, join, ...), mock call assertions, and functions that control the clock are excluded. The 100 current offenders are allowlisted with a blame owner and #22767; the test fails on new offenders and on stale entries so the list only shrinks. It is a codebase scan, so it is marked slow and listed in tests/slow_guardrail_manifest.txt (~0.45 s). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 65e7559274
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| tests/unit/test_pusher_circuit_breaker.py | ||
| tests/unit/test_pusher_ghost_connections.py | ||
| tests/unit/test_pusher_heartbeat.py | ||
| tests/unit/test_real_clock_budget_ratchet.py |
There was a problem hiding this comment.
Register the ratchet in both check lanes
This commit only adds the ratchet to the slow CI manifest; it adds no entry to .github/checks-manifest.yaml. Because local backend runs exclude slow tests, a developer introducing a tiny real-clock budget will not encounter this check locally and will first see it fail in CI. Register a hermetic invocation with both local and ci lanes as required. .github/agent-docs/doc-maintenance.mdL33-L37
Useful? React with 👍 / 👎.
| if last in ('setattr', 'object') and len(args) >= 3 and _string(args[1]) is not None: | ||
| # setattr(obj, 'NAME', v) / monkeypatch.setattr(obj, 'NAME', v) / patch.object(obj, 'NAME', v) | ||
| self._flag(_string(args[1]), _number(args[2], allow_str=False)) # type: ignore[arg-type] |
There was a problem hiding this comment.
Handle keyword
new in patch.object calls
When a preferred patch is written as patch.object(module, "REQUEST_TIMEOUT_SECONDS", new=0.01), there are only two positional arguments, so this branch is skipped; the generic keyword pass sees only the name new, and the tiny timeout is never reported. Read keywords.get("new") for patch.object as the dotted-string branch already does, and add a fixture for this standard call form.
AGENTS.md reference: backend/AGENTS.md:L227-L227
Useful? React with 👍 / 👎.
| 'wait', | ||
| 'get', | ||
| 'join', | ||
| 'result', | ||
| 'acquire', |
There was a problem hiding this comment.
Restrict exemptions to actual harness calls
The exemption is based only on the final method name, so a production call such as service.wait(timeout=0.01) or client.get(timeout=0.1) is discarded exactly like Event.wait or Queue.get. Any new test exercising a code-under-test API named wait, get, join, result, acquire, or put can therefore introduce the flaky budget this ratchet is intended to reject; match the known harness receiver/call shapes rather than globally exempting these common method names.
Useful? React with 👍 / 👎.
| def test_no_new_tiny_real_clock_budgets() -> None: | ||
| allowed = {entry for entry, _ in load_allowlist()} | ||
| new = sorted(scan_tree() - allowed) |
There was a problem hiding this comment.
Enforce that the allowlist cannot grow
The current working-tree allowlist is treated as authoritative, so a change can add module.REQUEST_TIMEOUT_SECONDS = 0.01 and a matching allowlist entry in the same commit: new and stale are then both empty, and the ownership-format test also passes. Consequently the advertised “only shrinks” ratchet does not actually reject allowlist growth; compare the entries against the base revision or another immutable baseline before accepting them.
Useful? React with 👍 / 👎.
| _PREFILTER = re.compile( | ||
| rb'(?:budget|deadline|timeout)\w*[\'"]?\]?\s*[=,:]\s*(?:\w+\s*=\s*)?[\'"]?(?:0*\.\d|\d+(?:\.\d*)?e-\d)' |
There was a problem hiding this comment.
Allow parentheses before literals in the prefilter
A literal wrapped in parentheses, such as drain_tasks(tasks, timeout=(0.1)) or the multiline equivalent, is still an ast.Constant that the scanner would flag, but this byte prefilter requires the number to immediately follow = and returns false before parsing. A new tiny real-clock budget can therefore bypass the ratchet solely because of harmless formatting; make the prefilter a true superset by admitting optional parentheses and cover both single-line and multiline forms.
Useful? React with 👍 / 👎.
| source = '\n'.join(self.lines[node.lineno - 1 : node.end_lineno]) # type: ignore[attr-defined] | ||
| self.clock_controlled = bool(_FAKE_CLOCK.search(source)) |
There was a problem hiding this comment.
Scope fake-clock exemptions to the affected budget
Finding any fake-clock-looking text marks the entire outer test function as clock-controlled, so a mixed test such as deterministic(timeout_seconds=0.01, clock=fake_clock) followed by production_using_real_time(timeout_seconds=0.01) reports neither call. Even an unrelated string containing "monotonic" triggers the same exemption. Track whether each flagged assignment or call actually receives or patches the fake clock instead of suppressing every budget in the function.
Useful? React with 👍 / 👎.
Grok review (FIX-FIRST) found four gaps:
- `'monotonic': time.monotonic` counted as a fake clock and exempted six
real-clock ack-budget tests in test_listen_pusher_session.py. Only a
clock replaced by something other than time.* / None counts now, and
decorators are part of the inspected source. The six sites are
grandfathered (106 entries).
- patch.object(obj, 'NAME', new=v) was not read.
- The byte prefilter missed parenthesized, ' +0.05', and 1_0e-2 values.
It is possessive now so whitespace runs cannot backtrack.
- patch.dict('os.environ', ...), patch.dict(..., NAME='0.05') and
values={...} were not read.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0750d9a894
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if last in ('setattr', 'object') and len(args) >= 2 and _string(args[1]) is not None: | ||
| # setattr(obj, 'NAME', v) / monkeypatch.setattr(obj, 'NAME', v) / patch.object(obj, 'NAME', v | new=v) | ||
| value = args[2] if len(args) >= 3 else keywords.get('new') | ||
| if value is not None: | ||
| self._flag(_string(args[1]), _number(value, allow_str=False)) # type: ignore[arg-type] |
There was a problem hiding this comment.
Recognize keyword arguments in patch helpers
When a valid invocation supplies the helper parameters by keyword, such as patch.object(target=module, attribute='REQUEST_TIMEOUT_SECONDS', new=0.05) or monkeypatch.setenv(name='REQUEST_TIMEOUT_SECONDS', value='0.05'), these positional guards never run. The generic keyword pass examines argument names such as attribute, new, and value rather than the budget-name string, so the tiny real-clock budget produces no offender and bypasses the ratchet; normalize the positional and keyword forms before scanning.
Useful? React with 👍 / 👎.
| def _number(node: ast.AST, *, allow_str: bool) -> Optional[float]: | ||
| if not isinstance(node, ast.Constant): | ||
| return None |
There was a problem hiding this comment.
Unwrap unary-plus numeric literals
When a budget is written as module.REQUEST_TIMEOUT_SECONDS = +0.05 or call(timeout=+0.05), the prefilter admits the source, but Python represents the value as an ast.UnaryOp rather than an ast.Constant; _number therefore returns None and silently misses the offender. Unwrap ast.UAdd around numeric constants so this harmless formatting cannot bypass the ratchet.
Useful? React with 👍 / 👎.
| elif last == 'setenv' and len(args) >= 2 and _string(args[0]) is not None: | ||
| self._flag(_string(args[0]), _number(args[1], allow_str=True)) # type: ignore[arg-type] |
There was a problem hiding this comment.
Scan os.environ.setdefault mutations
When an env-backed timeout is configured with os.environ.setdefault, this visitor ignores it because the call has neither a recognized callee nor keyword arguments. This already omits PARAKEET_GPU_POLL_TIMEOUT="0.01" in tests/unit/test_parakeet_gpu_worker.py, even though the prefilter admits that file, and future tests using this common environment setup pattern will also bypass the ratchet; handle environ.setdefault and grandfather the existing site alongside the other env mutation forms.
Useful? React with 👍 / 👎.
Grok r2: the optional `new=` introducer could be skipped so the lookahead tested `new`, and `(time.monotonic)` slipped past it, so `patch.object(obj, 'monotonic', new=time.monotonic)` still exempted the function. Introducers (`new=`/`value=`, parentheses, whitespace) are now consumed possessively and also rejected by the lookahead. Self-tests cover both real-clock spellings and a fake `new=` clock. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 71557b7d32
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| def _enter(self, node: ast.AST) -> None: | ||
| self.scope.append(node.name) # type: ignore[attr-defined] | ||
| is_outer_def = self.outer_def is None and isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) |
There was a problem hiding this comment.
Honor class-level clock-freezing decorators
When a test class is decorated with @freeze_time(...), is_outer_def remains false for the class, and each method is later scanned using source that excludes the class decorator. A method that passes timeout=0.1 or assigns a tiny budget is therefore reported even though the class-level decorator gives it a deterministic clock, causing this ratchet to reject valid frozen-clock tests. Preserve the clock-controlled state inherited from class decorators when visiting their methods.
Useful? React with 👍 / 👎.
| def _flag(self, name: str, value: Optional[float]) -> None: | ||
| if value is None or not (0 < value < LIMIT_SECONDS) or not _BUDGET_NAME.search(name): |
There was a problem hiding this comment.
Normalize millisecond timeout values before comparison
When code under test accepts the repository's established timeout_ms spelling, a value such as timeout_ms=100 is a 0.1-second real-clock budget, but this comparison treats the raw value as seconds and ignores it because 100 exceeds 0.5. This lets the same flaky budget class bypass the ratchet solely because an API expresses its timeout in milliseconds; interpret recognized unit suffixes before applying LIMIT_SECONDS.
Useful? React with 👍 / 👎.
…er tests #22797's ratchet requires the list to shrink when its tests go. Co-Authored-By: Claude Opus 5.5 <[email protected]>
#22226 added test_first_attempt_past_the_per_attempt_deadline_still_summarizes with a 0.1 s per-attempt budget after #22797's real-clock-budget ratchet landed, so "Backend unit guardrails" fails on main for every PR that runs it (main's own push CI does not select the job). Scale the per-attempt budget to 0.5 s and the slow turn to 0.75 s: same ratio, still past one attempt and inside the mount's import-time whole-transport deadline. The sleep is wall time, so the CPU-time fast-unit guard is unaffected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Why
On 2026-10-20, three separate CI runs flaked or failed on the same kind of test. Each one shrank a production budget to tens of milliseconds of real time and then expected healthy in-process work to finish inside it. On a loaded runner, a scheduler hiccup is longer than the budget:
SYNC_JOB_HANDLER_BUDGET_SECONDS = 0.05intest_sync_cloud_tasks.pyDAILY_SUMMARY_USER_BUDGET_SECONDS = 0.05,REQUEST_TIMEOUT_SECONDS = 0.02, and the sync handler budgetThis PR adds a ratchet so new tests stop adding to the class. Existing tests are listed in an allowlist, and the allowlist can only shrink.
What it flags
backend/tests/unit/test_real_clock_budget_ratchet.pyis a pure staticastscan ofbackend/tests/**/*.py. It imports none of the code under test. It flags a literal value with0 < value < 0.5seconds when the name matchesbudget|deadline|timeout(case-insensitive) and the value is set in one of these ways:module.X_BUDGET_SECONDS = 0.05setattr/monkeypatch.setattr/patch.object/patch('pkg.mod.X', 0.05 | new=0.05)monkeypatch.setenv,os.environ[...] = '0.05',patch.dict(os.environ, {...})drain_tasks(..., timeout=0.1),Budget(deadline_seconds=0.01)It does not flag:
asyncio.wait_for,Event.wait,Queue.get,Thread.join,Future.result,Lock.acquire)sleepcalls and plain local variablesclock=, fake clock,freeze_time/freezegun/time_machine, a patchedmonotonic/perf_counter)The scan parses a file only after a byte-level prefilter matches a budget-like name followed directly by a small literal. I checked this against a full parse of every file: both return the same 106 findings, so the prefilter drops no hits. The ratchet test takes about 0.45 s.
The scan reads the whole test tree, so following
tests/README.mdit is markedslowand added totests/slow_guardrail_manifest.txt. TheBackend unit guardrailslane runs it on every full-CI run, which includes all same-repo PRs. A selection-based unit lane would only run it when this file changes.How to fix a new offender
_pipeline_expiring_the_handler_budgetintest_sync_cloud_tasks.py).asyncio.Eventthat is never set, and keep the budget at 0.5 s or more.Allowlist policy
backend/tests/unit/real_clock_budget_allowlist.txthas 106 entries across 34 files. Each entry has the formpath::qualname::name=value # TODO(owner): #22767 reason. Line numbers are not part of the key, so unrelated edits do not churn the list. The owner is the git-blame author of the line that set the value.Verification
Layer: unit tests only, run in a local worktree at the PR head.
.github/scripts/deferred-work-marker-count.py --check-newpasses because every new allowlist marker cites #22767.Product invariants affected
none
Failure class (fixes)
No
fix:commits; no declaration is required.🤖 Generated with Claude Code