Skip to content

[AI-3612] Redact encoded keys and invalid-key messages - #2238

Merged
kanat merged 15 commits into
mainfrom
kanat/ai-3612-safelogtext-shapes
Nov 23, 2026
Merged

kanat merged 15 commits into
mainfrom
kanat/ai-3612-safelogtext-shapes

Conversation

@kanat

@kanat kanat commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Why

store.SafeLogText (and RedactLogText) let two credential shapes through, found in the round-1 review of #2212 (R1.5) and ticketed as AI-3612:

  • a URL-encoded key with no ? or & before it: key%3D<hex> (also api_key%3D, token%3D, %3d);
  • a vendor refusal that names the key with no = or :: Invalid API key <32 hex>, or with the key before the verdict: The API key '<32 hex>' is invalid.

The text reaches the model/speech/tool timing lines, the agent failure log and requests.error_message, all through SafeLogText.

How it works

Three rules in acceleration/internal/store/logs.go, run with the other keyword rules in redactLegacyCredentials (so the existing mayHoldCredential gate already covers them: both texts hold key or token). redactCredentials now runs the shaped rules (JWT, Slack, GitHub...) before the keyword rules, so a keyword rule that takes only part of a shaped token (a JWT after Invalid API token, up to its first dot) cannot leave the rest in a shape no rule matches.

Rule Takes out Keeps
encodedCredential the value after a name plus %3D (any case, once or twice encoded). key, token, id_token need a boundary before them: the text start, a character that is not a letter, digit or underscore, %XX or %25XX, \n or \uXXXX. The names credentialText takes (api_key, access_token, refresh_token, auth_token, private_key, password, secret, _id_token) match wherever they stand, camel case included (accessToken, clientSecret) the name and boundary; monkey%3D1, keys%3D1, max_token%3D256, sort_key%3Ddate, key%3D with no value
vendorKeyBefore the same 16+ character key between API key/API token and is/was invalid/incorrect, in single quotes, double quotes (raw or JSON-escaped \") or none the phrase and quotes; a word, an id of 15 or fewer characters, any other verdict (is set)
vendorKeyMessage the 16+ character key (letters, digits, _ - + / =) after Invalid/Incorrect + API key/API token/x-api-key/invalid_api_key, with an optional provided, : and quote (raw or JSON-escaped) the phrase; a word after it (authentication_failed_error), a short id (Invalid API key. Request id 01234567), a text with no key

Incorrect API key provided: sk-... was already redacted by providerCredential; a row pins it.

before: Invalid API key 0123456789abcdef0123456789abcdef
after:  Invalid API key [redacted]

before: request failed: key%3D0123456789abcdef0123456789abcdef tail
after:  request failed: key%3D[redacted] tail

No ClickHouse view change: no new msg and no new field.

Changes

  • acceleration/internal/store/logs.go: the three rules, redactVendorKeyMessage (word check per match, as redactUnlessWord does), and the shaped rules moved before the keyword rules in redactCredentials.
  • acceleration/internal/store/logs_test.go: TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut (whole-output rows, each also run a second time for idempotence) and two rows in TestEveryTextARuleRedactsPassesTheCheck.

Validation

  • go test ./internal/store/ ./internal/llmrouter/ ./internal/sttrouter/ ./internal/ttsrouter/: pass; go vet, gofmt: clean.
  • The rows with nothing to redact pass on base 31fd2dd too (control); every redaction row except the ones already covered fails there.
  • Mutations of the three patterns, their boundaries, names, value class, floor, output templates, the per-match word check and the rule order: all killed but one equivalent (swapping encodedCredential and vendorKeyMessage, whose matches cannot overlap).
  • False-positive sweep, base vs head: SafeLogText over every Go string literal of acceleration/ and every repo text line with key/token/secret/password/invalid/incorrect (261k items). Only this PR's test fixtures change.

🤖 Generated with Claude Code

kanat and others added 3 commits November 23, 2026 17:40
…ssage

SafeLogText missed key%3D<hex> (the encoded name with no ? or & before
it) and a vendor refusal such as 'Invalid API key <hex>'. Two rules in
store/logs.go take them out; the rest of the text stays.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The API key '<key>' is invalid (single, double or no quotes) kept the key.
vendorKeyBefore covers it with the 16 character floor of vendorKeyMessage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[security R1] NO-GO

No new entry point: the change is the redaction filter that router log lines (RedactLogAttr), stored error fields (SafeLogText) and Sentry events share. No logged path skips it. Of the shapes base redacts, one now leaks: S1.1. The others below are gaps in the shapes this PR says it covers.

  • [Blocker] S1.1: a regression on a credential shape that base redacts whole (inline).
  • [Should fix] S1.2: a quoted key after the vendor phrase, and the JSON-escaped quote form in both vendor rules (inline).
  • [Should fix] S1.3: camelCase compound names in encodedCredential (inline).
  • [Nit] S1.4: a twice-encoded separator before the name (inline).
  • [Nit] S1.5: a key with +, / or = after the vendor phrase is cut short and its tail stays (same place as S1.1).

I spot-checked 7 mutations of the new rules. The PR's tests caught all 7.

The fixer gets ready test rows for each finding through the ticket.

text = urlCredential.ReplaceAllString(text, "${1}[redacted]@")
text = queryCredential.ReplaceAllString(text, "${1}[redacted]")
text = encodedCredential.ReplaceAllString(text, "${1}${2}[redacted]")
text = redactVendorKeyMessage(vendorKeyMessage, text)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Blocker] S1.1 This rule runs in redactLegacyCredentials, which runs before the shaped rules (redactCredentials, L204). Its key class stops at the first .. When a JWT follows the vendor phrase, the rule takes only the header, and the JWT shape rule (L82) then has nothing to match. The token's payload and signature stay in the log line and the stored field. Base redacts the same text whole. Fix: in redactCredentials, run the shapedCredentials loop before redactLegacyCredentials. I tried that and the store suite still passes; it guards every legacy rule against cutting a shaped token. Another fix is a . in the key class of vendorKeyMessage (L119). Add rows that put a fake JWT after each phrase form and expect the whole token to be [redacted]. S1.5 is here too: with +, / or = in a key, the tail after that character stays.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 4157657: redactCredentials runs the shaped rules first, then the keyword rules. Test: TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut rows "jwt after the phrase" and "jwt after the phrase and a colon". Mutation (old order back): both rows fail.

Comment thread acceleration/internal/store/logs.go Outdated
// the same for an API token. The key is the 16 characters or more of the key alphabet after the
// phrase, so a request id of 8 hex digits after "Invalid API key." stays. The phrase stays and
// the key is taken out, unless it is a word (see redactVendorKeyMessage).
var vendorKeyMessage = regexp.MustCompile(`(?i)\b((?:invalid|incorrect)[\s_-]+(?:x-)?api[\s_-]?(?:key|token)\b(?:\s+provided)?\s*[:=]?\s*)([A-Za-z0-9_-]{16,})()`)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] S1.2 A key in quotes after the phrase is not matched: single quotes, double quotes, and a quote escaped as \". vendorKeyBefore (L124) also misses the escaped quote. A provider's message usually reaches the error string inside a JSON body, where every quote is escaped, so the double-quote rows in the tests do not cover the common case. Fix: allow an optional \\?["\x27] before the key here, and \\?["\x27]? in both quote slots of vendorKeyBefore. Add rows for each form: the key becomes [redacted] and the quotes stay.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 4c74f59: optional \\?["'] before the key in vendorKeyMessage, and in both quote slots of vendorKeyBefore. Test: TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut rows "single-quoted key after a colon", "double-quoted key after the phrase", "json-escaped quote after the phrase", "json-escaped quotes before the verdict". Mutations (no quote; no escaped quote in each of the 3 slots): each fails a row.

Comment thread acceleration/internal/store/logs.go Outdated
// and is kept (see shapeStart). The value is read as queryCredential reads it, whatever its
// length: a parameter named key is a key. A name with a plain = is the rule of credentialText
// and queryCredential.
var encodedCredential = regexp.MustCompile(`(?i)(^|[^A-Za-z0-9]|%[0-9A-Fa-f]{2}|\\[a-z]|\\u[0-9A-Fa-f]{4})((?:apikey|key|token|password|secret)%(?:25)*3D)[^&\s"\x27#\\]+`)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] S1.3 The comment says the names are the ones credentialText takes. Here the name must follow a character that is not a letter or digit, so an encoded camelCase compound still passes: accessToken, clientSecret, authToken, refreshToken, privateKey. credentialText (L19) takes all of them with a plain =. Fix: list the compounds in the name group as credentialText does (access_?token, refresh_?token, auth_?token, id_?token, client_?secret, private_?key, api_?key). Add a redaction row per name and keep the monkey%3D control.

[Nit] S1.4 The boundary takes one %XX, so a separator encoded twice (%2522, %2520) right before the name hides it, though %253D is handled. Fix: use %(?:25)*[0-9A-Fa-f]{2} in the boundary group, plus one row for it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in cb259ba, reshaped in ec23bb8 (R1.4): the compound names credentialText takes match wherever they stand, camel case included. Test: TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut rows "camel case accessToken / clientSecret / authToken / refreshToken / idToken / privateKey / apiKey", "id_token after a prefix". Mutations (drop each name): each fails its row.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewed d9f50ea merged onto main eaaf409. Suites ./internal/store ./internal/llmrouter ./internal/sttrouter ./internal/ttsrouter pass; vet and gofmt clean. CI on this draft head runs nothing yet (go and integration skipping; runs at gh pr ready).

Checked and sound: false positives. SafeLogText, base vs head, on 54k string literals of acceleration/**/*.go and 40k repo lines holding key/token/secret/password/invalid/incorrect: the only changes are this PR's own test fixtures. No real vendor message in the repo changes. Performance is linear (RE2): 100 KB-1.6 MB inputs of a, api key repeats, long keys and key%3D repeats take 40-160 ms per 100 KB (base 30-50 ms); no backtracking. The new rows fail on base (34 fail, the rest are controls or rows base rules already cover). The author's 53 mutants all die.

[Nit] R1.3 Other shapes of the same refusal still leak, same on base: a verdict other than invalid/incorrect (API key <hex> has expired, is not valid, was revoked), brackets or parentheses around the key (Invalid API key (<hex>)), Invalid token <hex> with no API, token%3A<hex>, api_key\u003d<hex>. Open-ended family: ticket it, do not widen this PR.

[Nit] R1.4 Five mutants only widen redaction and survive (no keep-row pins them): drop the leading \b of vendorKeyMessage or of vendorKeyBefore; [\s_-]+ -> [\s_-]* in vendorKeyMessage; \s+ -> \s* before the verdict or after key in vendorKeyBefore. Also max_token%3D256 and sort_key%3Ddate now lose their values (the name boundary counts _). Harmless for secrecy; a keep row each if the author wants them pinned.

Verdict: request changes, for R1.1 and R1.2 (inline).

