Skip to content

perf(storage): serialize each AgentRun event once on append - #5785

Merged
Astro-Han merged 1 commit into
apache:mainfrom
E2ern1ty:perf/agent-run-event-single-stringify
Sep 28, 2026
Merged

Astro-Han merged 1 commit into
apache:mainfrom
E2ern1ty:perf/agent-run-event-single-stringify

Conversation

@E2ern1ty

Copy link
Copy Markdown
Contributor

Summary

appendEvent — the ledger's hottest write path, run once per emitted agent-run event — serialized every event twice: once to clone it for decodeAgentRunEvent validation, and again inside insertAgentRunEvent for record_json. Both passes ran through sanitizeJson, a replacer that is provably identity (return value === undefined ? undefined : value is exactly what JSON.stringify already does), but passing any function replacer disables V8's fast path for the whole serialization.

decodeAgentRunEvent only validates — it injects no fields — so the caller's event and the decoded clone stringify identically. The append now serializes once and hands the same string to both the round-trip clone (which stays what detaches the store's copy from an object the caller may still hold) and the ledger row. The projection writer (writeSqliteAgentRunProjection, also inside the append transaction for checkpoint and latest-context events) drops the same identity replacer, and the now-unused sanitizeJson export is removed along with its last importer (the memory test double, which mirrored the same pattern).

Why not structuredClone: it is not behavior-equivalent here — it preserves undefined-valued own keys where JSON drops them, throws on values stringify silently skips, and preserves Dates/prototypes JSON flattens. The parsed object feeds both validation and record_json, so the JSON-normalizing semantics are load-bearing; this change keeps them by reusing the string itself.

Verification

  • Row bytes are unchanged: differential check over 5,005 events — hand-built edge cases (nested data, undefined-valued keys, arrays containing undefined, unicode/escapes, NaN/Infinity/-0, numeric-like keys, 20 KB payloads) plus 5,000 fuzzed nested payloads — confirms the old path (stringify(parse(stringify(E, replacer)), replacer)) and the new path (stringify(E)) produce byte-identical rows and identical validation inputs. 0 mismatches.
  • Serialization slice, measured: identity replacer penalty is 5.2x at 3.5 KB and 6.7x at 64 KB; per-event serialization work drops 67% (3.5 KB event: 36.4 → 11.8 µs) and ~60% (64 KB event: ~148 → ~57 µs).
  • End-to-end appendEvent on typical small events is SQLite-transaction-dominated (~107 µs/event, unchanged within noise); on 64 KB-payload events the direction shows (median ~449 → ~407 µs/event on a noisy machine). The win scales with event payload size, not event count.
  • npm --workspace @maka/storage run test:dist — 1539 pass / 0 fail; typecheck, biome clean.

AI use

Select exactly one:

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: ZCode authored the change, the differential verification script, and this description; all measurements are from real local runs.

Checklist

  • Tests cover the change and fail without it
  • Lint, format, typecheck and the affected suites pass locally

Note: behavior-preserving performance change; the existing suite plus the byte-level differential check above are the guards (a repo test cannot compare against the removed old serialization path).

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

appendEvent stringified every event twice — once to clone it for
validation, once inside insertAgentRunEvent for the ledger row — and
both passes went through sanitizeJson, a replacer that is provably
identity (returning undefined for undefined is what stringify already
does) but still disables V8's fast path. Measured on this machine, the
replacer alone is a 5.2x–6.7x slowdown of JSON.stringify.

decodeAgentRunEvent only validates — it injects no fields — so the
caller's event and the decoded clone stringify identically. The append
now serializes once and hands the same string to both the round-trip
clone and the row, and the projection writer drops the same identity
replacer. The unused sanitizeJson export is removed along with its
last importers (the memory test double mirrored the same pattern).

Row bytes are unchanged: a differential check over 5,005 events
(edge cases plus 5,000 fuzzed nested payloads) confirms the old path
and the new path produce byte-identical record_json and identical
validation inputs. Serialization work per event drops ~60–67%
(64 KB event: ~148 µs → ~57 µs); end-to-end appendEvent stays
transaction-dominated for typical small events.

Generated-by: ZCode
@github-actions github-actions Bot added the effort/S Under 100 readable lines label Sep 28, 2026

@hqhq1025 hqhq1025 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I reviewed the current head and found no substantiated P0–P3 in the changed paths. appendEvent now serializes the incoming event once, validates a parsed clone, and inserts the same JSON string in the ledger row within the existing transaction (agent-run-store.ts:145-178). The core decoder returns the validated object without adding or removing fields (agent-run.ts:238-255), so reserializing that clone was redundant. Removing the identity replacer from the projection writer and memory test store preserves ordinary JSON.stringify behavior (agent-run-store.ts:961-969; memory-execution-agent.ts:102-110).

I independently compared the former and current JSON row expressions across 5,000 synthetic events with nested values, undefined, non-finite numbers, Unicode, escaped strings, and numeric-like keys; all row strings matched. Current-head hosted test and label are successful, and fresh-main merge-tree/diff check are clean. I did not run the full storage suite or reproduce the PR’s performance measurements locally; those remain unverified by this review. This is not a merge approval.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

@Astro-Han

Copy link
Copy Markdown
Contributor

Thanks @E2ern1ty for the contribution and for following up on review feedback. Merging at @Astro-Han's request.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approved at @Astro-Han's explicit request: no blocking findings in the automated review of this head, and CI is green.

@Astro-Han
Astro-Han merged commit 076cdd1 into apache:main Sep 28, 2026
2 checks passed

@me2seeks me2seeks left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review notice: This comment was posted by an automated review agent operated by me2seeks make. It is not an independent human review and does not replace one.

Summary

Serializes each AgentRun event once on append instead of twice: the old sanitizeJson replacer and the redundant second JSON.stringify are removed, with the justification documented in code — decodeAgentRunEvent only validates (injects no fields), so the string form of the caller's event and of the decoded clone are identical, and the single JSON round-trip stays what detaches the store's copy from an object the caller may still hold. Behavior preserved, one serialization saved per appended event on the write path. label and test lanes pass.

Findings

No material findings. The single-serialization claim is proven, not assumed — the round-trip detachment property is named explicitly, and decodeAgentRunEvent's validate-only contract is the load-bearing fact.

Verdict

merge-ready — honest one-serialization win with the correctness argument in place; green CI.

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

Labels

effort/S Under 100 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants