Repository navigation
hotfix(sanitizer): the key test was still quadratic — one call below the #1670 fix (#2398) - #2406
Conversation
…1670 fix (#2398) HOTFIX ONTO MAIN: the burn is happening on client instances, which run main. Both sanitizer copies on main carry the vulnerable code, and the agent copy's _is_sensitive_kv_key sits at line 150 — exactly the line in every py-spy dump. A py-spy watchdog caught this 14 times across three agents (cmo, copywriter, cornelius), every dump on the same stack: <genexpr> (credential_sanitizer.py) <- the any(...) in this function _is_sensitive_kv_key _redact_kv_match -> sanitize_text -> sanitize_dict (recursive) sanitize_subprocess_line -> read_stdout (headless_executor) #1670 made the LINE scan linear (#1661) and left the KEY test quadratic: re.search(r'(?:.*TOKEN.*)\Z', key) retries the leading .* from every offset, O(n^2) in key length. Measured on main's tree, Python 3.13: backend copy (13 patterns): 44 KB key 40.9s -> 0.00035s (116,000x) agent-server copy (30 patterns): 44 KB key 44.4s -> 0.00072s ( 62,000x) Forty seconds of CPU for ONE key, per match, per line, on a thread holding the GIL. That is the pegged core, and why the event loop stopped accepting. What made a quadratic test look harmless was a wrong docstring. It called the key "a short KEY= name". It is not: the key is whatever preceded an "=" in _KV_LINE_RE's unbounded capture — and the dumps show it arriving from stream-json tool RESULTS through recursive sanitize_dict, so multi-KB "keys" are the normal case rather than an adversarial one. Every pattern is ".*LITERAL.*" or "LITERAL.*", and under .search() with a trailing \Z both mean exactly "the key CONTAINS this literal" — so the test is substring containment. Linear, C-level, no backtracking. VERDICTS ARE UNCHANGED, which is the half that mattered: a faster check that redacts LESS is a credential leak. Pinned against the old implementation as an oracle over 17,172 keys across both copies (7,566 + 9,606), zero disagreements, including the deliberate #1670 suffix semantics (DB_ still redacts MY_DB_PASSWORD). The literals are DERIVED from the patterns, and the derivation REFUSES anything that is not a plain literal, so a future pattern needing real regex fails loudly at import rather than being silently reduced to a check that redacts less. BOTH copies (Invariant #5) — vendored in shape, not byte-identically: the agent list is SENSITIVE_VAR_PATTERNS with 30 entries to the backend's 13. Every dump was taken in the AGENT copy, so a backend-only fix would have left all 14 burns exactly where they were. Existing agents need a base-image rebuild. 704 passed across the sanitizer, #1661 and #1670 suites on main. Related to #2398 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Findings from building this against
|
| old | new | ||
|---|---|---|---|
| backend copy (13 patterns), 44 KB key | 40.9 s | 0.00035 s | 116,000× |
| agent copy (30 patterns), 44 KB key | 44.4 s | 0.00072 s | 62,000× |
Growth is textbook quadratic on the way up — 500 ch: 0.003 s · 1 K: 0.013 s · 2 K: 0.063 s · 4 K: 0.32 s. Forty seconds for one key, per match, per line, on a thread holding the GIL.
4. Why my #1670 review missed it — a docstring, not the regex
The function said key was "a short KEY= name". It is whatever preceded an = in _KV_LINE_RE's unbounded ([^\s"'=]+), and the dumps show it arriving from stream-json tool results through recursive sanitize_dict. So multi-KB "keys" are the normal case, not an adversarial one. I measured the cost of the wrong input in #1670 and concluded the key test was cheap.
The guard added here is the one that change should have carried: the literals are derived from the patterns, and the derivation refuses anything that is not a plain literal, so a future pattern needing real regex fails at import rather than being silently reduced to a check that redacts less.
5. Equivalence was the expensive half, and worth it
A faster check that redacts less is a credential leak, so the old implementation is used as an oracle: 17,172 keys across both copies (7,566 + 9,606), zero disagreements — random keys plus targeted cases built from every pattern fragment, and the deliberate #1670 suffix semantics (DB_ still redacts MY_DB_PASSWORD). 704 passed across the sanitizer, #1661 and #1670 suites on main.
What this does not close
Stated because the issue is right to separate them, and because merging this will make them less visible, not fixed:
- Zombie
schedule_executionsrows — 3 rowsrunningwithclaim_token=NULLand no worker. - No
HEALTHCHECKon the agent image, so Docker will not restart a wedged container; the DORMANT breaker files an operator-queue alert that is silent until a human acknowledges it. The burn is what made both observable.
Next steps
- A base-image rebuild is required before the fleet sees any of this — the burn is in the agent copy. Keep
max_parallel_tasks 10→5andexecution_timeout 3600→1800until the rebuilt image is out. devhas the identical bug and gets it via the main→dev back-merge, which will likely need a manual resolution on these two diverged files. A dev-based branch already exists (fix/2398-sanitizer-key-redos, PR fix(sanitizer): the key test was still quadratic — one call below the #1670 fix (#2398) #2405 closed as superseded) if a separate PR is preferred.- Keep the py-spy watchdog running through the first night on the rebuilt image — 14 dumps on one stack is what turned four plausible hypotheses into one answer, and it is the only thing that will confirm the burn is actually gone rather than moved.
/review Report — self-reviewBranch: Critical Findings — 1 found, fixed in
|
…f-review) Two findings from reviewing my own diff. [C1] The derivation guard used `re.escape(body) != body` to mean "is this a plain literal". `re.escape` also escapes `-`, which is NOT a metacharacter outside a character class — so adding a perfectly literal pattern like `.*API-KEY.*` (or `X-AUTH-TOKEN.*`, a header-shaped name) would have raised at import. This module is imported everywhere, so that is a boot crash for the whole platform on a benign pattern addition. Loud, but "loud" there means "nothing starts". Replaced with an explicit safe set, [A-Za-z0-9_-]+, which accepts every current pattern and any plausible env-var or header name while still refusing real metacharacters: `A.B` and `TOKEN+` remain rejected, pinned by tests. [I2] `_sensitive_key_re` in the backend copy compiled the very regexes this change stopped using, and nothing referenced it any more. Dead code is a style note anywhere else; here it is the specific artifact that let this bug survive #1670 — a module-level name that looks like the live check and is not, sitting next to the one that is. Removed, with a test asserting neither it nor _SENSITIVE_KEY_SUFFIX_RE comes back. Also verified during the review, and worth recording as NOT findings: the agent copy's other two uses of the pattern list (`_sensitive_var_re` in `get_credential_values`) run `.match()` against ENV VAR NAMES — anchored at offset 0 and genuinely short — so they are not a third instance of the `.search`-every-offset shape. And the old/new verdicts were re-checked for Unicode divergence (ligatures, dotless i); none observed. 706 passed. Equivalence re-run after the change: 7,566 backend + 9,606 agent keys, zero disagreements. Related to #2398 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
45034f1 to
506e6b3
Compare
… review pass 2) Third self-review finding, and it is in the guard again. `_literal_from_pattern` validated that the body is a plain literal but never that the pattern kept its TRAILING `.*` — and the trailing wildcard is exactly what makes containment equivalent. Under `.search()` the old form was `(?:BODY)\Z`, anchored at the END, so a pattern without it meant "the key ENDS WITH this". Containment is wider: a bare `TOKEN` would stop matching only `MYTOKEN` and start matching `TOKEN_SUFFIX` as well. No shipped pattern is affected — all 13 backend and 30 agent patterns end in `.*`, now asserted by a test — and the drift redacts MORE, so it was never a leak. It is refused anyway, because refusing SILENT changes of meaning is this function's entire job. Tolerating one inside it would be the same internal inconsistency that produced #2398: a stated contract that no longer described the code beneath it. 708 passed. Equivalence unchanged: 7,566 backend + 9,606 agent keys, zero disagreements. Related to #2398 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
/review — pass 2Branch: Pass 1's two findings are fixed and verified. This pass found two more, both in code this PR introduced, and one of them is the third consecutive finding inside the same twelve-line guard. [C2] The stray submodule bump — third time this session, so the cause is mine and mechanicalThe diff carried Cause is not carelessness in the abstract, it is one command: [C3] The guard validated the LITERAL but not the FORM
No shipped pattern is affected — all 13 backend and 30 agent patterns end in Checked clean this pass
Summary
The honest read on this PR: the sanitizer fix itself has been right since the first commit and is well covered — 17,172-key equivalence oracle, both copies, measured 60,000–117,000×. Every finding across both passes has been in the scaffolding I added around it, and three of the four were in the twelve-line guard whose purpose is to stop the next person repeating my #1670 mistake. A guard is code, it gets the same scrutiny as the fix, and on this evidence it deserved more of it than the fix did. Unchanged and still required before any of this helps a client: the base-image rebuild (the burn is in the agent copy) and the main→dev back-merge across two diverged files. |
After this merges — what the operator of an affected instance has to doWritten for whoever runs the burning instance. Deploying the backend alone changes nothing for them, so the order below matters more than usual. The trapEvery py-spy dump was in And a rebuilt image is not adopted by a restart. On (Checked while writing this: the stop→start itself is safe on Steps
What this does NOT fixStated plainly because merging it makes both less visible, not resolved:
Both deserve their own issues; they are not this PR's scope, and they were the reason a CPU burn took 48 hours and a human poking around to notice. |
webmixgamer
left a comment
There was a problem hiding this comment.
Approved — verification notes
Reviewed against main (0cb3a4e2, the branch's exact base). Everything below was re-derived independently rather than taken from the PR body.
Verified
- Verdicts unchanged. Old implementation as oracle over ~27.5k keys across both copies: the only divergences are newline-bearing keys, which now redact more — and they are unreachable, since
_KV_LINE_RE's[^\s"'=]+cannot capture a newline. End-to-endsanitize_textdifferential (old vs new) over 1,510 generated lines × both copies: 0 output differences. Same result on Python 3.9, 3.12; the PR's own oracle test ran green on 3.13 in CI. - Quadratic reproduced, linear confirmed. 1 KB → 4 KB → 16 KB: 0.022s → 0.36s → 5.8s (×16 per ×4). New path: 8.5 → 85 µs.
- Import-safe. All 13 backend + 30 agent patterns pass the derivation; both modules import clean. No third
.search-per-offset instance — the remaining_sensitive_var_reuses are anchored.match()on env-var names. - Nothing dangling. Zero references to the removed names at the PR head;
main's enterprise submodule pin does not import the sanitizer at all.
Back-merge to dev — easier than the body says
Trial-merged this branch into origin/dev: both sanitizer files auto-merge cleanly, dev keeps its #2208 sk- consolidation and gains the fix, and the full sanitizer/credential suite (498 tests) passes on the merged tree. The only conflict is the routine enterprise gitlink. The standard main → dev back-merge is sufficient; no separate dev PR needed.
CI: the cancelled pytest (head, seed 99999) shard is not a failure
It hit the 25-minute job ceiling at 54% while still progressing — no test failed, no per-test timeout fired, no JUnit was produced. Timing profile vs the three healthy shards (base and head alike: ~740s, 2 stalls >30s, max ~122s — the pre-existing 60s / 40s waits in test_start_agent_skip_inject and test_1083_result_callback::TestPersistResend, identical on both sides): the cancelled shard hit 14 stalls >30s starting at 1%, before the suite had meaningfully run. The 25 new tests total 0.25s in CI. That is an order-sensitive stall in pre-existing tests on paths this diff does not touch, surfaced by the shuffle over a 25-item-larger collection. regression diff handled it as designed ("Degraded — proceeding on surviving seeds"): no new failures. Locally, head and main at seeds 12345 and 99999 are all clean, delta exactly the 25 new tests. Worth a gh run rerun --failed for a clean record.
Before merging (process, not code)
- Issue disposition. Merging to
mainruns no status automation (issue-status-on-merge.ymlisdev-only), and the body saysRelated to #2398, notFixes. As written, #2398 stays open andstatus-in-progresswith no record the fix shipped. EitherFixes #2398+ file the two residuals (zombierunningrows; missing agentHEALTHCHECK) as their own issues, or keep it open deliberately and set the label by hand at the tag. - Priority. P-07 hotfix-to-
mainis scoped to P0; the issue is labelled P1. Relabel, or note the exception so this isn't read later as a process bypass. - Rollout is what actually fixes the fleet. The burn is in the agent copy, baked into the base image; nothing rebuilds it on merge. Tag → base-image rebuild → deploy → recreate agents (cold start adopts the new image;
POST /api/ops/fleet/restartcovers a running fleet). Keep themax_parallel_tasks/execution_timeoutmitigations until that lands, and keep the py-spy watchdog running through the first night.
Minor
- Squash title carries
hotfix(while the commits usefix(; conventional prefix isfix(. - The agent-copy parity test is a source grep, not an import — it would not catch the
NameErrordescribed in the write-up. It is covered today only becausetest_1661exec_modules the copy; worth strengthening on thedevside.
…otfix `main` carried five commits that never came back to `dev`, and the one that matters is the Abilityai#2398 hotfix (Abilityai#2406): `_is_sensitive_kv_key` was still `re.search(r'(?:.*TOKEN.*)\Z', key)`, quadratic in key length, on a thread holding the GIL. Measured 0.32s at 4 KB and 40s at 44 KB; a py-spy watchdog caught it 14 times across three agents. `key` is whatever preceded an `=` in `_KV_LINE_RE` and is unbounded, and recursive `sanitize_dict` reaches it from stream-json tool results — so multi-KB keys are the normal case, not an adversarial one. Found by /release pre-flight while cutting v0.9.5-rc1. That RC becomes the DigitalOcean Marketplace snapshot (Abilityai#2281/Abilityai#2471), so tagging `dev` as-is would have shipped a known, production-observed DoS in a public image. Each branch had a sanitizer fix the other lacked, which is why this is a merge and not a cherry-pick in either direction: `dev` has the Abilityai#2208 `sk-` family consolidation (`sk-svcacct-` and anything after it), `main` has the Abilityai#2398 containment rewrite. Both are present on both copies after the merge, verified by grep and by the 195 tests across the five sanitizer suites. Conflict resolution, for the record: - `src/backend/utils/credential_sanitizer.py` and its agent-server sibling both auto-merged cleanly. They are NOT byte-identical vendored twins — the Invariant Abilityai#5 mirror set is credential_paths / model_context / safe_yaml / mcp_validator — so no parity obligation attaches and the independent merges are legitimate. - `src/backend/enterprise` resolved to **dev's** pin (90f2f2cb), which is three commits AHEAD of main's (2a5def35) and has it as an ancestor — verified, not assumed. Taking main's would have rolled the paid tree backwards. Verified: 195 tests pass across test_2398 / test_2208 / test_1661 / test_credential_sanitizer_{agent,backend}; alembic version line still resolves to exactly 1 head (0049); the merge touched no migration on either track. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01K9bL6DZ8QVyrSvPybp5ZuK
…#2880) /release Step 10b-2. The payload is bcf6711..b422f26 (405 commits). The v0.9.0..dev count (877) included pre-v0.9.0 dev history that the v0.9.0 squash does not reach. Records #2876, the two partial issues (#2281, #2238) and the #2406 hotfix, and corrects the dependabot count and the contributors line. Co-authored-by: sim <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
This is my regression. #1670 fixed the catastrophic backtracking in the credential sanitizer's line scan (#1661) and left the identical shape one call deeper, in
_is_sensitive_kv_key. Every one of the 14 py-spy dumps is on that stack.The cost
re.search(r'(?:.*TOKEN.*)\Z', key)retries the leading.*from every offset — O(n²) in key length. Measured on 3.13:Forty seconds of CPU for one key, per match, per line, on a thread holding the GIL. That is the pegged core, and it is why the event loop stopped accepting.
Why a quadratic test looked harmless
A wrong docstring. It described
keyas "a shortKEY=name". It is not — the key is whatever preceded an=in_KV_LINE_RE's unbounded([^\s"'=]+). And the stack above reaches it from stream-json tool results through recursivesanitize_dict, so multi-KB "keys" are the normal case, not an adversarial one. That single wrong assumption is what let the quadratic survive the #1670 review.The fix
Every pattern is
.*LITERAL.*orLITERAL.*. Under.search()with a trailing\Z, both mean exactly "the key contains this literal" — so the test is substring containment: linear, C-level, no backtracking.Verdicts are unchanged, and that was the part to get right — a faster check that redacts less is a credential leak. Pinned against the old implementation as an oracle: 17,172 keys across both copies (7,566 + 9,606), zero disagreements, including the deliberate #1670 suffix semantics (
DB_still redactsMY_DB_PASSWORD).The literals are derived from the patterns and the derivation refuses anything that is not a plain literal — so a future pattern needing real regex fails loudly at import instead of being silently reduced to a check that redacts less. That is the guard #1670 should have had.
Both copies — and the agent one is the one that matters
Invariant #5. The two files are vendored in shape, not byte-identically: the agent list is
SENSITIVE_VAR_PATTERNSwith 30 entries to the backend's 13. Every py-spy dump was taken in the agent copy, so a backend-only fix would have left all 14 burns exactly where they were. A test asserts the agent copy carries the fix.What this does and does not close
schedule_executionsrows or the missingHEALTHCHECKon the agent image (no auto-recovery). Those are real and separate; the burn was making them visible.max_parallel_tasks10→5,execution_timeout3600→1800) cap blast radius and are still worth keeping until this ships to the fleet — note the agent copy means a base-image rebuild is required for existing agents.Test Plan
tests/unit/test_2398_sanitizer_key_redos.py— verdict equivalence against the old implementation, the fix(sanitizer): linear KEY=value redaction — the #1661 CPU spin is the regex, not the pipe #1670 suffix semantics, linearity at 64 KB, end-to-endsanitize_texton a 44 KB token, the derivation's refusal of a non-literal pattern, and the agent-copy parity assertionmain's tree: 7,566 backend + 9,606 agent keys, 0 disagreements704 passedacross the sanitizer, bug: agent-server leaks a busy-spinning reader thread (100% CPU) on stdout-pipe-race / drain deadlock — #728 fix incomplete #1661 and fix(sanitizer): linear KEY=value redaction — the #1661 CPU spin is the regex, not the pipe #1670 suites onmainRelated to #2398 · follow-up to #1670 / #1661
Getting it to
devdevhas the identical bug in files that have since diverged frommain, so the standard main→dev back-merge is the route — and it will likely need a manual resolution on these two files. I have a dev-based version of the same change ready if you would rather have it as its own PR; say which you prefer and I will close the other.