Skip to content

Stop rebuilding sender history and resending orchestration rows on unchanged graph replies - #43458

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/fix1-orch-projection
Nov 17, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/fix1-orch-projection

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Every time the window tells main "here is my terminal layout" (title ticks, tab create/close, workspace switches), main answered with two expensive things even when nothing had changed:

  • It threw away its cached "who sent this agent message" history right after answering, so the next answer rebuilt it from the database. With a few hundred agent panes that was about 16 ms of main-process work per answer.
  • It rebuilt and resent the whole orchestration list (about 290 rows, ~180 KB) on every answer.

Now main keeps that history while the window is using it, and only resends the orchestration list when it actually changed.

Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​58 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​53
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​101 $\color{#cf222e}{\Huge{\mathbf{−}}}$​22 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​79

What Changed

  • Sender history stays warm while the window holds the graph. Agent message cards find their sender's agent and status in the same store as the sidebar #36660 meant to release cached sender history "when the last desktop consumer leaves", but hasAgentSenderListeners() only counted paired session-tab listeners, not the local window that reads the sender publication on every graph reply. So agentSenderGraphReply released it after every reply and the next reply rebuilt it cold: every pane re-read and statements prepared again. The authoritative renderer window now counts as a consumer. History is released when it gives up the graph (markGraphUnavailable, or a headless restore), as before for paired clients.
  • The orchestration projection is resent only when it changed. The renderer sends agentOrchestrationBase, the revision it last applied. Main keeps the last projection and bumps the revision only when the content differs (AgentOrchestrationGraphRevision, the same base/revision shape as the sender publication's agentSenderBase). While the base is current, the reply carries only agentOrchestrationRevision.
    • The renderer keeps its map on an unchanged reply. It still re-applies the held map, so it keeps merging into status rows that arrived since, exactly as today. An absent map with a different revision still clears, as before.
    • A base is sent only while the store's map is the same object the renderer applied. Local edits (pane removal, tab move) void it, so the next reply carries the full map and snaps back to main's view, as today.
  • Status evidence for the projection no longer composes each Dispatch twice. Minting evidence resolved each pane's binding by projecting its Dispatch again, but the projection reads only the evidence's activity and clock.

Why

The Nov 15 live-lag report (FIX 1) measured unchanged graph submissions driving full main-side work and 290-row orchestration replies. #42934 removed the renderer half (phone snapshot inputs). This PR removes the main half that remained on current main.

Measured before → after (main-process syncWindowGraph on the M4Air: real OrcaRuntimeService, 300 terminals, 290 Dispatches, one status row per pane, 200 calls after warm-up, arms alternated, two runs each):

Submission main p50 / p95 (ms) this PR p50 / p95 (ms)
Identical graph, quiet M4Air 19.4–37.5 / 33.5–122 4.9–6.8 / 7.1–11.5
Title tick, quiet M4Air 22.0–34.2 / 36.9–59.3 5.5–7.6 / 9.5–13.9
Identical graph, final head, busy M4Air 47.3–57.1 / 83–293 6.1–7.2 / 10.5–13.6
Title tick, final head, busy M4Air 41.1–55.5 / 76–560 6.8 / 12.7–14.7

"Final head" is this PR's code exactly. The quiet run was on an earlier commit, before the renderer-failure release and the null guard were added.

  • Sender history rebuilds over 20 replies: 20 cold → 1 (the first). Pane reads: 18,000 → 900.
  • Unchanged reply size with the base: 183 KB → 55 KB. What's left in the benchmark is the sender publication, which a real window also skips through agentSenderBase.
  • The orchestration build itself is about 3 ms per reply at 290 rows (unchanged within noise). The rest of the remaining ~5 ms is graph reconciliation.

Considered and not done, both from #42934's follow-up list:

  • Skipping the projection build when inputs are unchanged. It reads DB facts, terminal identity, status evidence, session records and the clock (30-minute recency, 5 s and 30 min status freshness, 60 s attempt freshness). Status freshness changes raise no row event, and the terminal-identity bus fires on every sync, so a cache would need new signals and deadlines, where any miss shows a stale sidebar row. For about 3 ms per reply that risk isn't worth it.
  • Skipping main's reconciliation of unchanged terminal graphs. With the sender rebuild gone, reconciliation is about 2 ms at 300 leaves. It also re-derives main-side state between identical submissions: connected/writable flags, first-dispatch handle issuance, pending mailbox delivery, createTerminal waiters and reload settling. Skipping it would need each of those re-proven, for little gain.

Not overlapping the status-sync-flood work: nothing here touches session-tab snapshotVersion or status replica publication.

Linked Issue

Tracked in #42934 (its follow-up items 1 and 2: the orchestration reply and unchanged graph replies).

Visual Proof

N/A. No UI change: the sidebar, sender cards and phones show the same data. The window just receives it only when it changes.

Testing

  • Benchmark above (scratch vitest bench on the real OrcaRuntimeService, kept out of the PR; run on the M4Air through qa-gate).

  • New assertions:

    • main omits the projection for a current base and resends it after a change (lineage-and-scan-cache-part-05.spec.ts);
    • the window keeps its map on an unchanged reply, sends its base, and drops the base after a local edit (sync-runtime-graph-payload-partition.test.ts).
      Both fail without this change.
  • pnpm check:changed on Omarchy through remote-check: 38/38 passed on this head.

  • Automated tests added/updated, or explained why not below

  • Every added test fails without this change and avoids the test anti-patterns

Risk

  • Riskiest part: the renderer keeping its orchestration map on an "unchanged" reply. If main's equality missed a real change, a sidebar orchestration row could stay stale until the next change. Main compares the whole projection with isDeepStrictEqual, so any field difference resends it.
  • Sender history is now kept while a window is open. That's the same retention paired desktop clients already get: bounded by live panes, released when the window leaves the graph.
  • Wire compatibility: the window and main always ship in the same build (preload IPC). Paired web clients and the headless runtime send no base and keep today's full replies.
  • Back out: a plain revert. Nothing is saved.

Level: Medium

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Cross-platform: main/renderer TypeScript only; no platform, path or shell code.
  • Remote: paired hosts' session-tab listeners keep their existing release rule.
  • Mobile: phones don't use graph replies.
  • Folder workspaces: unaffected.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out

…tion on unchanged graph replies

The window counts as a sender consumer while it holds the graph, so each graph
reply no longer drops and cold-rebuilds sender worker history. The orchestration
projection rides the reply only when it changed since the window's applied
revision, and status evidence for the projection no longer composes each
Dispatch a second time for a binding nothing reads.
@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

The runtime now tracks agent orchestration projection revisions and can omit a pane-keyed projection when the renderer already has the current revision. The renderer sends its applied revision and applies or retains orchestration context maps based on the reply. Tests cover revision-only replies and map restoration after a local edit. Agent-sender listener detection and history-release calls also change for graph availability and headless-graph transitions.

Merge Risk: Low · up to 76ea6

The change reduces repeated work on unchanged graph replies. A narrow risk remains that sidebar orchestration rows stay stale if a runtime is replaced while the renderer keeps its revision state. No such path was found, so this is a low merge risk. Making the revision token unique per runtime would remove the concern.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: main stops rebuilding sender history and resending orchestration rows when graph replies are unchanged. The raw summary and objectives confirm both parts. It is specif…
Description check Passed The description follows the repository template. It has ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Risk, AI Disclosure, Review, Agent skill boundary, Notes, and Checklist sections. …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: main stops rebuilding sender history and resending orchestration rows when graph replies are unchanged. The raw summary and objectives confirm both parts. It is specific and concise, although at 90 characters it is slightly long.

Full details: Description check

Explanation

The description follows the repository template. It has ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Risk, AI Disclosure, Review, Agent skill boundary, Notes, and Checklist sections. It gives a before/after explanation, a mechanism, measured benchmarks, tests, and a risk statement with a rollback plan. The Linked Issue section uses 'Tracked in #42934' and leaves the 'Fixes #' line blank. The template requires an actual linked issue for outside contributors, and the Risk 'Level' is set. The AI Disclosure section is empty, which the template only permits for StablyAI team members. The author is not identified in the inputs, so this gap is noted but does not make the description incomplete.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

…h-projection

# Conflicts:
#	src/main/runtime/session-graph/session-window-graph.ts
#	src/main/runtime/session-tabs/publication/mobile-session-tab-subscriptions.ts

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Major · Revision numbers can repeat across runtime instances, so a stale… · session-window-graph.ts:320

src/main/runtime/session-graph/session-window-graph.ts:320
Major · Data Integrity & Integration · Heavy lift

Revision numbers can repeat across runtime instances, so a stale map can persist.

Each runtime instance starts its orchestration revision at 0 and assigns revision 1 to its first reply. If a replacement runtime reports revision 1 for a different projection while the renderer still holds base 1 from the previous runtime, the renderer treats the reply as unchanged. It keeps the old map, and the stale rows remain until the projection changes again. The renderer clears its base only when the store map identity changes or when an unchanged reply carries a different map, so the stale state can survive the replacement.

Make the revision token unique to the runtime instance. Alternatively, clear the renderer's applied base whenever the runtime changes. Either change needs a way to signal replacement to the renderer, which the inspected code does not provide, so this comment has no patch.

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 43a13d9d-4a0f-4f55-a339-937e3fe1389b
Commits

Reviewing files that changed from the base of the PR and between 28b0f8f and 76ea6bf.

Files selected for processing: 2

  • src/main/runtime/session-graph/session-window-graph.ts
  • src/main/runtime/session-tabs/publication/mobile-session-tab-subscriptions.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status

Problem. On every window graph publication (title ticks, tab create/close, workspace switch) main did expensive work even when nothing had changed:

  • It dropped the sender-identity history right after answering, so every answer rebuilt it from the database. With 300 agent panes that was about 16 ms per answer.
  • It resent the whole orchestration list (about 290 rows, ~183 KB).

User-facing change. None visible: the sidebar, agent message sender cards and phones show the same data. Main does about 4–8× less work per unchanged graph reply.

Fixed during review

  • Renderer crash or reload timeout with the window still open. History was kept with no consumer. Now it's released as soon as the graph becomes unavailable (Codex pass 1, perf pass 1).
  • Null guard in the renderer's applied-revision read. With no applied revision and a store without the map, it threw. The store always has the map, so this hit test fixtures only, never users. Found by check:changed.

Considered and deferred

  • Skip the projection build on unchanged inputs (perf reviewer). A council of three fresh agents (Claude Opus and two Codex) ruled unanimously to keep rebuild, compare and omit. A cache key would need signals that don't exist today: status-freshness renewals raise no event, the terminal-identity bus fires on every sync, and the time deadlines live inside SQL inputs. A miss shows a stale sidebar row, and the gain is about 3 ms per reply.
  • Dirty-key writes on worker-terminal resource changes while history is retained (perf reviewer). They grow with a terminal's prior owners. This is the steady state paired desktop clients already run in. It's per resource change, in in-memory temp tables, and replaces a cold rebuild per graph reply.
  • Renderer setter still scans on unchanged replies. Pre-existing, and kept on purpose: re-applying the held map merges orchestration into status rows that arrived since.
  • Skipping main reconciliation of unchanged graphs. About 2 ms at 300 leaves after this PR, and it re-derives main-side state (connected/writable, first-dispatch handles, mailbox delivery, createTerminal waiters). Not worth the risk.

Verified

  • Benchmark on the final head (M4Air, 300 terminals and 290 Dispatches, real runtime): handler p50 41–57 → 6.1–7.2 ms; cold sender rebuilds 20 → 1 per 20 replies; unchanged reply 183 → 55 KB.
  • check:changed 38/38 on Omarchy on this head; CI green. One unrelated shard failed once in acp-structured-restore-retry.test.ts (an ACP restore timing assertion) and passed on rerun.
  • The head commit 76ea6bff861 merges main. Its conflicts were import paths only, from main moving session-tabs/ files into publication/ and inventory/.
  • Review: three passes, each with a fresh Claude Opus (medium) and Codex gpt-6.1-sol (high), plus a separate perf pass. The last pass is clean on 28b0f8fe09a (the guard commit); only the main merge comes after it.
  • QA: tests and benchmark (a runtime/perf change with no UI or agent-integration flow).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (fresh perf reviewer, Claude Opus medium, full perf-scan)

DONE: READY TO MERGE #43458 There are no perf blockers on this head. The PR removes a cold sender-history rebuild and a full orchestration resend from every unchanged graph reply, and adds only an equality check that costs less than the cloning it removes.

Scope. I reviewed 354c91cd81b..76ea6bff861 against the PR's own commits, read the full perf-scan skill, and read the earlier perf pass, the council results and the PR body. I didn't edit, build or run any test suite. The only thing I ran was a standalone Node microbenchmark in /tmp, on 290 synthetic contexts shaped like AgentStatusOrchestrationContext:

Map size isDeepStrictEqual (equal maps) structuredClone JSON size
290 0.16 ms 0.49 ms 120 KB
2,900 1.75 ms 4.3 ms 1.2 MB

The before/after syncWindowGraph timings (about 20–50 ms down to 5–7 ms p50) are the author's numbers, not mine.

Findings

None at P0 or P1. The orchestration map is still sent whole whenever it changed, and the renderer still scans it on every reply, but both are older than this PR.

Earlier perf findings on this head

  1. Comparing the whole projection on every reply: not a blocker.
    • agent-orchestration-graph-revision.ts:20-25 adds one deep comparison per reply. The build it follows was already unconditional at the old session-window-graph.ts:308.
    • On an unchanged reply the check (0.16 ms, 1.75 ms at 10×) replaces cloning the map on main (0.49 ms, 4.3 ms at 10×), plus the IPC transfer and the renderer having to rebuild every context.
    • On a changed reply the comparison stops at the first difference. At worst it adds 0.16 ms next to a build of about 3 ms (author-measured), so it is a small constant factor rather than a new growing cost.
    • The council chose to keep rebuilding the projection on each reply, and I agree.
    • The headless caller (headless-runtime-graph.ts:8) sends no base, so it gets the full map as before plus the 0.16 ms check.
  2. History-sized dirty-key writes to SQLite: not a blocker.
    • This PR doesn't touch the trigger code. The prior-owner list grows with each transfer (worker-terminal-resource-store.ts:193) and the json_each enumeration in the triggers (runtime-agent-sender-history-triggers.ts:47-56) both predate it.
    • The tracked-key lookup per candidate key already ran even when nothing was tracked. The only new work is at most H+2 INSERT OR IGNORE rows per resource change.
    • Those rows are deduplicated and capped by the tracked population (live panes plus reachable lineage), and they live in in-memory TEMP tables.
    • The work this replaces is a full cold rebuild on every graph reply (author-measured 18,000 → 900 pane reads over 20 replies). That rebuild costs more than the dirty inserts whenever replies are at least as frequent as resource changes. If the window is quiet and changes keep coming, the dirty set stops growing once it covers the tracked keys.
    • Desktop clients paired with the window already had this same retention.
  3. A failed renderer stays counted as a consumer: fixed.
    • In session-graph-authority.ts:68,81, the renderer-failure path now sets graphStatus='unavailable' and then calls releaseAgentSenderHistoryIfUnobserved().
    • hasAgentSenderListeners() (mobile-session-tab-subscriptions.ts:104-110) then returns false, unless a paired desktop listener survives.
    • Restoring headless authority (:104) and markGraphUnavailable (session-graph-reload-lifecycle.ts:230) release it too.
  4. The renderer scans the whole map and all status rows: older than this PR, not a blocker.
    • orchestration-graph-revision.ts:26 passes the map the store already holds, so the setter (agent-status-orchestration-actions.ts:33-60) compares each context with itself. Before this PR it compared against a freshly rebuilt IPC copy, so the per-reply cost is now the same or lower.
    • The status-row loop is unchanged. The PR adds no growing cost here.

Work the PR adds, changes or keeps

Work Trigger Population Bound
Main revision state every syncWindowGraph one counter and one published map, O(R) replaced only when content changes; no log
Deep comparison every reply R contexts, about 13 fields each 0.16 ms at 290, 1.75 ms at 2,900
Omitting the map reply whose base matches – saves about 120–180 KB clone and IPC per unchanged reply
Renderer applied-revision record every send and reply one revision and one map reference O(1) identity check; a local edit to the map voids it
Sender history kept warm while a non-headless window holds a usable graph live panes plus reachable lineage pruned on refresh; released when the graph becomes unavailable, on headless restore or on close
Dispatch-binding callback removed (runtime-agent-orchestration-projection.ts:57,113,197) each piece of evidence in a projection – removes one getForHandle composition per row (less work)

Revision publication

  • Subscribers: the window that owns the graph, through applyOrchestrationReply, which feeds the store consumers the earlier pass listed. The headless caller and the workspace-facts override send no base and get the full map as before.
  • Equality and invalidation: isDeepStrictEqual over the whole map, which ignores key order. The revision goes up only when content differs, with the first reply always counted as a change. The renderer sends a base only while the store's map is the exact object main last sent. Revision and content are global because the projection doesn't depend on the window.
  • Rate when idle: zero. There is no graph polling.
  • Rate under load: at most 62.5 requests/s, coalesced at 16 ms with one in flight. Replies triggered by titles, layout or drafts carry no map unless the projection changed. Changes can come from clock-based attention boundaries (5 s, 60 s, 30 min) or from status evidence that differs when a graph reply happens to fire.
  • Replies with no change: with a stable projection, every reply after the seed omits the map, for example 19 of 20. This is derived from the code, not observed. The worst case is a map that changes on every reply: that matches the old behaviour plus the 0.16 ms check.

Checks

  • Regression classes:
    • Update published when nothing changed: checked and ruled out. The revision is compared against content, not against a version field.
    • Whole snapshot per change: older than this PR and now reduced.
    • Work before the skip gate: the build still happens before the check, which the council accepted. The check is cheaper than the cloning it removes.
    • Per-entity state outliving its owner: one map per runtime and one per renderer.
    • Synchronous SQLite on main: covered under finding 2.
    • Eager imports: only node:util.
  • Six scan questions:
    • Unused work before the skip gate: reviewed, numbers above.
    • Ownership multiplying work: one owner per runtime.
    • Which thread pays: Electron main and the renderer, both priced above.
    • Growth: the new state is O(R); history has no fixed cap, but this PR didn't add it.
    • Host differences: no new subprocess, filesystem or SSH calls.
    • Cleanup of abandoned work: release paths verified.
  • Not measured: Windows, Linux and live-fleet CPU, and heap.

Not perf, for you to decide: since() returns the same map object it keeps as published. IPC clones it today, but if an in-process caller ever changed the reply map, main would miss a real change. Nothing does this on this head.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status

Problem. On every window graph publication (title ticks, tab create/close, workspace switch) main did expensive work even when nothing had changed:

  • It dropped the sender-identity history right after answering, so every answer rebuilt it from the database. With 300 agent panes that was about 16 ms per answer.
  • It resent the whole orchestration list (about 290 rows, ~183 KB).

User-facing change. None visible: the sidebar, agent message sender cards and phones show the same data. Main does about 4–8× less work per unchanged graph reply.

Fixed during review

  • Renderer crash or reload timeout with the window still open. History was kept with no consumer. Now it's released as soon as the graph becomes unavailable (Codex pass 1, perf pass 1).
  • Null guard in the renderer's applied-revision read. With no applied revision and a store without the map, it threw. The store always has the map, so this hit test fixtures only, never users. Found by check:changed.

Considered and deferred

  • Skip the projection build on unchanged inputs (perf reviewer). A council of three fresh agents (Claude Opus and two Codex) ruled unanimously to keep rebuild, compare and omit. A cache key would need signals that don't exist today: status-freshness renewals raise no event, the terminal-identity bus fires on every sync, and the time deadlines live inside SQL inputs. A miss shows a stale sidebar row, and the gain is about 3 ms per reply.
  • Dirty-key writes on worker-terminal resource changes while history is retained (perf reviewer). They grow with a terminal's prior owners. This is the steady state paired desktop clients already run in. It's per resource change, in in-memory temp tables, and replaces a cold rebuild per graph reply.
  • Renderer setter still scans on unchanged replies. Pre-existing, and kept on purpose: re-applying the held map merges orchestration into status rows that arrived since.
  • Skipping main reconciliation of unchanged graphs. About 2 ms at 300 leaves after this PR, and it re-derives main-side state (connected/writable, first-dispatch handles, mailbox delivery, createTerminal waiters). Not worth the risk.

Verified
Benchmark: head=76ea6bff861 gate=PASS. Corpus: real OrcaRuntimeService with 300 terminals, 290 Dispatches and one status row per pane, 200 syncWindowGraph calls after warm-up, on the M4Air through qa-gate. Main (merge base 354c91cd81b) and this head alternated, two runs each. Handler p50 24.0–24.9 → 5.7–6.4 ms; sender history cold rebuilds 20 → 1 per 20 replies (pane reads 18,000 → 900); unchanged reply 183 → 55 KB. The bench file is kept outside the repo: ~/orca-qa/fix1-orch-projection/bench/zz-orchestration-reply-bench.test.ts.

  • Fresh full perf-scan on this head: clean (comment above).
  • check:changed 38/38 on Omarchy on this head; CI green. One unrelated shard failed once in acp-structured-restore-retry.test.ts (an ACP restore timing assertion) and passed on rerun.
  • The head commit 76ea6bff861 merges main. Its conflicts were import paths only, from main moving session-tabs/ files into publication/ and inventory/.
  • Review: three passes, each with a fresh Claude Opus (medium) and Codex gpt-6.1-sol (high), plus a separate perf pass. The last pass is clean on 28b0f8fe09a (the guard commit); only the main merge comes after it.
  • QA: tests and benchmark (a runtime/perf change with no UI or agent-integration flow).

@brennanb2025
brennanb2025 merged commit c26929e into main Nov 17, 2026
109 of 111 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant