Skip to content

feat(audit): dedupe large payload snapshots as content-addressed chunks - #439

Open
kiddyt00 wants to merge 6 commits into
astaxie:mainfrom
kiddyt00:feat/audit-payload-chunk-dedup
Open

kiddyt00 wants to merge 6 commits into
astaxie:mainfrom
kiddyt00:feat/audit-payload-chunk-dedup

Conversation

@kiddyt00

@kiddyt00 kiddyt00 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Coding agents resend their whole tool schema set and conversation history on every request, so those requests overflow the 64 KiB audit scan budget and their snapshots are recorded as an omission marker. Routing, billing, and status codes stay correct, but the admin console loses the ability to replay what the client actually sent for exactly the traffic where replay matters most (#435).

This change raises the snapshot limits to sizes that cover coding-agent traffic and stores large snapshots as deduplicated chunks instead of a marker.

Related Issue

Closes #435

Changes

  • TOKENHUB_AUDIT_PAYLOAD_SCAN_KB (default 256) and TOKENHUB_AUDIT_PAYLOAD_MAX_KB (default 64) control snapshot rendering and the inline preview. The old defaults, 64/8, omitted nearly every agent snapshot; 256 KiB covers requests whose tool schemas and history usually exceed 64 KiB on their own. A preview larger than the scan budget folds back to it.
  • Snapshots larger than the preview are split into 16 KiB chunks on UTF-8 rune boundaries, deduplicated by SHA-256 in a new payload_chunks table, and referenced in order from payload_chunk_refs. Insertion is idempotent (ON CONFLICT DO NOTHING plus in-loop hash tracking), so repeated content inside one snapshot or a concurrent writer race cannot drop the snapshot. The inline columns keep only the bounded preview; GetRequestDetail reassembles the full text when a request is opened.
  • Retention GC drops references whose payload row is gone and then unreferenced chunks in indexed batches, keeping chunks that newer requests still share.
  • Schema expansion migration v12 (add-payload-chunk-dedup) covers existing databases; the fresh baselines and the migrations manifest are updated to match.
  • The two variables are synced across backend/.env.example, deploy/.env.example, deploy/docker-compose.yml, start.sh, and the three deployment docs.

Measured against real DSH agent traffic (13 requests carrying 25 tool definitions each): tool chunks repeated 92%, message chunks 87%, whole payloads 0% — which is why the dedup is chunk-based rather than whole-body. Content-addressed storage reduced the sampled bytes 12.7x (453 KB to 35 KB), so raising the scan budget no longer multiplies storage for every request. At the new 256 KiB default the remaining cost is transient rendering memory: the 192 KiB working point measures about 7.8 ms and 1.5 MB of allocations per oversized snapshot (BenchmarkGatewayPayloadAuditRendering).

Type of Change

  • New feature
  • Bug fix
  • Refactor or maintenance
  • Documentation
  • Deployment or configuration

Verification

  • go test ./... via the CI shard script, all four shards: green except TestNotificationSecretsRedactSMTPQuotedErrors, which fails identically on upstream/main (0e627e5) and is unrelated to this change
  • go vet ./... clean; golangci-lint v2.12.2 (CI-pinned): 0 issues
  • Regression tests for the review findings: repeated content inside one snapshot (previously dropped the whole snapshot), UTF-8 multibyte chunk boundaries, chunk round trip through GetRequestDetail, cross-request dedup, GC keeps referenced chunks, configurable rendering, preview clamp, env fallback and normalization
  • The full-server-package suite and all repository gates run locally on the head commits; git diff --check passes
  • docker compose config skipped: Docker is unavailable in this environment

Type of Change note on review fixes

The three findings from the first review round are addressed: chunk insertion is idempotent (P1), chunk boundaries stay on UTF-8 runes (P2), and the rollback claim below is corrected (P2).

Compatibility, Security, and Operations

  • Defaults now render up to 256 KiB per snapshot; deployments that prefer the old memory profile can set TOKENHUB_AUDIT_PAYLOAD_SCAN_KB=64 and TOKENHUB_AUDIT_PAYLOAD_MAX_KB=8 to restore it.
  • Rollback is not a plain binary revert once a database has taken migration 12: the previous release refuses to start with unknown_applied_version (version 12) and the managed-rollback preflight reports the state as incompatible. Rolling back needs a bridge release of the previous binary whose registry knows version 12; the three operator guides state this next to the variable documentation. The new tables are otherwise additive, and the compatibility manifest moves to version 12.
  • Snapshots are redacted before chunking, so unredacted content never reaches the chunk store. The security-sensitive payload handling (pre-scan rejection, depth cap, redaction order) is preserved.

Checklist

  • The PR title and body are written in English.
  • Tests were added or updated for behavior changes.
  • No credentials, local .env files, databases, backups, or runtime logs are included.
  • Environment variable changes are synchronized across examples, Compose, start.sh, and deployment documentation.
  • Shared user-facing behavior is documented consistently in English, Simplified Chinese, and Japanese.
  • data/model-catalog.yaml remains tracked; no catalog changes in this PR.
  • git diff --check passes.

Agent-sized requests carry their full tool schema set and conversation
history on every call, so they overflow the 64 KiB audit scan budget and
their snapshots collapse to an omission marker. Operators could not
replay what a client actually sent for exactly the traffic where replay
matters most (astaxie#435).

Snapshot rendering now takes configurable limits via
TOKENHUB_AUDIT_PAYLOAD_SCAN_KB and TOKENHUB_AUDIT_PAYLOAD_MAX_KB
(defaults unchanged at 64/8). Snapshots larger than the inline preview
are stored once per distinct 16 KiB chunk in payload_chunks, referenced
in order from payload_chunk_refs, and reassembled when the request
detail is opened. Retention deletes orphaned references and unreferenced
chunks in batches. A measurement against real DSH agent traffic showed
92% tool-chunk and 87% message-chunk reuse, a 12.7x storage reduction,
and zero whole-payload repeats, which is why chunking rather than whole
body comparison.
The omission marker now carries the scan limit that rejected the body
and the setting that raises it, so an operator reading a stored
snapshot sees the fix next to the symptom instead of hunting the docs.

@astaxie astaxie left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Reviewed the complete diff at 361e8df212883dbc27f09e6a291cd668260548d5 against the PR base and issue #435.

Standards

One P2 finding is attached: the binary-rollback claim does not account for migration 12. An isolated SQLite probe using the exact prior migration registry confirms that both verification and migration reject the new ledger entry with unknown_applied_version.

Spec

Two findings are attached: P1 duplicate chunk insertion silently drops the complete audit payload, and P2 byte-based chunk boundaries produce invalid UTF-8 for PostgreSQL text storage. Independent probes reproduce a duplicate-key rollback with zero payload rows and invalid UTF-8 chunks from otherwise valid Chinese JSON.

Existing focused chunk round-trip, deduplication, retention and configurable-limit tests pass; the independent regression probes fail as described. GitHub CI passes on this head (the conditional LiteLLM E2E job is skipped). A live PostgreSQL runtime was unavailable, so PostgreSQL rejection was not exercised against a running server; the malformed chunk bytes and text column definition were verified. Full local suites were not rerun.

Findings: Standards 1 (P2); Spec 2 (highest P1).

// flags marking which side is chunked.
func payloadChunkDedupMigration() dbschema.Migration {
return dbschema.Migration{
Version: 12,

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[P2] Account for migration 12 before claiming binary rollback

The PR says old binaries ignore these additive tables and that rollback is a binary rollback, but the shipped base registry ends at version 11 and rejects unknown applied ledger versions. Once startup records this migration, reverting to that binary fails with dbschema: unknown_applied_version (version 12) before it can serve requests. An isolated SQLite probe with the exact base registry reproduces this in both Verify and Migrate. Please coordinate and test a compatible bridge release, and correct the PR plus English/Chinese/Japanese operator guidance to state the prerequisite; additive table shape alone does not provide the rollback compatibility required by docs/database-evolution.md.

if _, ok := knownSet[chunk.hash]; ok {
continue
}
if err := tx.Create(&PayloadChunk{Hash: chunk.hash, Body: chunk.body, CreatedAt: now}).Error; err != nil {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[P1] Make chunk insertion idempotent within and across requests

knownSet only contains hashes found before this loop and is never updated after an insert. If a new 16 KiB chunk occurs twice in one snapshot, its second insertion violates the primary key. With the default 64 KiB scan and 8 KiB preview, a content value of 50,000 repeated ASCII characters reproduces duplicated key not allowed; RecordRequestPayload rolls back and discards the error, leaving zero payload rows and losing both request and response snapshots. Concurrent PostgreSQL writers can also race the initial lookup for a shared new hash. Insert each hash idempotently, including database conflict handling, so the deduplication path preserves the audit record.

if end > len(body) {
end = len(body)
}
part := body[offset:end]

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[P2] Preserve UTF-8 when storing chunks in text columns

This fixed byte slice can split a multibyte character even when the rendered snapshot is valid UTF-8. A default-limit snapshot with content = "x" + strings.Repeat("汉", 7000) produces two invalid UTF-8 chunk strings in an independent probe. The PostgreSQL migration defines payload_chunks.body as text, which cannot accept those strings in a UTF-8 database, and RecordRequestPayload silently rolls back the entire request/response snapshot on the insertion error. Split on UTF-8 boundaries or store chunk bodies as binary data while preserving exact reassembly. The malformed chunks were reproduced locally; no live PostgreSQL instance was available for this check.

storePayloadChunkRefs only tracked hashes known before the insert loop,
so a snapshot whose content produced the same 16 KiB chunk twice failed
on the second primary-key insert, rolled back the transaction, and
dropped the whole request and response snapshot. RecordRequestPayload
swallowed the error, leaving zero payload rows.

Insert missing chunks with ON CONFLICT DO NOTHING and record every hash
the loop stores, which also covers a concurrent writer racing the initial
lookup. Regression test with uniform 64 KiB content reproduces the old
failure and passes with the fix.
Coding-agent requests carry 60-100 KiB of tool schemas plus history, so
the old 64 KiB scan budget omitted nearly every agent snapshot by
default and operators had to raise the variables by hand. 256 KiB
covers those requests end to end; the 64 KiB inline preview plus chunk
deduplication keep the storage growth bounded, and the remaining cost
is transient rendering memory of roughly 1.5 MB per oversized snapshot
(measured at the 192 KiB working point).
Chunk bodies are stored in text columns, and a byte slice cut through a
multibyte character is not valid UTF-8 for PostgreSQL. Splitting now
backs each boundary off to the nearest rune start, advances the offset
to that boundary instead of a fixed stride, and the regression test
renders a 120 KB Chinese-body snapshot through store and reassembly.
Once a database has taken migration 12, the previous release refuses to
start because its migration registry ends at version 11, and the
managed-rollback preflight reports the state as incompatible. Say so in
the three operator guides instead of implying that a plain binary
revert is safe.
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.

feat(audit): make snapshot size limits configurable for agent-sized payloads

2 participants