// is a word, as redactUnlessWord does, such as authentication_failed after "invalid_api_key".
func redactVendorKeyMessage(rule *regexp.Regexp, text string) string {
return rule.ReplaceAllStringFunc(text, func(match string) string {
parts := rule.FindStringSubmatch(match)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] R1.1 Mutant survives and it is a leak: rule.FindStringSubmatch(match) -> rule.FindStringSubmatch(text) passes the whole suite. Under it the first match's parts are used for every match, so Invalid API key authentication_failed_error; Invalid API key <32 hex> keeps the key (and the reverse order redacts the word). No test row has two matches in one text, so nothing pins that each match is judged on its own value.

Add to the main table of TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut (checked: all three fail under the mutant, pass on head):

  • "word then key": "Invalid API key authentication_failed_error; Invalid API key " + secret -> "Invalid API key authentication_failed_error; Invalid API key [redacted]"
  • "key then word": "Invalid API key " + secret + "; Invalid API key authentication_failed_error" -> "Invalid API key [redacted]; Invalid API key authentication_failed_error"
  • "before: word then key": "API key authentication_failed_error is invalid; API key " + secret + " is invalid" -> "API key authentication_failed_error is invalid; API key [redacted] is invalid"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in f50dcdc: the reviewer's three rows added ("word then key", "key then word", "before the verdict, word then key"). Mutation FindStringSubmatch(match) -> (text): "word then key" and "key then word" fail.

Comment thread acceleration/internal/store/logs.go Outdated
// the same for an API token. The key is the 16 characters or more of the key alphabet after the
// phrase, so a request id of 8 hex digits after "Invalid API key." stays. The phrase stays and
// the key is taken out, unless it is a word (see redactVendorKeyMessage).
var vendorKeyMessage = regexp.MustCompile(`(?i)\b((?:invalid|incorrect)[\s_-]+(?:x-)?api[\s_-]?(?:key|token)\b(?:\s+provided)?\s*[:=]?\s*)([A-Za-z0-9_-]{16,})()`)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] R1.2 The key is not redacted when the vendor quotes it after the phrase: Invalid API key '<32 hex>', Invalid API key: '<32 hex>', Incorrect API key provided: "<32 hex>" come out unchanged (probed on head). vendorKeyBefore takes single, double and no quotes; this rule takes none, so the same refusal leaks by one quote character. Same class as R0.1.

Fix, checked in a scratch copy (store suite passes): \s*[:=]?\s*) -> \s*[:=]?\s*["\x27]?) in vendorKeyMessage. Rows to add to the main table (fail on head, pass with the fix, second pass unchanged):

  • "Invalid API key '" + secret + "'" -> "Invalid API key '[redacted]'"
  • "Invalid API key: '" + secret + "'" -> "Invalid API key: '[redacted]'"
  • `Incorrect API key provided: "` + secret + `"` -> `Incorrect API key provided: "[redacted]"`
    and a keep row "Invalid API key '" + secret[:15] + "'".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed with S1.2 in 4c74f59: Invalid API key '<k>', Invalid API key: '<k>' and the double-quoted forms redact the key and keep the quotes. Test: TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut rows "single-quoted key after a colon", "double-quoted key after the phrase".

kanat and others added 8 commits November 23, 2026 18:11
A JWT after "Invalid API token" lost only its header: the vendor rule
took the key up to the first dot and the JWT rule then matched nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A key in quotes after the phrase, or in quotes a JSON body escapes
(\"), was kept whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The key class stopped at + / =, so the tail of a base64 key was kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
accessToken%3D, clientSecret%3D and the other compound names with no
separator before the short name kept their value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
%2522key%253D and %2520key%253D kept their value: the boundary took one
encoding only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…oken

max_token%3D256 and sort_key%3Ddate lost their values: an underscore
counted as the boundary before key and token. The compound names are
now taken wherever they stand, as credentialText takes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each match is checked for a word on its own: a word after the first
phrase must not keep the key after the second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kanat

kanat commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Round-1 findings from the review bodies, fixed:

  • S1.4 in aa60c21: the boundary before key/token takes a twice-encoded character (%(?:25)*XX). Test: TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut rows "after a twice-encoded quote", "after a twice-encoded space", "camel case after a twice-encoded ?". Mutation (one encoding only): fails.
  • S1.5 in 5f9df01: the key class of both vendor rules takes + / =. Test: rows "base64 key", "base64 key before the verdict". Mutations (old class; drop each of + / = in each rule): 8 killed.
  • R1.4 in ec23bb8: an underscore is no longer a boundary before key/token; api_key, x_api_key, access_token and the other compound names match as credentialText takes them. Keep rows max_token%3D256, sort_key%3Ddate, valid_token%3D<hex>, and 5 rows for the surviving widening mutants (leading \b of both rules, phrase separator, space after the name, space before the verdict). Mutations: 14 killed.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Delta review, round 2 (d9f50ea -> 2c7a27b): GO. Reviewed on the merged head onto current main. Suites for store, llmrouter, sttrouter and ttsrouter pass. The draft has no CI for go and integration (#2130); CodeQL and labeler pass.

Prior findings

  • S1.1 (JWT after the phrase) fixed. The shaped rules run first. The JWT probe is redacted in all five rows. Swapping the order back fails the "jwt after the phrase" rows.
  • S1.2 and R1.2 (quoted key, escaped quote) fixed. Probe rows P1-P4 went from leak to redacted. Dropping the quote slot fails the double-quoted row.
  • S1.3 (camel-case encoded names) fixed. E3-E5 and E11 are redacted. Camel-case idToken, privateKey and apiKey rows also pass.
  • S1.4 (twice-encoded separator) fixed. E1 and E2 are redacted. A single-%XX boundary fails the twice-encoded rows.
  • S1.5 (base64 key) fixed. P6 and P7 are redacted. Dropping + from the class fails the base64 rows.
  • R1.1 (per-match word check) fixed. The FindStringSubmatch(text) mutant fails; the word-then-key and key-then-word rows hold.
  • R1.4 (over-redaction) fixed. max_token%3D256, sort_key%3Ddate and monkey%3D1 keep their value. The old survivors are killed, and 10 new mutants on the changed regexes are all killed.
  • Probe sweep, 45 rows, base vs new head: 15 rows go from leak to redacted, none from redacted to leak.
  • Repo sweep, 261k items: base vs new head differ only in the test fixtures of logs_test.go.
  • Performance at 100 KB and 1.5 MB, 15 input shapes: linear, and the same as the old head. The second pass leaves the text unchanged (idempotent).

New findings, both Nit, not blocking.

N2.1 over-redacts a name=value glued to the vendor phrase; N2.2 is one row for a surviving order mutant. The other refusal forms stay in the R1.3 ticket.

Comment thread acceleration/internal/store/logs.go Outdated
// "Invalid API key." stays. A quote before the key, or a quote escaped as a JSON body has it
// (\"), stays with the phrase. The phrase stays and the key is taken out, unless it is a word
// (see redactVendorKeyMessage).
var vendorKeyMessage = regexp.MustCompile(`(?i)\b((?:invalid|incorrect)[\s_-]+(?:x-)?api[\s_-]?(?:key|token)\b(?:\s+provided)?\s*[:=]?\s*(?:\\?["\x27])?)([A-Za-z0-9_+/=-]{16,})()`)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Nit] N2.1 — = and / in the key class make the key run swallow a name=value or a path glued to the phrase, so the 16-character floor that keeps a request id no longer holds. Invalid API key provided: model=gpt-4o-mini-transcribe becomes ...provided: [redacted], and Invalid API key: request_id=req_0123456789abcdef loses the id; base and the old head kept both. It over-redacts only, no leak. Fix in both vendor rules: padding at the end only, ([A-Za-z0-9_+/-]{16,}={0,2}). I checked in a scratch copy: the suite passes, the base64 rows still redact, and the two examples keep their text. Rows for the keep table: "Invalid API key provided: model=gpt-4o-mini-transcribe" and "Invalid API key: request_id=req_" + secret[:16].

@kanat kanat Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 2faaf1b (the fix and the two keep rows for the phrase before the key) and 7b53774 (the keep row for the phrase after the key): both vendor rules now take ([A-Za-z0-9_+/-]{16,}={0,2}), so = is only padding at the end. Test: TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut, rows keeps a name=value after the phrase, keeps a request id after the colon, keeps a name=value before the verdict. Reverting the class in either rule fails its rows; the base64 rows still redact. / stays in the class on purpose (base64 keys carry it).

text = urlCredential.ReplaceAllString(text, "${1}[redacted]@")
text = queryCredential.ReplaceAllString(text, "${1}[redacted]")
text = encodedCredential.ReplaceAllString(text, "${1}${2}[redacted]")
text = redactVendorKeyMessage(vendorKeyMessage, text)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Nit, unchanged code] N2.2 — the mutant that runs vendorKeyMessage before encodedCredential survives, and it is not equivalent: the key class (it already held -) can eat the name of an encoded parameter glued to it. In Invalid API key aaaaaaaaaaaaaaaaaaaaaaa-key%3D<secret> head gives Invalid API key [redacted]%3D[redacted], the swapped order leaves the secret. Contrived, but one row pins it: in the redact table, "key run glued to an encoded name", input Invalid API key aaaaaaaaaaaaaaaaaaaaaaa-key%3D + secret, want Invalid API key [redacted]%3D[redacted]. I checked it fails under the swap and passes on head.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 4194e46: row key then an encoded key, in this order (Invalid API key <16 chars>-key%3D<secret> -> Invalid API key [redacted]%3D[redacted]). With vendorKeyMessage run before encodedCredential the row fails (the %3D value leaks); a comment in redactLegacyCredentials says why the order holds.

kanat and others added 4 commits November 23, 2026 19:02
The key class took = anywhere, so 'Invalid API key provided: model=m' lost the model.
= is now only the padding at the end of a base64 key.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@kanat
kanat marked this pull request as ready for review November 23, 2026 19:21
@kanat
kanat merged commit a541581 into main Nov 23, 2026
20 of 21 checks passed
@kanat
kanat deleted the kanat/ai-3612-safelogtext-shapes branch November 23, 2026 19:51
kanat added a commit that referenced this pull request Nov 24, 2026
## Why

`TestTelnyxUnpaidSuite` failed now and then in CI `integration (api)` on
PRs that do not touch scheduled tasks (AI-3655):

- #2229: `TestAThreadTaskWhoseMoneyCannotBeCheckedIsRetried` expected 4
attempts and got 3 (scheduled_unpaid_test.go:170).
- #2238, first attempt: `TestAThreadTaskWhoseSessionEndsMidTurnSettles`
expected the run `delivered` and got `failed`
(scheduled_unpaid_test.go:1133).

Cause: `runSuite` runs every suite with `t.Parallel()` in one process
(router_suite_test.go:152). `ScheduledTasksSuite` and
`TelnyxUnpaidSuite` saved, set and restored package vars that every
router and every worker read. When the save and restore of two suites
interleave, one suite's worker or router runs on the other suite's
value.

| Failure | Value the test set | Value the code read | Evidence |
|---|---|---|---|
| 3 attempts, expected 4 | `retryAtOnce`: 2 waits, so the worker made
1+2 attempts | the assertion read `len(scheduling.DeliveryRetries)`
after the run settled. By then another suite had restored the default 3
waits | CI job log of #2229 |
| run `failed`, expected `delivered` | default 3 min reply window |
`ScheduledTasksSuite.TestAReplyNeverWrittenIsNoReply` sets 1 s | CI log:
attempt 1's held turn is cancelled after 5 s, and attempt 2 runs no
turn. Local base probe: 3 of 3 runs fail |

What happens on the second failure with a 1 s window: attempt 1 stops
reading the reply after 1 s, while the kept session is still closing
(its turn gets a 5 s grace). The two 1 ms retries then fail with
`conversation is already open`, and the run settles `failed` before the
session ends.

```
TelnyxUnpaidSuite            process-wide var          ScheduledTasksSuite
  kept = 3 min ------------> scheduledReplyWindow <---- kept = 3 min, set 1 s
  ...                                          (1 s) <- restored later
  MidTurnSettles reads 1 s
  -> attempt 1 gives up at 1 s, retries hit "conversation is already open"
```

`-race` does not report this race. The suites share log and pool
mutexes, and these give the race detector a happens-before edge (a
`-race` run of both suites on base was clean).

#2229 does not touch any of these vars, and its own CI run failed on
this flake, so it does not fix it.

## How it works

Each value now belongs to one worker or one router. A test sets the
value on its own worker or router, so no other suite sees the change.

| Before (process-wide) | After (per instance) | Default |
|---|---|---|
| `scheduling.DeliveryRetries` | `Scheduler.SetRetries`, unexported
`deliveryRetries` | 30 s, 2 min, 10 min |
| `scheduling.FinishRetries` (new on main, same pattern) |
`Scheduler.SetFinishRetries`, unexported `finishRetries` | 1 s, 2 s, 4 s
|
| `scheduledReplyWindow` var | `Server.replyWindow` (the name stays as a
const default) | 3 min |
| `scheduledPhoneWindow` var | `Server.phoneWindow` | 90 s |
| `scheduledCallLimit` var | `Server.callLimit` | 10 min |
| `resumedAt` var | `Server.resumedAt` | `time.Now` |
| `scheduledPeerWindow()` | `Server.scheduledPeerWindow()` | 21 min 30 s
|

Tests: `retryAtOnce`, `retryLate` and `finishAtOnce` set
`RouterSuite.retries` or `finishRetries`, and the workers the suites
start (`newScheduler`) apply it. The window and clock overrides set the
suite's own `s.router`, as tests already do for `replyPoll`.

Production does not change: `cmd/router/main.go:1677` still calls
`scheduling.NewScheduler`, which takes the same default waits, and
`NewServer` sets the same defaults (asserted in
`TestAPeerIsGivenLongEnoughToRingAndHoldATasksCall`). No log line
changes and no ClickHouse view is affected.

## Changes

- `internal/scheduling/scheduler.go`: `DeliveryRetries` and
`FinishRetries` become unexported, and `SetRetries` and
`SetFinishRetries` are added beside `SetActivity`.
- `internal/api`: the four windows and the clock become `Server` fields,
set in `NewServer`.
- Tests: every override goes to the suite's own router or worker. The 4
attempt assertions read `len(s.retries)`.
`TestACallNobodyPicksUpIsNotAnswered` now also checks that the ring
ended well before the default 90 s. Before, a ring on the default window
still passed, only 90 s later.

## Validation

- Base probe (`TestProbeOverrides`, not committed): a parallel test
saves, sets and restores the globals the way `ScheduledTasksSuite` does.
Beside it, `MidTurnSettles` failed 3 of 3 runs with `delivery_failed` /
`conversation is already open`. The probe cannot build on head: the
globals are gone.
- `MidTurnSettles` alone on base: 10/10 pass, and 10/10 with `-race -cpu
1`. So it fails only beside another suite.
- Head: `TestTelnyxUnpaidSuite`, `TestScheduledTasksSuite`,
`TestLinqChannelSuite`, `TestTelnyxChannelSuite`,
`TestTelnyxSandboxSuite`, `TestWhatsAppChannelSuite` and
`internal/scheduling` (unit and integration) pass.
- Mutations: 12 of 14 are killed. Each changed read was moved back to
the default const, each default dropped from `NewServer`, the peer
window had its call limit dropped, and `SetRetries` or `newScheduler`
was made a no-op. Two survive: a no-op `SetFinishRetries` and a
`newScheduler` that ignores `finishRetries`. `finishAtOnce` only
shortens the 1-4 s finish waits, and its two tests pass at the defaults
too, only slower. I added no timing bound for them: a bound that tight
would flake on a loaded runner.
- Not yet run: `-count=50`, `-race` and `-cpu 1` over the suite (the
done criteria of AI-3655).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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