Skip to content

feat(offload): add blobmask — mask tool output dominated by an embedded base64 payload - #332

Draft
OsherElhadad wants to merge 4 commits into
mainfrom
night0928/a1-work
Draft

OsherElhadad wants to merge 4 commits into
mainfrom
night0928/a1-work

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

No registered component targets a tool result whose bulk is an embedded base64 data-URI
payload (a browser-automation screenshot, a rendered image, an encoded attachment):
format/toon only reformat JSON structure, not field values; textclean targets ANSI
noise; searchfold targets repeated search-result prefixes; dedup needs a byte-identical
earlier occurrence in the same request's own message array.

Worked example (the strongest evidence here): a 24,413-token browser-automation tool
result (an inline JPEG screenshot inside a small JSON envelope) that format only trims to
24,357 tokens (0.2%) — the embedded image itself is untouched by every currently deployed
component.

Prevalence, measured, full population (306,785 request_content rows, not sampled):
1,667 rows (0.544%) match the embeddedBlob regex below, carrying 5.1% of true decompressed
bytes
and 7.3% of CG's own o200k_base token count for that content. (An earlier version of
this PR reported 1.37% of bytes and a "5.7x" byte/token gap — both wrong, caught in review: my
byte count was measured off request_content.before_gz, which apply.mkChange caps at 4,000
bytes while BeforeTokens is computed on the full string; every one of the 1,667 matches was
over that cap. Recovered the true length from clip's …[+N bytes] suffix, which survives
intact since the redaction-time cap is larger and never re-triggers. Corrected: matching
content measures 2.397 bytes/token, comfortably above the physically-required 1.0 floor and
only ~1.46x worse than non-matching content's 3.498 — not the impossible 0.448 / "5.7x" the
bug implied.)

Tokenizer caveat, and its direction matters: 7.3% is CG's own o200k_base counter, not
Claude's billing tokenizer. There is no measured correction factor (f, this repo's
billed/ours ratio) for base64 specifically; the closest proxy, hex_hashes, has the LOWEST
measured f of any class (1.1468) — every other class competing for the same denominator has
a HIGHER one (tool_result_json 1.3271, english_prose 1.5428, go_code 1.6887,
grep_output 1.7565). A low f on a LEVEL is not a low share on the bill: since the
surrounding content inflates faster than the base64 does when converted to billed tokens,
base64's true billed SHARE is plausibly LOWER than 7.3% — around 5-6.5%, close to the
corrected byte share, not the token share. (Intuition runs backwards here: "a correction
factor above 1.0 pushes the number up" is true of a level and false of a share whose
denominator corrects faster.)

This PR measures prevalence. It does NOT measure the dollar saving — that requires either
a live measurement against real traffic or a replay experiment, neither of which is in this
PR. And to be precise about scale: this targets roughly 5-7.3% of candidate mass CG
examines
, not of the bill — the bill-share of this deployment's "new content" slice alone is
a different, much larger number this PR does not move.

blobmask reuses the exact tryMark/commitMark/freeze/reapplyFrozen/TailOnlyCold
contract mask and failed_run already ship: same exactness guarantee (full-mode stash +
context_guru_expand round-trip), same cache-write safety (a NEW collapse only in the
uncached tail, or on a turn whose cache has provably expired — never retroactively inside an
already-cached prefix). Detection is now a single regex for an explicit
data:<mime>;base64,<200+ chars> URI (see below for why the bare-run form was dropped);
min_blob_frac (default 0.6) keeps a short incidental token sitting beside real, useful text
from taking the whole message with it.

Not wired into any preset — opt-in, like toolfilter, pending a live measurement of its
real effect on real traffic (see the "untested" note below). Kept as draft for exactly that
reason.

Update: dropped the bare base64-run detection arm entirely (2 review rounds found real gaps)

The original version also matched a bare 200+-char base64-alphabet run with no data: prefix,
to catch a payload with no explicit MIME declaration. Two rounds of review found real
adversarial-exactness gaps in it:

  1. Hex is a subset of the base64 alphabet, so a 200+-char hex digest chain (an SRI integrity
    block, a concatenated sha256sum listing) matched and would have been masked as a "binary
    payload" — discarding a hash the agent might need to compare. First fix: require one
    character outside the hex alphabet among the run.
  2. That fix still matched a pagination/continuation token — standard base64, no dots,
    routinely 200+ characters (an AWS/S3 NextToken, a GraphQL Relay cursor). Worse than the
    hex case: the agent needs this value VERBATIM on its very next tool call, so masking it
    isn't just a lossy compaction, it breaks the next step. There is no shape-only signal that
    tells "a payload the agent will never need back" apart from "a token it needs immediately"
    — both are high-entropy base64 blobs.

Rather than patch around this with a field-name denylist (token/cursor/page/next/...,
offered as a workable option but one that inevitably misses some API's naming convention and
cuts against this component's shape-not-name design), I checked how much real value the
bare-run arm was contributing: zero. Re-scanned the full snapshot — every one of the 1,667
real matches carries an explicit data: URI; the bare-run arm matched none of them on its
own. Dropped it. Renamed the adversarial test to TestBlobMaskOnlyTrustsAnExplicitDataURI and
added the continuation-token repro to its table alongside the two hex cases and the real
base64-image control.

Follow-up: a review thread continued after this fix landed, but it was checking the fix's
PREDECESSOR commit (505aedc, the hex-only patch) rather than this one — the bare-run arm was
already gone by the time those messages were sent. Re-verified against current HEAD with the
exact repro shape (a bare "nextPageToken":"<2160-char base64>" field, no data: URI): no
match, full stop, regardless of size or dominance — there's no bare-run arm left for it to hit.
Added TestBlobMaskNeverMatchesAPlainTokenFieldUnderRealDefaults, which pins this using the
ACTUAL shipped defaults (not the test helper's lowered min_tokens) and asserts the decline
comes from the structural no_embedded_blob gate specifically, so the gate-ordering question
("does it even clear min_tokens/min_blob_frac before the regex matters?") is settled rather
than argued from a hand computation. Whether an explicit data: URI could ever legitimately
wrap a non-media opaque token is an open question I don't have a real API example for; happy to
revisit if one surfaces.

Test plan

  • go test ./components/offload/... -run TestBlobMask -v — 8/8 pass (dominant-payload
    collapse, expand round-trip is byte-identical, a small incidental token beside real text is
    left alone, the cached-prefix gate holds, and the 4-case adversarial table: hex chain, hex
    listing, continuation token, real payload control)
  • go test ./components/offload/... — full existing package (200+ tests) still passes;
    extended commitgate_test.go's gateCases() with a blobmask entry so
    TestEveryOffloadComponentIsHeldToTheCommitGate covers it
  • go test -race ./components/offload/... — pass, 161.8s (re-run after the bare-run-arm
    removal and the real-defaults pinning test)
  • go vet ./... — clean
  • go build -tags cg_skeleton ./... — clean
  • gofmt -l on changed files — clean
  • Untested: the dollar SAVING. Prevalence is measured (above); the effect on real
    traffic — net tokens removed, task correctness, interaction with the cache-write penalty on
    the write turn — is not. That's why this stays draft and out of every preset.

Full writeup, decline-reason tables for the 12 live components, and the rejected alternatives
considered for this content class: /home/vpcuser/cg-night-0928/reports/A1-compaction.md
(overnight research run, not part of this PR).

…ed base64 payload

No registered component targets a tool result whose bulk is an embedded base64/
data-URI payload (a browser-automation screenshot, a rendered image, an encoded
attachment). format/toon only reformat JSON structure, not field values;
textclean targets ANSI noise; searchfold targets repeated search-result
prefixes; dedup needs a byte-identical earlier occurrence in the same request.

Sampling 1-in-7 of request_content on the deployed snapshot (43,826 of 306,785
rows), 0.55% of rows contain such a payload but carry 7.7% of all sampled
before_tokens. Worked example: a 24,413-token browser-automation tool result
(an inline JPEG screenshot inside a small JSON envelope) that format only trims
to 24,357 tokens (0.2%) — the embedded image is untouched by every currently
deployed component.

blobmask reuses the exact tryMark/commitMark/freeze/reapplyFrozen/TailOnlyCold
contract mask and failed_run already ship: same exactness guarantee (full-mode
stash + expand round-trip), same cache-write safety (a NEW collapse only in the
uncached tail, or on a turn whose cache has provably expired). Detection is one
regex for a data:<mime>;base64,<200+ chars> URI or a bare 200+-char base64 run
in a JSON string value; min_blob_frac (default 0.6) keeps a short incidental
token beside real text from taking the whole message with it.

Not wired into any preset — opt-in, like toolfilter, pending a live measurement
of its real effect on this deployment's traffic.

Extends commitgate_test.go's gateCases() with a blobmask entry so
TestEveryOffloadComponentIsHeldToTheCommitGate holds it to the same
no-state-before-the-stash-succeeds invariant every other offloader is held to.

Verified:
  go test ./components/offload/... -run TestBlobMask -v      (4/4 pass)
  go test ./components/offload/...                            (full package, pass)
  go test -race ./components/offload/...                      (pass, 157.5s)
  go vet ./...                                                 (clean)
  gofmt -l (new/changed files)                                 (clean)
Untested: no live/replay measurement of blobmask's effect on real traffic —
the sampled-content-class evidence above is the only measurement backing this.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Independent review — cache safety and reversibility PASS; one real false-positive class in the regex, with a verified fix

Reviewed by the orchestrator rather than the author. I ran everything below myself; I have not relied on the PR body's own test output.

What passes, verified independently

Cache safety — the pass/fail gate — holds. blobmask.go:79 calls reapplyFrozen and :106 gates on c.TailOnlyCold(i, b.coldCache) with repairLostFreeze, emitting Gate("cached_prefix") otherwise. So it inherits mask's discipline exactly: new masks only in the uncached tail, frozen masks reapplied byte-identically, depth lifted only on a provably-expired cache. That is the right contract and it is the same one four independent sources converge on.

Tests pass on a clean checkout of this branch:

$ go test ./components/offload/ -run 'BlobMask' -v
--- PASS: TestBlobMaskCollapsesADominantEmbeddedPayload (0.02s)
--- PASS: TestBlobMaskExpandRoundTrips (0.00s)
--- PASS: TestBlobMaskLeavesASmallIncidentalPayloadAlone (0.00s)
--- PASS: TestBlobMaskRespectsTheCachedPrefix (0.00s)
ok  github.com/rossoctl/context-guru/components/offload  0.040s

TestBlobMaskExpandRoundTrips and TestBlobMaskRespectsTheCachedPrefix are the two that matter, and both are real tests of the right properties.

The finding: the bare-run alternation fires on long HEX strings

embeddedBlob's second arm is "[A-Za-z0-9+/]{200,}={0,2}". Hex is a subset of [A-Za-z0-9], so any 200+ character hex run inside a JSON string value matches — and hex digests are exactly the kind of exact evidence a model may need verbatim. Measured against the committed regex:

input current regex should match?
256-char hex digest chain (SRI integrity, concatenated digests) MATCHES no
10 concatenated sha256 values (git cat-file-shaped output) MATCHES no
JWT payload, base64url with -/_ no match no (correct — -/_ are outside the class)
JWT payload, base64url without -/_ matches arguably yes, it is base64-shaped
real data:image/png;base64,… matches yes

This matters here specifically because hex_hashes is a measured content class in this corpus (it carries the lowest billed factor of any class, f = 1.1468), so hex-dense tool output is present, not hypothetical. A sha256sum over many files, a lockfile integrity block, or a git cat-file listing can be dominated by hex — which is what defeats MinBlobFrac.

Verified fix

Require the bare-run arm to contain at least one character outside the hex alphabet. Real base64 of binary data essentially always has one (uppercase past F, lowercase past f, or +//):

"(?=[A-Za-z0-9+/]{200,}={0,2}")(?:[A-Za-z0-9+/]*[G-Zg-z+/][A-Za-z0-9+/]*)={0,2}"

Measured on the same cases — both hex false positives eliminated, every true positive retained, including a bare base64 PNG with no data: URI:

input current proposed
hex digest chain 256ch true false
10x concatenated sha256 true false
JWT base64url with -/_ false false
JWT base64url no -/_ true true
data: URI screenshot true true
bare base64 PNG in JSON true true

Severity: should-fix, not blocking

Three things limit the damage, and I want to be fair about them: MinBlobFrac requires the blob to dominate the message, so an incidental hash in a large output is safe; the transform is reversible via the stash + <<cg:HASH>> marker, so a false positive is recoverable rather than lost; and the component is in no preset, so nothing is exposed today. But the reversibility argument is weaker than it looks right now — #188's rewind reserve is absent from the deployed binary (#323) and #244 (silent pin-budget saturation) is open — so "it is recoverable" currently rests on machinery that is not fully enforced in production. Worth fixing the regex rather than leaning on the stash.

Two smaller notes

  1. Please add the adversarial cases above as table tests. TestBlobMaskLeavesASmallIncidentalPayloadAlone covers the small case but nothing covers hex that dominates, which is the actual gap.
  2. The prevalence numbers and the share-direction caveat in the PR body are correct as now written (1.4% bytes / 7.3% our tokenizer / ~5–6.5% billed, lower because base64's f is the lowest measured class). Good — that direction was wrong in an earlier draft and is right now.

Keeping this draft. Not blocking, but I would not merge the regex as-is.

@OsherElhadad OsherElhadad 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.

Independent review (REV) — PR #332 (blobmask)

Reproduced/attacked in my own worktree (wt2/rev), against the read-only snapshot only
(sqlite3 "file:...?mode=ro"). No spend, no live service, no writes to the snapshot.

Reversibility & cache safety — verified, both pass

  • go test ./components/offload/... -run TestBlobMask -v → all 4 existing tests PASS
    (dominant-payload collapse, expand round-trip, small-incidental-payload left alone,
    respects-cached-prefix).
  • go test -race ./components/... → PASS, all 5 packages including offload (163.7s) and
    reformat (91.9s). go build -tags cg_skeleton ./components/... → clean.
  • TestEveryOffloadComponentIsHeldToTheCommitGate PASS with blobmask wired into
    gateCases()
    — this is the exact "does it refuse when it cannot stash" invariant, and it's
    real: spyStore.PutStash returns false, and the shared table asserts no cg:frz:/cg:res:/…
    write happens for a refused removal. blobmask inherits this for free by reusing
    tryMark/commitMark/freeze verbatim from mask.go — it does not reimplement the contract.
  • I wrote and ran an additional cache-safety test (not committed) reproducing a two-turn
    scenario: turn 1 masks a screenshot in the uncached tail (freezes the decision); turn 2 the
    client resends the same original bytes, now sitting inside the cached prefix
    (MaxCachedIdx=0, cold_cache: false — a brand-new mask here would hit cached_prefix).
    Result: byte-identical masked output on turn 2, via reapplyFrozen, exactly as the shared
    contract promises. This is the actual pass/fail gate the brief asked for, and it passes.
  • Regex catastrophic-backtracking: not applicable — Go's regexp is RE2 (guaranteed linear
    time, no backtracking engine), confirmed by running the pattern against a 200,000-byte
    pathological near-match input (long matching-alphabet run with no closing quote) under a 5s
    deadline in a goroutine: returned in ~20ms.

Real, reproducible false positive: opaque tokens the model needs (pagination cursors, long

non-JWT bearer tokens) get masked away exactly like a screenshot

The regex's bare-string branch ("[A-Za-z0-9+/]{200,}={0,2}") is pure shape, with only
MinBlobFrac/MinBlobFrac guarding it — and that guard's assumption ("a blob that dominates a
message is presumably a throwaway image") breaks down precisely when the message's entire
utility
is a long opaque value. I constructed: {"items":[],"nextPageToken":"<2250 clean base64 chars>"}} (well over the 500-token/0.6-frac defaults) and ran it through Offload:

FALSE POSITIVE: got "[embedded binary payload masked] <<cg:...>> [full output: call context_guru_expand]"

Reversible in principle (the marker can be expanded), but a model has no particular reason to
proactively call expand on what looks like a masked screenshot before using it as a pagination
token in its next tool call — this is a functional-correctness risk, not just a lost-savings one.
Note a real JWT is naturally excluded by construction (base64url alphabet + two .
separators break the 200+ contiguous-run match), but a standard-base64 opaque continuation token
(AWS/S3 NextToken-style, Kubernetes continue, GraphQL Relay cursors — all commonly this shape
and easily this long) is not. This is real and worth fixing or documenting as a known limitation
before this is ever wired into a preset; the field-name-agnostic design is deliberate (documented
in the file) and I'm not asking to abandon it, but the current guard doesn't cover this case and
should say so.

Prevalence and the token-share number: I re-measured independently, and here's the trap I hit

(and want to flag so nobody re-hits it)

Prevalence — exactly reproduced: I ran the PR's own regex against before_gz for the full
306,785-row population (own script, own worktree). 1,667 matched rows — 0.5434% — same to
three decimal places as claimed.

Token share — also confirmed exactly, but only after I caught my own methodology bug: my
first pass decompressed before_gz and tokenized it directly with tiktoken/o200k_base, and
got a wildly different number (~1.6% token share, not 7.32%) with a "bytes/token" ratio for blob
content that is mathematically impossible for any byte-level BPE tokenizer (a guaranteed
≥1.0 bytes/token floor — merges only increase that ratio, they can't push it below 1). Chasing
that down: request_content.before_gz is not the full original message — apply/apply.go's
mkChange caps the stored preview at TraceTextCap = 4000 bytes (Before: clip(before, TraceTextCap)) while computing BeforeTokens on the full, uncapped string. Real screenshots
are routinely far bigger than 4000 bytes, so I was tokenizing a truncated preview and comparing it
against a token count computed over the true original — hence the impossible ratio. Once I
instead summed request_content.before_tokens directly (the column that is computed on the
full string) for matched vs. non-matched rows:

base64 (matched):     14,943,667 tokens   <- exact match to PROGRESS.md §2c and the PR
rest (non-matched):  189,143,042 tokens   <- exact match
share: 14,943,667 / (14,943,667+189,143,042) = 7.322%

So the 7.32% token-share figure is confirmed correct, not a defect. Flagging the trap anyway
because it's a real, non-obvious gotcha for the next person querying this table directly (I nearly
reported a false blocking finding over it) — before_gz/after_gz are diff-view previews, capped,
not a byte-accurate source for size statistics on large content.

What I could not verify, and would ask the author to double-check: the byte-share (1.37%)
and the specific "0.448 vs 2.555 bytes/token" / "5.7x gap" framing in PROGRESS.md §2c (restated
in this PR's context). Both numbers necessarily hit the same before_gz truncation trap I just
described if they were computed the same way I first (wrongly) did — and 0.448 bytes/token is,
again, impossible for a real byte-level BPE result, which is itself decent evidence something
upstream of it was computed against capped bytes. This does not affect the PR's core economic
argument
: the billed-share reasoning (~5–6.5%, lower than the tokenizer share) is derived
directly from the verified-correct token counts above plus the measured f factors — it does
not depend on the bytes/token figure at all. So the headline number I'd actually rely on
(7.32% tokenizer share, ~5-6.5% estimated billed share) holds up; the "5.7x gap" side-explanation
for why is the part I'd ask to be re-derived or dropped.

Ordering / overlap with format, textclean, extract, linecap

No conflict, verified in source rather than assumed: every offloader (blobmask included) calls
skipReduce, which gates on expand.HasPlaceholder(content) — content already carrying a
<<cg:HASH>> marker from an earlier component in the same pipeline run is skipped
(already_marked), regardless of ordering. format/textclean are lossless reformatters, not
Offloaders, so they don't inject markers and can't trigger this gate; the risk is only ever
between two lossy Offloaders, and that's covered generically. Since blobmask isn't wired into any
preset yet, there's no live ordering decision to critique — when it is proposed, I'd put it beside
mask (another shape/age-based offloader), before the collapse/linecap "last-resort" pass per
the general preset's own documented ordering rationale.

Is a new component warranted?

Yes, on balance — the shape (embedded base64 dominance) genuinely isn't covered by any live
trigger (age for mask, relevance for extract, generic size for collapse/linecap), and 7.32%
of tokens concentrated in 0.54% of rows (both now independently confirmed) is a real, non-trivial,
currently-uncovered pool, not a rounding error. I would not fold this into mask or collapse —
the trigger condition is orthogonal to both. But it should not go into any default preset until
(1) the pagination-token false-positive above is fixed or explicitly documented with a mitigation,
and (2) the dollar value is actually measured, per the author's own honest framing.

Verdict

Does not yet pass — one real fix needed, one claim to correct, both small.

  1. Blocking-before-wiring-into-any-preset (not blocking this draft PR's existence): the opaque
    long-token false positive. A cheap mitigation: don't match a bare 200+ run that is the entire
    value of a JSON field whose key looks like a token/cursor/id (token, cursor, page, next,
    continuation, signature, key, hash, etag — a small denylist, same shape-first
    philosophy, opposite direction from a field-name allowlist) — or simply raise the caution level
    in the docs/config comment until measured.
  2. Please re-derive or drop the "0.448 bytes/token" / "5.7x gap" framing — it's mathematically
    impossible as stated and I believe it's a TraceTextCap-truncation artifact. The 7.32%
    token-share and the billed-share estimate built from raw token counts are unaffected and I've
    independently confirmed both.

Everything else (reversibility, cache safety, commit-gate discipline, no preset wiring, go test -race clean) is solid, verified, and well-tested.

Hex is a subset of the base64 alphabet, so a 200+-char hex digest chain
(an SRI integrity block, a concatenated sha256 listing, a lockfile) matched
the bare-run arm and would have been masked as a "binary payload" — throwing
away a hash the agent may need to compare, not an unreadable blob.

Found in review, verified independently on both the false-positive claim and
the proposed fix: the reviewer's suggested pattern used a lookahead
(`(?=...)`), which Go's RE2-based regexp package does not support and does
not compile. Rephrased without a lookahead: require the mandatory 200+-char
run to be at least 199 hex-or-base64 characters followed by one character
OUTSIDE the hex alphabet ([G-Zg-z+/]), which guarantees both the minimum
length and the presence of a genuinely non-hex byte — real base64 of binary
data essentially always has one within 200+ characters; a pure hex digest
chain never does.

Verified against the deployed snapshot: re-scanning all 306,785
request_content rows with the corrected regex finds the exact same 1,667
matches as before (0 rows removed) — none of this deployment's captured
traffic happened to trigger the false positive, so this is a robustness fix
for a real but not-yet-observed failure mode here, not a correction to the
measured prevalence already reported.

Added TestBlobMaskDoesNotMistakeLongHexForABinaryPayload (table test: a
256-char hex digest chain, a 10x concatenated sha256-shaped listing, and a
real base64 image payload as control) so the adversarial case has a
permanent regression test, not just a one-off check.

Verified:
  go test ./components/offload/... -run TestBlobMask -v   (7/7 pass, incl.
    the 3 new table-test cases)
  go test ./components/offload/...                         (full package, pass)
  go vet ./...                                              (clean)
  gofmt -l (changed files)                                  (clean)
Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Confirmed the finding independently before touching anything, and it's exactly right: 256-char hex chain and the 10x-sha256-shaped listing both match the old regex, verified with regexp.MatchString.

One correction to the suggested fix itself: the proposed pattern uses a lookahead ((?=[A-Za-z0-9+/]{200,}={0,2}")...), which does not compile under Go's regexp package — it's RE2-based and RE2 doesn't support lookahead at all (regexp.Compile returns invalid or unsupported Perl syntax: (?=). Applying it as literally proposed would have broken the build.

Rephrased without a lookahead to the same effect: require the mandatory run to be at least 199 hex-or-base64 characters followed by one character strictly outside the hex alphabet ([G-Zg-z+/]), which guarantees both the ≥200 total and a genuinely non-hex byte in one linear pattern:

"[A-Za-z0-9+/]{199,}[G-Zg-z+/][A-Za-z0-9+/]*={0,2}"

Verified against your exact adversarial cases (all pass) plus the true positives (real data URI, bare base64 PNG): pushed as 505aedc. Also re-scanned the full 306,785-row snapshot with the corrected regex — identical 1,667 matches, 0 removed, so none of this deployment's real traffic happened to trigger the false positive; this is a robustness fix for a real-but-not-yet-observed case here, not a correction to the prevalence numbers already in the PR body.

Added TestBlobMaskDoesNotMistakeLongHexForABinaryPayload as a permanent table test (your three cases plus the real-payload control) rather than leaving it as a one-off check. Full test suite + go vet + gofmt clean; -race re-run in progress, will confirm.

PR body updated with both this fix and a corrected note (still draft, saving still untested).

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Confirmed: go test -race ./components/offload/... passes clean post-fix (157.2s). Full test plan checklist in the PR body is now all green except the untested dollar-saving item, which stays that way deliberately.

@OsherElhadad OsherElhadad 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.

Follow-up: confirmed my pagination-token false positive clears both defaults, with exact numbers

The orchestrator raised a fair question — does my repro actually clear min_tokens=500 and
min_blob_frac=0.6, or would it be gated out at below_min_tokens first? Re-verified against
the post-hex-fix branch (505aedc) with real production defaults (newBlobMask([]byte("")), no
test-helper override) and exact numbers logged:

message tokens = 1209   (min_tokens default = 500)
blob/message byte frac = 0.9873   (min_blob_frac default = 0.60)
result: masked

So yes — comfortably over both thresholds, still masked. This is a distinct false-positive class
from the hex one (the token here is a mix of letters/digits, not pure hex, so it also clears the
new hex-exclusion guard). Sent A1 the exact repro directly. Two independently-confirmed
false-positive classes in the same regex arm, from two reviewers, is why I think this needs a
shape-level rethink of that arm rather than another one-off exclusion — happy to review whatever
A1 proposes.

…ds, 2 false-positive classes

The bare-run regex arm (a 200+-char run of the base64 alphabet with no
data: URI, added to catch a payload with no explicit MIME declaration)
turned out to be pure downside on this deployment's traffic.

Second review round found it still matches a pagination/continuation
token — standard base64, no dots, routinely 200+ characters (an AWS/S3
NextToken, a GraphQL Relay cursor) — even after the prior fix required a
non-hex character (which closed a different false positive: a long hex
digest chain, e.g. an SRI integrity block or a sha256sum listing, is a
SUBSET of the base64 alphabet and matched too).

Masking a continuation token is a worse failure than masking a hash: the
agent needs it VERBATIM on its very next tool call, not merely "might
want to compare it later." And there is no shape-only signal that tells
"a binary payload the agent will never need back" apart from "an opaque
token the agent needs immediately" — both are high-entropy base64 blobs.
A field-name denylist (token/cursor/page/next/...) was offered as a fix
but rejected: it inevitably misses some API's naming convention and cuts
against this component's own shape-not-name design.

Checked how much real value the bare-run arm was contributing before
deciding how to fix it: zero. Re-scanned the full snapshot (306,785
request_content rows) — every one of the 1,667 real matches carries an
explicit data: URI; the bare-run arm matched none of them on its own.
Dropping it costs nothing measured here and removes both false-positive
classes at once, which is a smaller and more defensible diff than
patching around a token/cursor denylist.

Renamed the adversarial test to TestBlobMaskOnlyTrustsAnExplicitDataURI
and added the continuation-token repro to its table, alongside the two
hex cases and the real-payload control.

Verified:
  go test ./components/offload/... -run TestBlobMask -v   (8/8 pass, incl.
    the continuation-token repro)
  go test ./components/offload/...                         (full package, pass)
  go vet ./...                                              (clean)
  go build -tags cg_skeleton ./...                          (clean)
  gofmt -l (changed files)                                  (clean)
  go test -race ./components/offload/...                    (pass — see
    next commit or PR thread for the exact run this covers)
Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Both findings confirmed independently before acting, and both were real — thank you for the depth here.

1. Continuation-token false positive: reproduced with your exact repro shape (2,115-char clean base64, no dots, in a nextPageToken field) — matches the hex-fixed regex from the last round, exactly as you found. You're right that a field-name denylist would work but cuts against the shape-not-name philosophy and inevitably misses some API's convention. Before deciding how to fix it, I checked how much real value the bare-run arm was contributing to the actual measured prevalence: zero. Re-scanned the full 306,785-row snapshot — every one of the 1,667 real matches carries an explicit data: URI; the bare-run arm (hex-guarded or not) never matched a real payload on its own in this corpus. So I dropped the bare-run arm entirely rather than add a denylist — smaller diff, removes both your false-positive classes (this one and the earlier hex one) at once, and costs nothing measured here. Pushed as b5c4e17. Added your continuation-token repro to the adversarial test table (TestBlobMaskOnlyTrustsAnExplicitDataURI), alongside the two hex cases and the real-payload control — 8/8 pass, -race re-run clean (168.4s).

2. The 0.448 bytes/token impossibility: confirmed your root-cause diagnosis exactly. apply.mkChange computes BeforeTokens on the full string but stores clip(before, TraceTextCap) (4000 bytes) as the text that gets gzipped into before_gz — and every one of the 1,667 matching rows was over that cap, so I was measuring a truncated preview's bytes against a full-string token count. clip's …[+N bytes] suffix turned out to be recoverable (the redaction-time cap, DASHBOARD_CONTENT_CAP = 16KiB default, confirmed via systemctl show, is larger than the 4000-byte cap and never re-truncates already-clipped content, so the suffix survives intact). Recomputed with the true lengths: 5.134% of bytes, not 1.367%; matching content measures 2.397 bytes/token (above the 1.0 floor, as it must be) against 3.498 for non-matching — base64 tokenizes ~1.46x worse per byte, not 5.7x. Agreed the billed-share estimate (~5-6.5%, derived purely from token counts + f-factors) is unaffected — confirmed that independently too, it never touched the byte figures.

Both fixes are in the PR body and the report now, with the wrong numbers left visible and marked as corrected rather than silently edited away. Full test plan checklist all green except the deliberately-untested dollar-saving line. Happy to take another pass if anything else stands out.

…al defaults

Resolves a back-and-forth in review about whether commit 505aedc's
pagination-token false positive survives into the CURRENT design (it
does not — b5c4e17 already dropped the bare base64-run detection arm
entirely, so a bare JSON string value with no `data:` URI cannot match
`embeddedBlob` regardless of size or dominance). Both a reviewer and the
orchestrator's follow-up messages tested against 505aedc, which this
branch had already superseded before their messages arrived.

Adds a test using the ACTUAL shipped defaults (newBlobMask([]byte("")),
not the test helper's lowered min_tokens:5) with a realistic 2,160-char
token that clears both min_tokens=500 and min_blob_frac=0.6 on its own,
asserting the component still declines it — via the structural
`no_embedded_blob` gate specifically, not `below_min_tokens` or
`blob_not_dominant` — so nobody has to re-derive by hand whether the
gate ordering or the regex is what's protecting this case.

Verified:
  go test ./components/offload/... -run TestBlobMask -v   (10/10 pass)
  go test ./components/offload/...                         (full package, pass)
  go vet ./...                                              (clean)
  go build -tags cg_skeleton ./...                          (clean)
  gofmt -l (changed files)                                  (clean)
Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Resolving the pagination-token back-and-forth: both the orchestrator's and REV's latest checks were against 505aedc (the hex-only fix). This branch had already moved past that — b5c4e17 (pushed before those messages arrived) dropped the bare base64-run detection arm entirely, for exactly the reason REV originally raised (it matched zero real payloads in the full snapshot and carried two distinct false-positive classes).

Re-verified against current HEAD (ddbcf85) with REV's exact repro shape: a bare "nextPageToken":"<2160-char base64>" field, no data: URI, does NOT match embeddedBlob at all now — regexp returns no match, full stop, regardless of size or dominance. There's no gate-ordering subtlety left to argue about (whether it clears min_tokens/min_blob_frac first is moot) because the regex itself no longer has an arm that could match a bare JSON string value.

Added TestBlobMaskNeverMatchesAPlainTokenFieldUnderRealDefaults, which pins this with the ACTUAL shipped defaults (newBlobMask([]byte("")), not the test helper's lowered min_tokens:5) and a fixture that clears both real defaults on its own (2,160 chars ≫ 500-token floor, 0.6 frac), asserting the decline comes from the structural no_embedded_blob gate specifically — not from being gated out by size first, which is what the "was it even measuring the real defaults" thread was trying to pin down.

On REV's forward-looking point (does a data: URI itself risk wrapping a non-media token?): I don't think this is a realistic API convention — pagination/continuation tokens don't get wrapped in MIME-declaring data URIs in any convention I'm aware of, and requiring that explicit declaration is what makes the current design a structural exclusion of the token/cursor class rather than a heuristic one. If either of you can construct a real API shape where that happens, I'd genuinely like to see it and will take the patch — but absent one, I think this closes the class REV was worried about, not just the one example.

-race re-run in progress on ddbcf85, will confirm. 10/10 blobmask tests pass, full package/vet/gofmt/cg_skeleton build all clean.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Confirmed: go test -race ./components/offload/... passes clean on ddbcf85 (161.8s). All 10 blobmask tests pass, full package/vet/gofmt/cg_skeleton build all clean. PR body updated with the resolution.

@OsherElhadad OsherElhadad 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.

Final confirmation: the fix closes both false-positive classes, verified independently

Confirmed the fix (b5c4e17 + ddbcf85) rather than just reading it:

  • My exact original repro is now clean. Re-ran it verbatim (real defaults, 1,209 message
    tokens vs. the 500 floor, 0.9873 blob fraction vs. the 0.6 floor — the same numbers from my
    earlier "confirmed with exact numbers" comment) against the new regex: no longer masked.
  • The hex false positive (from the orchestrator's review) is also gone, by construction —
    confirmed the new pattern (data:<mime>;base64,<200+> only) has no bare-run alternative for
    a hex chain or anything else to accidentally match.
  • The "zero real matches lost" claim is exactly right. Independently re-scanned the full
    306,785-row snapshot with the new, narrower regex (own script, not reusing the PR's numbers):
    still 1,667 matches — identical to the original count with the bare-run arm included. The
    bare-run arm really was contributing nothing measured on this deployment's traffic; dropping it
    is free.
  • go test ./components/offload/... -run TestBlobMask -v: 6/6 pass, including the renamed
    TestBlobMaskOnlyTrustsAnExplicitDataURI table (hex ×2, the continuation-token repro, and the
    real-payload control). go vet ./components/offload/..., gofmt -l, and
    go build -tags cg_skeleton ./components/... all clean. go test -race ./components/offload/...
    in progress as I write this; will flag if anything comes back other than clean (I don't expect
    it to, given the diff is a regex literal + test changes only, no concurrency-relevant code).

Agreed this is the strongest possible answer to the false-positive class, for exactly the reason
the commit message gives: there's no shape-only signal that tells "disposable payload" apart from
"opaque token needed immediately," so removing the ambiguous arm rather than trying to patch
around it with a denylist is the right call. Filed #339 for the one adjacent, unrelated residual
(FoldSearchOutput's byte-vs-token candidate selection, found while reviewing #336) — no live
instance found, latent only, not blocking anything here.

Verdict: passes.

@OsherElhadad OsherElhadad 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.

go test -race ./components/offload/... finished clean (157.5s, no failures) — as expected. #332 fully confirmed passing on my end.

@OsherElhadad OsherElhadad mentioned this pull request Oct 21, 2026
13 of 24 tasks

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: New/ToDo

Development

Successfully merging this pull request may close these issues.

1 participant