Skip to content

perf(gateway): reuse prepared display projections - #133203

Merged
steipete merged 1 commit into
mainfrom
codex/perf50-gateway-projections
Aug 30, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf50-gateway-projections

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway display requests repeatedly compute results they already have: bounded session ordering scans candidates that cannot enter the page, child-link projection evaluates parents outside the selected page, status builds the same completed row twice, anchored history repeatedly copies and recounts its growing window, and progress updates serialize retained events twice.

Why This Change Was Made

Keep preparation at the existing owners and carry its results through the request:

  • Reject out-of-window session candidates after checking the first and last selected rows; preserve stable ordering and the unbounded sort path.
  • Use one child-link evaluator for selected parents, exact-row callers and row fallbacks. Delete the duplicate full-map/context builders and per-row sparse validation.
  • Reuse completed status rows within one request, returning independent DTOs and flags for the aggregate view.
  • Accumulate anchored-history group costs once. Both private callers use additive count or exact JSON-byte budgets; return one final slice.
  • Combine superseded startup/item removal and recount retained progress payloads once. Mutable nested payloads still receive a full recount.

Production +146/−170, net −24; existing test-helper migration +2/−3, net −1, with its assertions retained. No config, schema, protocol, authorization or persistence change; no new dependency or process cache.

Contracts and Tradeoffs

The child-link refactor preserves the two existing registry read policies. A real external SQLite writer demonstrated that the scalar and prepared registry caches can differ within their existing 500 ms lifetime. Short-list reads still use the scalar policy, including its stricter missing-controller behavior; prepared lists keep their snapshot. Hidden children, current controllers, explicit navigation parents, recent terminal links and active descendants remain covered.

Status now deliberately returns the same completed ACP/runtime projection in the per-agent and aggregate views of one summary, even if a backend changes between those phases. Later requests read again. It keeps the first scalar ACP read and its legacy-binding behavior; the batch ACP API is not substituted.

History retains exact sequence groups, first matching anchor, older-before-newer growth, independent blocked directions, oversized-group fallback and archive metadata. For a nonempty JSON array, its cost is one framing byte plus the sum of each message's bytes and separator. Progress keeps sequence rejection, first-seen preamble time, independent Guardian review IDs, strict-review resolution and whole-tool eviction. Native Codex Guardian contracts were checked directly; no approval behavior changes.

Measurements and Verification

Fresh Node 26.8.1 processes, opposite starting orders, uninstrumented complete owners and retained raw samples:

Workload Observed change
10,000 randomly ordered sessions, limit 100 ~3.84 ms → 213–223 µs; comparisons 969,386 → 44,725
300 stored parents, 10 selected list rows 2.68–2.97 ms → 1.56–1.72 ms (~42% lower)
Default status with one agent and 30 sessions 56.48–58.44 ms → 29.07–30.31 ms (~48% lower)
1,000-row anchored history including fresh byte preparation 2.63–2.64 ms → 0.31–0.32 ms; growing-window reference copies 501,500 → 1,000
Progress update with 49 retained 2 KB events 184.98–190.41 µs → 94.04–97.44 µs (~49% lower)

These are local owner/workload measurements, not whole-turn or network latency claims. Small controls are retained: already favorable top-N ordering is 1.7–4.1% slower; short/grouped history selections can cost an extra 0.03–0.08 µs; several tiny list/status/progress cases are noisy or slightly slower. No isolated memory saving is claimed.

Source-bound probes cover 4,960 top-N outputs, 52 complete SQLite-backed status comparisons with 652 identities, 6,768 anchor outputs with 61,391 identities, 189 child comparisons including 174 complete lists, and 8,461 progress comparisons with 25,352 snapshot identities. Mutable nested payloads, real external writer state and final DTO identity are explicitly exercised.

The baseline and initial candidate both passed 471 selected tests across 11 files, including real Gateway history tests for anchors, archives, rejected selectors and byte budgets. The initial changed-file gate passed all type/boundary/dead-export checks but rejected an invariant sequence condition in two loops; the final form restores the original early return without a suppression. Final local checks and live evidence follow; hosted CI must be green before landing.

Final local changed-file checks passed in 190.75 seconds, including core/test types, lint, boundary/dead-export/import and state guards. The 15 affected history checks passed again after the loop cleanup. Independent source review is clean; the fresh automated Codex review reported no actionable findings at its configured P0 threshold. The patch was rebased unchanged onto merged main 5cb702d464a7869e3a1dc4b6f85361d91f3e4291; the published head is 28435c17c5a10bddae877fef233fd5e82e4a90a5. All 471 selected tests passed again at that head, followed by a fresh build in 166.34 seconds.

At that exact published head, the isolated real-OpenAI Gateway completed a three-turn chat conversation with two actual web_fetch calls, then a separate native web-search turn. A newly connected read-only client recovered the active run and retained tool progress with the exact run/tool identity. Real transcript anchors at limits 1/3/100, bounded session ordering, matching aggregate/per-agent status, restricted status, terminal cleanup, and unchanged baseline previews/tool inventories/catalog passed 81 assertions across 32 RPC calls. Node CPU profiles were retained and the owned Gateway stopped cleanly. The live run does not simulate child-controller concurrency or Guardian approvals; those retain the complete-owner and canonical test evidence above.

Landing Review

The latest ClawSweeper review found no introduced code defect but could not obtain the sibling Codex checkout in its environment. The maintainer directly inspected the local public Codex checkout at 6478a751fde8884b2fdc76486fe23175a8e795d4: Guardian started/completed notifications and assessment lifecycle identity. At that source version, stable review IDs, optional targets and multiple reviews per command match the retained projection behavior; the refactor still replaces only the matching review and preserves standalone/strict-review handling. A second independent reviewer checked the producer and notification mapping too. This resolves the source-inspection limitation. The rank-up request for exact-head Gateway validation is satisfied by the build/live proof above. Maintainer review accepts the scoped status-snapshot choice and disclosed small timing costs; exact-head CI run 33302579327 is now green.

@clawsweeper

clawsweeper Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Aug 30, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 4:55 AM ET / 08:55 UTC.

ClawSweeper review

What this changes

This PR refactors Gateway display preparation so session lists, status summaries, anchored history, and progress snapshots reuse per-request work instead of repeating scans, projections, copies, and byte counts.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this maintainer-authored Gateway refactor open for normal review. The introduced code preserves the reviewed list, history, progress, and status invariants, but the PR’s Codex Guardian contract assertion could not be independently checked because the required sibling Codex source checkout is absent and DNS prevented obtaining it.

Priority: P3
Reviewed head: 28435c17c5a10bddae877fef233fd5e82e4a90a5
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A net-negative, focused refactor with no concrete introduced defect found; merge confidence still requires the repository-mandated Codex contract check.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored internal performance refactor is exempt from the external-contributor proof gate; the ordinary tests and local measurements in the body are supplemental, while direct Codex-source verification remains a reviewer limitation for its Guardian assertion.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored internal performance refactor is exempt from the external-contributor proof gate; the ordinary tests and local measurements in the body are supplemental, while direct Codex-source verification remains a reviewer limitation for its Guardian assertion.
Evidence reviewed 7 items Selected-parent child projection: The new index evaluates only selected parents while retaining the existing candidate cache, liveness test, controller ownership rule, and filtered-child exclusion.
List caller and sibling coverage: The list path deliberately keeps snapshot reads for prepared/filtering cases and scalar reads for short lists; existing tests cover navigation-vs-runtime ownership and stale links.
Exact history-byte accounting: The new cost expression equals the established JSON-array byte formula: one framing byte plus each message and separator, against a budget reduced by one.
Findings None None.
Security None None.

How this fits together

The Gateway converts session, run, transcript, and progress state into display-safe RPC responses. These projections feed session lists, status output, history pages, and reconnect snapshots.

flowchart LR
  A[Session and run state] --> B[Gateway display preparation]
  C[Transcript and progress events] --> B
  B --> D[Session list]
  B --> E[Status summary]
  B --> F[History page]
  B --> G[Reconnect snapshot]
Loading

Decision needed

