Skip to content

perf: compile measured nested tool validation - #147971

Merged
steipete merged 13 commits into
mainfrom
codex/compile-runtime-zod
Sep 14, 2026
Merged

steipete merged 13 commits into
mainfrom
codex/compile-runtime-zod

Conversation

@steipete

@steipete steipete commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Nested tool activity history repeatedly validates one schema; three readers rebuild stable array schemas. These costs are avoidable, but compiling every schema adds first-use work many callers cannot recover.

User Impact

Compile only nested tool activity validation with Zod 4.5.4's z.compile(schema). The customType precheck skips ordinary transcript rows. First matching read or creation initializes one compiled schema, shared across Gateway turns. Payload bounds, cloning and validation contracts stay unchanged.

ClawHub recommendations, Workboard events and memory events reuse ordinary schemas. Browser-shared schemas remain uncompiled for strict CSP: explicit compilation attempts code generation even with jitless. No global compiler hook, dependency change, migration or z.validate cutover is introduced.

Why This Change Was Made

Config compilation raised first parsing 9.13 → 157.38 ms; cached config reads avoid parsing. Against uncompiled boolean validation, compiled validation left 4,096-row session-manager JSONL loading unchanged at 18.70 → 18.71 ms (existing safeParse: 20.07 ms); first 20-row loading rose 3.35 → 7.26 ms. Neither boolean-validation variant is adopted. Relay compilation added 0.41 ms initially, with inconsistent larger-exchange gains. All three compilation candidates were rejected.

Nested compilation costs 1.42 ms, conservatively recovered after 3,400 matching reads or 67 scans of 512 mixed rows. The separately measured incremental first-read penalty was 0.174 ms; baseline first parsing already pays initialization cost. Production call frequency remains unmeasured.

Evidence

Synthetic measurements used Node 26.8.2 / Zod 4.5.4:

Measured operation Before After
Read one small nested activity 0.483 µs 0.061 µs
Scan 512 rows, including 52 activities 28.20 µs 6.95 µs
Create one small nested activity 2.74 µs 2.20 µs
Read three recommendations, schema reuse 6.16 µs 1.77 µs
Normalize eight Workboard events, schema reuse 12.02 µs 5.30 µs
Normalize ten recall records, schema reuse 4.51 µs 2.95 µs

Nested reads improved 7.3–8.3×. Parity passed for 18 nested, 19 relay, 46 reuse and 534 codec cases. Nested measurements call exported APIs; reuse measurements extract reader closures. Workboard uses jitless in Node. Reuse first-call costs were mixed. These are not whole-Gateway throughput or startup measurements.

Published 3749e163 passes three Bash cases and fresh independent P2 review, retaining main's exact diagnostic test. Prior 6b6e1faf passed 15 focused cases, build, Gateway/UI types and lint/formatting; these were not rerun. The four optimization owners, Workboard references and remaining PR test diffs are unchanged. Its CI 34906851601 completed SUCCESS: 132 successes and 13 skips, including theme and real-Gateway checks. Final-head CI 34908142383 also completed SUCCESS: 132 successes, 13 skips, zero failures.

The previous normal run failed one theme case plus its aggregate. The hosted fallback also failed desktop reconnection and Windows startup checks. Neither failed run qualifies the new head; no gates or budgets were changed.

Retained fixture repairs

The Reports theme fixture visits /chat, waits for bootstrap to publish embedSandboxMode: scripts, then opens Reports. CI captured the fixture script blocked by the initial strict sandbox; the isolated original case passed locally. This fixes fixture ordering without changing production CSP.

CLI-auth initial acquisition uses the standard 180-second hook budget, preserving the 90-second body, six native transitions, real restart and the original 30 assertions within main's expanded 34-assertion coverage. Cleanup joins acquisition/body work and closes the current Gateway. Other retained repairs cover Discord mock initialization and memory close-entry synchronization. Main owns Bash diagnostics, wizard routing, Radius relocation, cloud, Custodian, website and SDK pooling fixes.

@steipete steipete self-assigned this Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: signal Channel integration: signal channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: voice-call Channel integration: voice-call channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes scripts Repository scripts commands Command implementations docker Docker and sandbox tooling agents Agent runtime and tooling channel: feishu Channel integration: feishu channel: twitch Channel integration: twitch channel: irc extensions: acpx labels Sep 14, 2026
@steipete
steipete requested a review from a team as a code owner September 14, 2026 06:01
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 14, 2026, 7:44 PM ET / 23:44 UTC (Revision 28).

ClawSweeper review

What this changes

The PR reduces repeated validation work in nested tool history, recommendations, Workboard events, and memory events, documents measurements, and stabilizes supporting test fixtures.

Merge readiness

⛔ Blocked before merge - 1 item remains

The optimization remains useful and is not present on inspected main. No blocking defect was found. The earlier migration blocker does not apply: the patch preserves persisted formats, validation rules, and storage operations.

Priority: P2
Reviewed head: 3749e16361c02a88242c917581f178b955471dae

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, measured optimization with preserved contracts, successful exact-head CI, and no blocking findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied maintainer-author context exempts ordinary contributor proof. Reported exported-API measurements cover nested validation, with synthetic parity and exact-head CI as supporting evidence; they do not claim whole-Gateway performance. No material authority change triggers additional final-effect proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied maintainer-author context exempts ordinary contributor proof. Reported exported-API measurements cover nested validation, with synthetic parity and exact-head CI as supporting evidence; they do not claim whole-Gateway performance. No material authority change triggers additional final-effect proof.
Evidence reviewed 9 items Pinned implementation: The introduced delta retains the existing activity schema and payload bounds, adding one lazy compiled instance used by creation and matching reads. Ordinary transcript rows retain their existing precheck.
Storage blocker resolved: The complete event-store module and introduced diff show only three reusable array schemas. Event fields, truncation, serialization, journal namespaces, sequence allocation, retention, and write operations are unchanged. This supports the author's explanation at #147971 (comment) and resolves the prior review's generic migration request.
Verified compiler dependency contract: The direct z.compile call establishes the dependency signal. GitHub identifies Zod v4.5.4 with this commit; its compiler clones the schema, retains the original parser for invalid input, and returns the original schema when compilation cannot be supported. Object generation retains strict-key checks and declared output order.
Findings None None.
Security None None.

How this fits together

Nested tool activity records carry tool inputs and results into session history and Gateway display projections. Their validator checks those records before creation or reading; the other changed readers normalize recommendations and event data.

flowchart TD
  A[Completed nested tool call] --> B[Bound and clone payload]
  B --> C[Lazy compiled validator]
  D[Transcript row] --> E{Nested activity?}
  E -->|Yes| C
  E -->|No| F[Ordinary history path]
  C --> G[Validated activity]
  G --> H[Session history and display]
Loading

Before merge

  • Resolve merge risk (P1) - Production call frequency remains unmeasured, so the synthetic speedups do not establish a whole-Gateway latency or throughput improvement.
Agent review details

Security

None.

PR surface

Source +11, Tests +151. Total +162 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 29 18 +11
Tests 6 356 205 +151
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 385 223 +162

Review metrics

Metric Value Why it matters
Compilation amortization Reported 1.42 ms compilation cost; approximately 3,400 matching reads to recover The PR quantifies the cold-cost tradeoff and confines compilation to its measured repeated path.

Stored data model

Persistent data-model change detected: unknown-data-model-change: src/memory-host-sdk/event-store.ts. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Retain selective compilation at the existing nested-activity owner and ordinary schema reuse elsewhere, preserving browser CSP and persisted-data contracts.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Retain selective compilation at the existing nested-activity owner and ordinary schema reuse elsewhere, preserving browser CSP and persisted-data contracts.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a functional bug reproduction: this is a performance optimization supported by reported synthetic measurements. This read-only review did not execute benchmarks or tests.

Is this the best way to solve the issue?

Yes. The final patch keeps one validation owner, avoids global compiler activation, and preserves existing parsing and storage contracts; the earlier migration request has no supporting introduced change.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 04aa9a8e318c.

Labels

Label justifications:

  • P2: This is a bounded runtime performance improvement without evidence of an urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied maintainer-author context exempts ordinary contributor proof. Reported exported-API measurements cover nested validation, with synthetic parity and exact-head CI as supporting evidence; they do not claim whole-Gateway performance. No material authority change triggers additional final-effect proof.

Evidence

What I checked:

  • Pinned implementation: The introduced delta retains the existing activity schema and payload bounds, adding one lazy compiled instance used by creation and matching reads. Ordinary transcript rows retain their existing precheck. (src/sessions/nested-tool-activity.ts:33, 3749e16361c0)
  • Storage blocker resolved: The complete event-store module and introduced diff show only three reusable array schemas. Event fields, truncation, serialization, journal namespaces, sequence allocation, retention, and write operations are unchanged. This supports the author's explanation at perf: compile measured nested tool validation #147971 (comment) and resolves the prior review's generic migration request. (src/memory-host-sdk/event-store.ts:45, 3749e16361c0)
  • Verified compiler dependency contract: The direct z.compile call establishes the dependency signal. GitHub identifies Zod v4.5.4 with this commit; its compiler clones the schema, retains the original parser for invalid input, and returns the original schema when compilation cannot be supported. Object generation retains strict-key checks and declared output order. (packages/zod/src/v4/core/compile.ts:117, e8e206fa33ac)
  • Browser and authority boundaries preserved: Workboard only reuses its ordinary tolerant-array schema; recommendations likewise remain uncompiled. The UI change orders a scripted test fixture after bootstrap without changing production CSP. Nested activity creation remains downstream of tool execution, with existing live-run validation before transcript append; no authorization decision or final-effect authority is changed. (extensions/workboard/browser/lib/workboard/metadata-normalization.ts:88, 3749e16361c0)
  • Fixture lifecycle review: The CLI-auth fixture separates acquisition from behavioral assertions, joins acquisition and body work during cleanup, and closes the current Gateway after restart. Existing account-selection and history assertions remain; the cancellation case exercises the preparation owner. The shared configuration already provides the 180-second hook budget. (src/gateway/server.chat-cli-auth.test.ts:145, 3749e16361c0)
  • Exact-head CI verified: GitHub reports completed success for the linked pull-request CI run on the exact reviewed head. This is supplemental validation, not a whole-Gateway performance measurement. (3749e16361c0)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (27 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-14T20:40:50.911Z sha dcacf1b :: blocked before merge. :: none
  • reviewed 2026-09-14T20:55:45.259Z sha e89b674 :: blocked before merge. :: none
  • reviewed 2026-09-14T22:01:46.568Z sha 57b768c :: blocked before merge. :: none
  • reviewed 2026-09-14T22:09:15.895Z sha 57b768c :: blocked before merge. :: none
  • reviewed 2026-09-14T22:35:31.601Z sha 57b768c :: blocked before merge. :: none
  • reviewed 2026-09-14T23:06:32.025Z sha 6b6e1fa :: blocked before merge. :: none
  • reviewed 2026-09-14T23:12:46.942Z sha 6b6e1fa :: blocked before merge. :: none
  • reviewed 2026-09-14T23:30:17.823Z sha 3749e16 :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/compile-runtime-zod branch 2 times, most recently from fbc7b2c to 3ac5219 Compare September 14, 2026 08:22
@steipete

steipete commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author

The final revision compiles only nested tool activity, once at first use; ordinary transcript rows bypass it. Three other readers reuse ordinary schemas. The PR body records measured gains, cold cost, rejected candidates and the limits of synthetic measurements.

Schema definitions, defaults, parsed and serialized output, stored formats, permissions and dependency versions are unchanged. The memory-event diff only reuses three array schemas. No data-model migration is needed; the latest review’s technical evidence confirms the existing storage contract is retained, so its generic migration checkbox does not apply.

Final head 3749e16361c02a88242c917581f178b955471dae passed CI 34908142383: 132 successful jobs, 13 skipped, zero failures. Independent P0–P2 review is clean. Prior measured-owner and integration evidence remains scoped in the PR body; the earlier failed runs remain available there.

@steipete
steipete force-pushed the codex/compile-runtime-zod branch 2 times, most recently from 694397d to 7eee505 Compare September 14, 2026 11:10
@openclaw-barnacle openclaw-barnacle Bot added the extensions: memory-core Extension: memory-core label Sep 14, 2026
@steipete
steipete force-pushed the codex/compile-runtime-zod branch from fa13a6a to 948fc7a Compare September 14, 2026 12:24
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Sep 14, 2026
Enable native lazy Zod compilation across core, plugins, workers, and tooling. Preserve existing schemas, parse results, and runtime fallbacks for unsupported schemas and strict-CSP browsers. Warm synthetic validation improves while first-use compilation adds CPU and memory cost.
Cache stable recommendation, dashboard, memory-event, and Workboard schemas so repeated reads do not repeat compilation. Preserve validation and serialized output, and resolve side-effect imports in the relocated updater survival fixture.
Load the Discord voice runtime before its realtime sibling so their shared async audio mock completes once. Concurrent imports can otherwise return separate export objects and leave WAV writer spies disconnected from the running consumer. Preserve every assertion and timeout.
Keep gateway-lock within the existing line limit by inlining its temporary cmdline string. Remove a duplicate wizard recovery entry introduced by overlapping database-worker routing fixes, preserving its canonical fork ownership.

Apply the existing wizard choice-button interaction from #148444 while retaining typed answer, session rotation, and no-replay assertions.

Validation: 175 tooling/config, 46 gateway-lock, and 53 UI lifecycle/render/submission cases passed; focused formatting/lint and independent P2 review passed. No schema, policy, deadline, threshold, or expectation changes.
Replace process-wide Zod compiler activation with one lazy compiled schema at the nested-tool activity owner. Ordinary transcript rows bypass compilation and the parsed-output contract is unchanged.

Keep measured schema reuse for recommendation reads, Workboard event normalization, and memory event storage normalization. Config, transcript-entry, and relay-frame compilation did not justify their caller or first-use costs.

Synthetic Node 26.8.2/Zod 4.5.4 measurements: nested reads 0.483 to 0.061 microseconds; 512 mixed rows 28.2 to 6.95 microseconds; approximately 1.42 ms compilation cost and 0.174 ms additional first-read cost. Full session-load results did not establish a compilation win. Schema reuse reduced representative reads from 6.16 to 1.77, 12.02 to 5.30, and 4.51 to 2.95 microseconds without compilation. These are measured boundaries, not aggregate Gateway throughput.

Validation: 232 focused tests, including persistence, history projection, Workboard and strict-CSP browser startup; core/extension typechecks, targeted lint, formatting, and independent P2 review. Preserve schema definitions, serialized output, stored formats, permissions, and dependency versions.
Preserve the reviewed production optimization unchanged while integrating current main. Keep main's cloud reply identity and startup-discovery fixtures alongside the provider close-entry synchronization.

Restore one canonical wizard recovery test registration after overlapping upstream deduplication changes removed the last entry. The unregistered test reproduced a host-broker admission failure; all eight cases pass with fork routing restored.

Validation: 18 integration cases across wizard recovery, provider lifecycle, and cloud reconciliation; formatting, PR-diff whitespace checks, and fresh independent P2 review passed. Frozen dependencies match main's Vitest patch. Earlier measured production behavior and 232-case selective proof remain unchanged and scoped; final CI is required.
Keep the six generic provider-auth URL-routing cases in core. Move the two registered Radius device-flow cases to the existing root plugin integration test surface, which admits the real plugin entrypoint and is checked outside core TypeScript graphs.

Preserve device destination, code and expiry, browser suppression, cancellation, awaited settlement, and single-fetch assertions. No production changes or boundary exceptions.

Validation: 31 behavior and boundary tests, the complete core TypeScript boundary guard, root test typecheck, scoped lint, formatting, and independent P2 review passed.
Prepare each isolated real Gateway and Claude CLI fixture in beforeEach under the existing fixture-hook budget. Keep the six ordered account transitions, real restart, and every auth/history assertion inside the unchanged 90-second behavior deadline.

Register cleanup before awaiting acquisition, join acquisition and case work, and close the current Gateway after restart. Failed preparation cleans partial resources; the cancellation regression exercises the same preparation owner.

CI exposed cold setup consuming the account test's deadline. A restored local phase probe measured 39.74 seconds for initial Gateway startup, 10.92 seconds for the first turn, and 4.21 seconds for the remaining five turns; shutdown was brief. No timeout values, mocks, or assertions are relaxed.

Validation: all six cases pass with the explicit CI configuration, including cancellation; gateway test types, lint, formatting, and independent P2 review pass.
Integrate current main, retain the measured Zod optimization, and remove the Radius test copy now owned by main. Start the scripted plugin theme fixture only after bootstrap publishes its existing sandbox policy. All theme and no-reload assertions remain unchanged.
Retain main’s equivalent native Bash assertion diagnostics and remove the superseded PR delta. All three policy cases and their assertions remain unchanged; focused verification and independent review pass.
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

Labels

app: web-ui App: web-ui channel: discord Channel integration: discord docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. plugin: workboard rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant