Skip to content

test(backend): ratchet tiny real-clock budgets in tests - #22797

Merged
Git-on-my-level merged 3 commits into
mainfrom
ramp-tooling/clock-budget-ratchet
Oct 20, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
ramp-tooling/clock-budget-ratchet

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

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:

This 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.py is a pure static ast scan of backend/tests/**/*.py. It imports none of the code under test. It flags a literal value with 0 < value < 0.5 seconds when the name matches budget|deadline|timeout (case-insensitive) and the value is set in one of these ways:

  • attribute assignment: module.X_BUDGET_SECONDS = 0.05
  • setattr / monkeypatch.setattr / patch.object / patch('pkg.mod.X', 0.05 | new=0.05)
  • env-backed budgets: monkeypatch.setenv, os.environ[...] = '0.05', patch.dict(os.environ, {...})
  • keyword arguments passed to code under test: drain_tasks(..., timeout=0.1), Budget(deadline_seconds=0.01)

It does not flag:

  • harness waits that only bound the test itself (asyncio.wait_for, Event.wait, Queue.get, Thread.join, Future.result, Lock.acquire)
  • mock call assertions and Redis client construction
  • sleep calls and plain local variables
  • anything inside a function that visibly controls the clock (clock=, fake clock, freeze_time / freezegun / time_machine, a patched monotonic / 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.md it is marked slow and added to tests/slow_guardrail_manifest.txt. The Backend unit guardrails lane 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

  1. Inject or patch the clock so the budget expires deterministically, or make the stub itself expire the budget (see _pipeline_expiring_the_handler_budget in test_sync_cloud_tasks.py).
  2. If the test only needs the timeout path, block the stub on an asyncio.Event that is never set, and keep the budget at 0.5 s or more.
  3. Otherwise raise the budget to 0.5 s or more.

Allowlist policy

backend/tests/unit/real_clock_budget_allowlist.txt has 106 entries across 34 files. Each entry has the form path::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.

  • A new offender fails the ratchet.
  • An entry that no longer matches anything fails as stale. Delete it when you fix the test.
  • Malformed entries, duplicates, or entries without an owner fail.
  • Do not add entries for new tests.

Verification

Layer: unit tests only, run in a local worktree at the PR head.

cd backend
BACKEND_FAST_UNIT_FAIL_SECONDS=1.0 BACKEND_PYTEST_MARK_EXPR="slow and not integration" \
  BACKEND_UNIT_TEST_FILE_LIST=<list with tests/unit/test_real_clock_budget_ratchet.py> bash test.sh
# 11 passed (self-tests include every spelling the review found)
PYTHON=.venv/bin/python bash scripts/run-slow-guardrails-ci.sh
# 2043 passed, 1325 deselected in 195.06s (whole slow-guardrail lane, including this file)
BACKEND_UNIT_TEST_FILE_LIST=<same list> bash test.sh
# default PR lane: file deselected as slow, treated as skipped, exit 0
python scripts/check_unit_test_discovery.py
# unit test discovery OK, 0 orphans

.github/scripts/deferred-work-marker-count.py --check-new passes 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

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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T08:27:18.996047Z 71557b7 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +217 to +219
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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +101 to +105
'wait',
'get',
'join',
'result',
'acquire',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +285 to +287
def test_no_new_tiny_real_clock_budgets() -> None:
allowed = {entry for entry, _ in load_allowlist()}
new = sorted(scan_tree() - allowed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +89 to +90
_PREFILTER = re.compile(
rb'(?:budget|deadline|timeout)\w*[\'"]?\]?\s*[=,:]\s*(?:\w+\s*=\s*)?[\'"]?(?:0*\.\d|\d+(?:\.\d*)?e-\d)'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +174 to +175
source = '\n'.join(self.lines[node.lineno - 1 : node.end_lineno]) # type: ignore[attr-defined]
self.clock_controlled = bool(_FAKE_CLOCK.search(source))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +235 to +239
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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +135 to +137
def _number(node: ast.AST, *, allow_str: bool) -> Optional[float]:
if not isinstance(node, ast.Constant):
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +245 to +246
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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +203 to +204
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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 71a76f4 into main Oct 20, 2026
56 checks passed
@Git-on-my-level
Git-on-my-level deleted the ramp-tooling/clock-budget-ratchet branch October 20, 2026 08:38
Git-on-my-level added a commit that referenced this pull request Oct 20, 2026
…er tests

#22797's ratchet requires the list to shrink when its tests go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 21, 2026
#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant