Skip to content

improve(gateway): reduce session metadata read costs - #136391

Merged
steipete merged 3 commits into
mainfrom
codex/gateway-session-metadata-projections
Sep 2, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/gateway-session-metadata-projections

Conversation

@steipete

@steipete steipete commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway session metadata reads decode saved skills and system-prompt snapshots that the UI never consumes. Exact metadata lookups discard those fields only after parsing, and a borrowed metadata view's get ignores the projection that its entries method honors. History/startup reads also hydrate the full parent and direct-child entries.

Why This Change Was Made

Move metadata projection into the shared SQLite query/parser boundary and carry it through exact, child, history, startup, and chat-metadata reads. Reuse the existing listing projection instead of maintaining consumer-side stripping. Consolidate 19 duplicated accessor type definitions into their canonical definitions, retaining SQLite-specific contracts separately.

Full reads and raw JSON comparison bytes remain intact. Canonical-key checks, owner/participant projections, read-only missing-store behavior, cache freshness, and corrupt/retained-row handling are preserved. The SQL projection retains corrupt prompt-only objects rather than converting them into the retained-window {} sentinel; overdepth JSON still reaches the original parser. No schema, index, transaction, concurrency policy, configuration, dependency, or protocol change.

Production LOC: +134 / -252, net -118. Tests and test support: +63 / -26, net +37.

User Impact

Less work and allocation when session metadata contains large saved prompts. This fixes inconsistent metadata projection and reduces duplication; it does not claim to eliminate Gateway saturation.

Evidence

The original 148 focused cases passed. New assertions failed on the parent for both writable/borrowed Gateway prompt decoding and exact borrowed-view projection. The final owner and sibling proof totals 637 passing cases across nine files, plus the built-CLI lifecycle proof, including history/startup, ownership/participants, canonical routing, corruption, retained windows, same-timestamp updates, and rollback. One cache-test observer needed to forward the new parser argument and exclude exact CAS reads now sharing the decoder; its count/byte budgets remain, and rollback now exercises the actual list cache. Independent Codex review is scoped-clean through P2 for the production refactor and both CI fixture corrections.

Controlled Blacksmith Testbox run: command exit 0; worker stopped after artifact verification. Baseline e9f322ff2326abcf4cea736786827e1b737c4774; final production afterimages exactly match the measured candidate. Each revision installed and built sourcePerformance separately, with all 36,679 source entries and 8,783 build entries verified unchanged. Node 24, four-CPU affinity, fresh HOME/state and loopback ports. Synthetic streaming provider; real Gateway HTTP/RPC. No operator or production Gateway was used.

All 10 load runs passed the unchanged 2000ms control/handshake budgets with zero operation failures and zero plugin metadata rescans. Workload: 32/64 turns, 48 seed sessions, 128 updates/4 clients, 3 history clients × 5 burst, 6 visible subscribers, 100ms cadence, 1000ms stream delay. Before/after/after/before at each concurrency, plus separate 64-turn CPU profiles.

At 64 turns, candidate history p99 was 624.6 / 626.6ms, versus 993.5 / 627.0ms before. Candidate sessions.list maxima were 599.9 / 606.9ms, versus 985.0 / 608.6ms before. Typical tails are similar; the slower first baseline repetition is not attributed wholly to this patch.

Component medians over 12 rounds of 100 reads, same worker, 48 rows:

Saved prompt bytes Read Before After
65,536 Parent + eight children 0.483ms 0.392ms
524,288 Single metadata row 0.414ms 0.228ms
524,288 Parent + eight children 5.016ms 1.507ms

The fixture uses one long prompt string, not every real prompt shape. Small-row metadata overhead increased by roughly 9µs; full-read timings were close. No universal speedup or memory-leak claim is made.

Residual saturation remains: candidate readiness degraded in 283/283 samples and median event-loop utilization stayed 1. Profiled transaction stacks occupied 17.57% before / 16.27% after, history handlers 11.95% / 11.43%; inclusive costs overlap and are not additive. RSS varied across repetitions.

Artifact bundle SHA-256: 80d62b3f1c3f12cd9a73e258edee2403319caf9355427aa4a4b8a7d18b46ca5e. The full changed-code gate and final local cache-fixture gate both exited 0. The one-shot worker stopped. Final exact-head CI passed on 4f421e2036e7721330cc37461f1654a08622ee78, including the aggregate gate, both Windows jobs, and the built-artifact lifecycle proof.

On initial head d70dd0e, CI run 33649514321 attempt 1 lost its self-hosted runners before any test step; one unchanged-head retry used the workflow’s existing hosted fallback. Attempt 2 passed 227 checks and exposed two failures (plus the aggregate gate). The exact history-alias expectation now includes the metadata projection, preserving all other arguments; its complete 213-case file passed in original order. The built-CLI lifecycle proof requested a 293,362-byte all-plugin inventory through a 256 KiB log-tail helper. It now inspects only its explicit OpenAI provider artifact (4,097 bytes), retaining the bundled identity and built-path assertion without changing any limit. The complete real Gateway/mock-provider lifecycle proof passed in 147 seconds. No failed assertion, test, buffer bound, or latency budget was removed or relaxed.

Maintainer Disposition

Accepted for landing as the requested internal session-read refactor. The latest completed ClawSweeper review covers this exact head and found no code or security defect; its outstanding CI condition is now satisfied. The read-only projection preserves existing storage semantics, and the residual saturation and measurement limitations above remain explicit. No required check or review rule is bypassed.

Unify exact, child and list metadata projections at the read boundary. Preserve full session payloads and write CAS bytes, and reuse the canonical accessor types instead of duplicating their contracts.
@clawsweeper

clawsweeper Bot commented Sep 2, 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 Sep 2, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 2, 2026, 12:28 PM ET / 16:28 UTC.

ClawSweeper review

What this changes

The PR moves session metadata projection into shared SQLite reads so Gateway metadata and history paths avoid decoding unused saved-prompt fields while full reads retain them.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this maintainer-authored PR open. The shared projection change is source-consistent across exact, child, metadata, history, and cache reads; no introduced correctness or security defect was found, but exact-head CI is still queued and maintainer approval is required.

Priority: P2
Reviewed head: 4f421e2036e7721330cc37461f1654a08622ee78
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, net-negative refactor with strong boundary coverage and production-boundary performance evidence; exact-head CI and maintainer approval remain outstanding.
Proof confidence 🦞 diamond lobster (5/6) Not applicable: This maintainer-authored PR includes a linked controlled real Gateway HTTP/RPC Testbox run for the changed session-read path; exact-head CI remains the outstanding merge gate.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR includes a linked controlled real Gateway HTTP/RPC Testbox run for the changed session-read path; exact-head CI remains the outstanding merge gate.
Evidence reviewed 6 items Shared projection owner: The introduced shared selector preserves owner columns and selects prompt-stripped JSON only for list reads; malformed or identity-less rows remain raw for the existing parser.
Exact and child read semantics: Exact and child paths retain current-session and timestamp fields needed for retained-window validation, then apply the same requested projection to parsing.
Gateway caller coverage: Chat metadata and history pass projection:list into the read-only Gateway session lookup, whose exact-key and direct-child paths forward that mode rather than deleting fields in consumers.
Findings None None.
Security None None.

How this fits together

Gateway metadata and history endpoints read agent session records from SQLite before returning client-facing session information. The new metadata-only mode removes saved prompt snapshots before decoding and flows through exact and child session lookups.

flowchart LR
  A[Gateway metadata request] --> C[Session-store lookup]
  B[Gateway history request] --> C
  C --> D[SQLite session rows]
  D --> E{Read projection}
  E -->|Metadata| F[Omit saved prompt fields]
  E -->|Full| G[Decode full session entry]
  F --> H[Gateway response]
  G --> H
Loading

Decision needed

Question Recommendation
After the queued exact-head checks pass, should this maintainer-owned Gateway/session performance refactor be approved for merge? Approve after green CI: Approve the shared metadata-projection refactor once the queued checks are green on the exact head.

Why: The author association and protected maintainer label require explicit human judgment even though static review found no defect.

Before merge

  • Resolve merge risk (P1) - The exact PR-head preflight, security, and changed-path checks are queued, so integration readiness is not established yet.
  • Complete next step (P2) - Wait for exact-head CI to pass, then obtain maintainer approval before merge.
Agent review details

Security

None.

PR surface

Source -118, Tests +37. Total -81 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 11 134 252 -118
Tests 7 63 26 +37
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 18 197 278 -81

Review metrics

Metric Value Why it matters
Production versus test delta production -118, tests/test support +37 The change removes duplicated accessor/cache logic while adding focused boundary coverage for projection and retained-row behavior.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Retain the single shared SQLite projection/decoder boundary, preserve full reads for prompt-owning callers, and merge only after exact-head CI succeeds and a maintainer approves the performance refactor.
  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 shared SQLite projection/decoder boundary, preserve full reads for prompt-owning callers, and merge only after exact-head CI succeeds and a maintainer approves the performance refactor.

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

Not applicable: this PR is an internal performance and projection-consistency refactor, not a separate current-main bug report.

Is this the best way to solve the issue?

Yes. Centralizing metadata projection at the SQLite read/parse boundary removes consumer-side mutation while preserving full reads and existing validation semantics.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 1623683f478b.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded Gateway performance and metadata-consistency improvement without evidence of an urgent user-facing regression.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR includes a linked controlled real Gateway HTTP/RPC Testbox run for the changed session-read path; exact-head CI remains the outstanding merge gate.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (2 earlier review cycles)
  • reviewed 2026-09-02T15:40:46.059Z sha d70dd0e :: needs maintainer review before merge. :: none
  • reviewed 2026-09-02T15:51:10.709Z sha d70dd0e :: needs maintainer review before merge. :: none

@steipete steipete self-assigned this Sep 2, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 2, 2026
@steipete
steipete merged commit 1212f99 into main Sep 2, 2026
299 of 300 checks passed
@steipete
steipete deleted the codex/gateway-session-metadata-projections branch September 2, 2026 17:57
@steipete

steipete commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 3, 2026
* perf(sessions): project metadata before decoding saved prompts

Unify exact, child and list metadata projections at the read boundary. Preserve full session payloads and write CAS bytes, and reuse the canonical accessor types instead of duplicating their contracts.

* test(gateway): assert metadata projection for history aliases

* test(gateway): scope built CLI artifact inspection
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 P2 Normal backlog priority with limited blast radius. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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