Question Recommendation
Can a maintainer with the required sibling Codex checkout verify that the unchanged Guardian event handling remains compatible with the asserted Codex contract? Verify the Codex contract: Inspect the Guardian event definitions and confirm that this refactor does not alter their reconnect projection semantics before merging.

Why: Repository policy requires direct inspection of that source before a Codex contract or merge verdict, and this read-only environment cannot obtain the checkout.

Before merge

  • Resolve merge risk (P1) - The Codex Guardian compatibility assertion in the PR body remains unverified in this review environment; it needs direct sibling-Codex source inspection before merge.
  • Complete next step (P2) - A maintainer with the mandated Codex source checkout must verify the PR body’s Guardian-contract assertion before merge.
Agent review details

Security

None.

PR surface

Source -24, Tests -1. Total -25 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 10 146 170 -24
Tests 1 2 3 -1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 148 173 -25

Review metrics

Metric Value Why it matters
Production versus test delta production +146/-170 (net -24); tests +2/-3 (net -1) The refactor is net-negative production code; its semantic coverage relies on existing Gateway tests rather than new behavioral assertions.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Retain the single selected-parent projection and cached status-row approach, then verify the unchanged Guardian event contract against the actual Codex source before landing.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Retain the single selected-parent projection and cached status-row approach, then verify the unchanged Guardian event contract against the actual Codex source before landing.

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

Not applicable: this PR is a behavior-preserving performance refactor, not a report of a current user-visible bug. Read-only source comparison supports its intended equivalence but did not execute target code.

Is this the best way to solve the issue?

Unclear: the selected-parent and accumulated-cost designs fit the existing owner boundaries and no introduced defect was found, but the stated Codex Guardian contract evidence cannot be confirmed here.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 039187abe405.

Labels

Label changes:

  • add P3: This is a bounded internal performance refactor with no demonstrated user-facing regression.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored internal performance refactor is exempt from the external-contributor proof gate; the ordinary tests and local measurements in the body are supplemental, while direct Codex-source verification remains a reviewer limitation for its Guardian assertion.

Label justifications:

  • P3: This is a bounded internal performance refactor with no demonstrated 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: This maintainer-authored internal performance refactor is exempt from the external-contributor proof gate; the ordinary tests and local measurements in the body are supplemental, while direct Codex-source verification remains a reviewer limitation for its Guardian assertion.

Evidence

What I checked:

  • Selected-parent child projection: The new index evaluates only selected parents while retaining the existing candidate cache, liveness test, controller ownership rule, and filtered-child exclusion. (src/gateway/session-utils-core.ts:419, 28435c17c5a1)
  • List caller and sibling coverage: The list path deliberately keeps snapshot reads for prepared/filtering cases and scalar reads for short lists; existing tests cover navigation-vs-runtime ownership and stale links. (src/gateway/session-utils-list.ts:483, 28435c17c5a1)
  • Exact history-byte accounting: The new cost expression equals the established JSON-array byte formula: one framing byte plus each message and separator, against a budget reduced by one. (src/gateway/server-methods/chat-history-handler.ts:381, 28435c17c5a1)
  • Progress and ordering invariants: The progress change preserves the startup early return and combines equivalent removals; bounded ordering retains the total stable comparator and discards only candidates no better than the retained worst row. (src/gateway/server-chat-progress-snapshot.ts:100, 28435c17c5a1)
  • Current-main merge context: The verified test merge applies this exact head after current main and changes the same eleven Gateway/status files; current main itself retains the pre-refactor paths. (58df9b4795fb)
  • Codex contract limitation: The PR touches the progress snapshot that recognizes Codex Guardian events, and its body asserts direct Guardian-contract checking. The required sibling Codex source was not present; its review-artifact directory contains no source checkout, and network DNS prevented cloning. (src/gateway/server-chat-progress-snapshot.ts:52, 28435c17c5a1)

Likely related people:

  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Verify the Guardian event contract against the sibling Codex source and complete the stated exact-head Gateway validation.

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.

@steipete
steipete merged commit 8243cc8 into main Aug 30, 2026
260 checks passed
@steipete
steipete deleted the codex/perf50-gateway-projections branch August 30, 2026 09:06
@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

gateway Gateway runtime maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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