Skip to content

fix(gateway): keep event lineage current across session lifetimes - #158581

Merged
steipete merged 4 commits into
mainfrom
perf/l09-prepared-lineage
Sep 26, 2026
Merged

steipete merged 4 commits into
mainfrom
perf/l09-prepared-lineage

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes stale parent-session attribution and permanently retained lineage lookups when many Control UI sessions are created, replaced, or removed.

User Impact

Agent and chat events follow current prepared controller and parent-session facts. Deleted sessions, closed incognito stores, and disposed projections no longer retain a cached parent. Optional enrichment can be absent while its owner prepares facts. No protocol, configuration, or SQLite schema changes are required.

Why This Change Was Made

The event handler used a permanent map for both successful and missing lineage lookups. Its initial lookup could also read SQLite on the Gateway thread. Events now consume the session projection owner and writer-published incognito metadata without materializing rows or rebuilding registry indexes during ingestion. Stored lineage remains canonical even when display aliases differ.

The lineage reader lives with existing projection relation reads; the sharing-entry constructor moved beside its type to keep both modules within their line caps. Production grows by 29 lines because preserving canonical selection and private-store lifetimes needs more than deleting the obsolete map.

Evidence

  • Baseline regression proof: eight scenarios failed for stale controller/null/positive results and SQL during the first prepared lookup (six statements in the basic case). Command wall time: 791.02 s on the shared campaign host.
  • Focused handler and incognito proof: node scripts/run-vitest.mjs src/gateway/server-chat.subagent-lineage.test.ts src/gateway/server-chat.agent-events.test.ts src/gateway/session-row-projection.incognito.test.ts --maxWorkers=1: 234 passed, 731.57 s wall before the behavior-preserving helper extraction. Lineage cases subsequently consolidated onto one admitted physical store and projection, retaining all lifecycle assertions.
  • Canonical stored-lineage and resource-policy proof: 16 passed, 753.51 s wall. Consolidated lineage-only proof: one lifecycle test passed, 28.620 s test time / 371.75 s command wall. Worker preparation and imports dominate wall time; one real-store fixture protects publication ordering, normalization, and incognito lifetime together.
  • Final helper-extraction proof: node scripts/run-vitest.mjs src/gateway/server-chat.subagent-lineage.test.ts src/gateway/session-resource-tool-policy.test.ts --maxWorkers=1: 16 passed; 1,201.11 s wall. The lineage test took 44.694 s on this run; the real writer/projection/ephemeral-store composition cannot be protected by a mocked lookup test. One shared fixture covers all transitions; no polling, sleeps, or Gateway boots were added.
  • Actual-handler microbenchmark, 10,000 distinct synthetic eligible missing session keys: 1,826.213 ms before → 83.635 ms after; retained heap delta 1,936,296 B → 185,136 B (90.4% lower). After dropping the handler: 565,952 B → 93,072 B. One paired isolated observation on Node 26.9.0, not a live Gateway latency or GC-pause measurement. No sockets or live state used.
  • Production LOC: +87 / -58, net +29. Tests and support: +182 / -125, net +57. Two obsolete cache-specific tests were replaced by real-owner publication and zero-SQL assertions.
  • Deslop complete. Line-cap ratchet passed after cohesive extraction; no suppression added.
  • node scripts/check-changed.mjs: 2,431.90 s wall; all production and 25 test type graphs, structural guards, and dead-export scans passed. Final lint found one shadowed local parameter. Renamed it without changing behavior; the exact changed-file lint command replay passed (exit 0), 141.73 s wall. Formatting and line-cap checks passed again. Earlier valid functional and type proof is reused for this naming-only correction.
  • Review regression: an actual-handler probe reproduced canonical main-alias lookup choosing stored lineage over its registry controller. Exact-row selection now lets the existing selector own alias fallback; the probe passes and the same case is included in the lifecycle test. Final node scripts/run-vitest.mjs src/gateway/server-chat.subagent-lineage.test.ts --maxWorkers=1: passed, 461.70 s wall / 33.410 s test time, including zero-SQL assertions for all lifecycle and alias transitions.
  • Independent Codex branch review through P2: final committed branch scoped-clean, no accepted/actionable findings. The initial alias finding was reproduced and fixed; the final lint correction only renames a local parameter. Candidate head: c516733b626827edd2c8bcef9c6087b61f4c5a03.

Landing verification

Merged current main 76e32e92441321b2e564263bc385cc7f4cc8ecd7 into the reviewed branch without rebasing. The sole textual conflict was the relocated sharing-entry constructor: the resolution preserves main's archivedAt and this change's spawnedBy together. Main's chat projection and presence work remains intact. Candidate: f4f0728cacf5fb7e71ab269dc764496d0475bc1e.

  • Local focused lineage, server-chat agent-event, and incognito projection tests: 227 passed; 541.01 s command wall (lineage lifecycle case: 13.524 s).
  • Independent Codex review of the merged candidate through P2: scoped-clean, no accepted/actionable findings.
  • Blacksmith Testbox tbx_01m3dv1hc5rz7xczgwkrx99h6n: node scripts/check-changed.mjs --base origin/main passed, 1,597.70 s command wall. Production and all 25 test type graphs, structural guards, dead-export scans, and lint passed. Source hashes were verified. Run. The box is confirmed stopped/completed; its backing workflow may show cancellation from normal delegated lease cleanup. Runner portal sync warned after the successful command and confirmed shutdown.
  • Two local invocation preflights were corrected before allocation: the source wrapper requires an origin/<branch> base, and Blacksmith does not support the generic --stop-after flag. Exactly one Testbox was allocated.
  • Exact-head hosted CI run 36215569396: completed successfully for f4f0728cacf5fb7e71ab269dc764496d0475bc1e; repository watcher returned GREEN. No failed jobs or test reruns. The watcher retried one read when the rollup changed during pagination.

@clawsweeper

clawsweeper Bot commented Sep 26, 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 gateway Gateway runtime size: M labels Sep 26, 2026
@steipete
steipete marked this pull request as ready for review September 26, 2026 02:24
Preserve the relocated sharing-entry constructor and main archive metadata while retaining the reviewed lineage owner changes.
@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 26, 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 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 26, 2026, 12:13 AM ET / 04:13 UTC.

ClawSweeper review

What this changes

The branch replaces the Gateway’s permanent parent-session cache with current session-projection and private-store metadata when adding lineage to chat and agent events.

Merge readiness

✅ Ready for maintainer review

Keep this PR open. Current main still retains the first lineage lookup for the lifetime of the event handler, so the central defect remains. The inspected patch has no definite introduced correctness defect.

Priority: P2
Reviewed head: f4f0728cacf5fb7e71ab269dc764496d0475bc1e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The owner-level patch and lifecycle regression are well supported by source review and exact-head checks, with no concrete blocking defect found.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The supplied Repository State identifies the author as MEMBER, so the external-contributor proof gate does not apply. The PR reports after-fix handler and real-store projection tests with a mocked broadcast plus a synthetic benchmark; no live Gateway client trace is claimed. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied Repository State identifies the author as MEMBER, so the external-contributor proof gate does not apply. The PR reports after-fix handler and real-store projection tests with a mocked broadcast plus a synthetic benchmark; no live Gateway client trace is claimed. No stored-data contract changes.
Evidence reviewed 7 items Current-main behavior: Current main still has a handler-lifetime spawnedBy cache; the new prepared lineage reader is absent there.
Introduced handler change: The pinned introduced diff removes the permanent map and asks the active projection for lineage on each eligible event.
Lineage owner: The projection selects an exact stored row or committed incognito metadata, then prefers prepared controller facts and falls back to stored spawnedBy.
Findings None None.
Security None None.

How this fits together

The Gateway receives agent events and turns them into chat and agent event payloads for connected clients. Its session projection supplies parent-session facts from committed rows and open incognito stores.

flowchart LR
A[Agent events] --> B[Gateway event handler]
C[Session key] --> B
B --> D[Session projection]
D --> E[Committed session metadata]
D --> F[Open incognito store]
E --> G[Current parent session]
F --> G
G --> H[Chat and agent events]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +29, Tests +57. Total +86 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 7 88 59 +29
Tests 3 182 125 +57
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 270 184 +86

Review metrics

Metric Value Why it matters
Production and test growth production net +29; tests and support net +57 The PR explains the production growth as the cost of preserving canonical selection and private-store lifetimes.

Technical review

Best possible solution:

Keep lineage with the session projection’s committed facts and lifecycle invalidation, then land the focused fix through normal review.

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

Yes, from source: current main permanently caches an eligible session’s first lineage result, so a later publication cannot change that handler’s answer. The PR reports a failing baseline regression; this read-only review did not run it.

Is this the best way to solve the issue?

Yes. Reading committed facts through the existing session projection removes the competing cache and follows row and store lifetimes without adding a persistence format.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: Stale parent-session attribution is an existing Gateway event defect with a bounded affected path.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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: The supplied Repository State identifies the author as MEMBER, so the external-contributor proof gate does not apply. The PR reports after-fix handler and real-store projection tests with a mocked broadcast plus a synthetic benchmark; no live Gateway client trace is claimed. No stored-data contract changes.

Label justifications:

  • P2: Stale parent-session attribution is an existing Gateway event defect with a bounded affected path.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 Repository State identifies the author as MEMBER, so the external-contributor proof gate does not apply. The PR reports after-fix handler and real-store projection tests with a mocked broadcast plus a synthetic benchmark; no live Gateway client trace is claimed. No stored-data contract changes.

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)
  • Vincent Koc: 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.

@steipete
steipete merged commit 4aa852f into main Sep 26, 2026
219 checks passed
@steipete
steipete deleted the perf/l09-prepared-lineage branch September 26, 2026 04:18
@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 P2 Normal backlog priority with limited blast radius. 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