Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(server): streamed projection updates no longer rewrite unchanged index entries #35026

ClosedVantrongs(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/35026/headopened View on GitHub

Problem

The projection upserts in ProjectionStore.apply assign every column in their ON CONFLICT DO UPDATE SET. SQLite deletes and reinserts the entry of every index on a column the SET list names, whatever its value: sqlite3Update (src/update.c) marks each assigned column in aXRef, and indexColumnIsBeingUpdated / indexWhereClauseMightChange pick the indexes to maintain at compile time without comparing values. So a streamed turn-item.updated that changes only payload_json and updated_at rewrites all nine turn_items index entries. The same holds for subagent, provider-thread and provider-turn updates. A standalone sqlite3 check on 20k rows with 6 indexes: the full upsert with unchanged indexed values writes 6 WAL frames, a col = CASE … END assignment also 6, and an upsert that leaves those columns out writes 1.

This is part of the per-commit page cost in #24003. The same idea was closed in #19619 for lack of a measurement through a live provider stream; this PR includes one.

Change

The upserts of turn items, subagents, provider threads and provider turns now go through one helper, upsertProjectionRow in the new projectionUpsert.ts, built from a spec per table: its columns, its key, the columns an index reads, and any conflict expression that is not excluded.<column>. From one spec it builds two statements:

  • A guarded upsert. Its conflict branch assigns only the columns no index reads, under WHERE <table>.<indexed column> IS <its new value> AND …, with RETURNING 1. A create and an update that keeps every indexed value run only this statement.
  • The previous full upsert, unchanged. It runs only when the guarded one returns no row, that is, when an indexed column would change. In that case the guarded statement wrote nothing.

Stored rows are unchanged on both paths. updated_at and payload_json are assigned even where an index reads them, because nearly every update changes them.

The other twelve upserts in apply are untouched. Their updates mostly change an indexed column (node and run status, the thread's updated_at), or they are rare. On a real 5,417-event window, the four converted tables give 98.8% of the saving that converting all sixteen gave.

Scope

A performance bug: every streamed update rewrites index entries whose values did not change. It is one part of #24003. Nothing T3 stores, reads or shows changes. The change is limited to these four upserts and the helper they share.

Verification

Write volume through the real write path. A replay harness (apps/server/scripts/bench-event-writes.ts on a branch of our fork, not part of this PR) feeds recorded events through the server's own EventSink, with the server's PRAGMAs and migrations, on a copy of a real 5.7 GB database. It counts the WAL frames each commit appends and attributes them to b-trees with dbstat. Counts repeat exactly from run to run. Its replay of a live Claude turn, recorded on a scratch server, matches that turn's live WAL within 2% (22.47 frames per event live, 22.86 replayed). Results, smallest gain first:

WindowFrames per event, before → afterKiB per event
One live Claude turn (65 events)22.86 → 22.4392.0 → 90.2
418 recorded events31.03 → 29.11124.8 → 117.1
5,417 recorded events29.21 → 27.29 (−6.6%)117.5 → 109.8

On the 5,417-event window, checkpoint pages per event went from 10.92 to 10.13, and frames per commit changed by event type as follows: turn-item.updated 36.5 → 34.0, subagent.updated 24.6 → 19.7, provider-thread.updated 23.2 → 19.2, provider-turn.updated 20.2 → 18.3. node.updated and message.updated are unchanged. Write time inside EventSink.write stayed at 0.31 ms per event, within noise (host load average about 9).

Tests in ProjectionStore.test.ts:

  • "projection upserts guard every column an index reads": reads sqlite_master and requires each spec's guarded columns to be exactly the columns its table's indexes read (keys, expressions, partial-index filters). It also fails if an UPDATE OF trigger exists on these tables.
  • "a guarded projection upsert leaves the rows the full upsert leaves": 300 random edits per table, including NULL transitions, type mixes and constraint errors, written through the helper and through the full upsert alone into two fresh databases. Rows, rowids and errors must match.
  • "streamed projection updates leave the same row as a fresh write": for each of the four event types, a create, an index-stable update and an index-moving update.
  • "streamed projection updates write only the pages whose contents change": WAL pages per index-stable update through apply on a file database, counting the thread's activity-time row. Against main's ProjectionStore.ts it fails with turn item 12, subagent 8, provider thread 7, provider turn 5. With the change all four are 3.

vp test run on ProjectionStore.test.ts and 14 related files (ShellStream, ProjectionRecovery, ProjectionSettlement, ProjectionMaintenance, ProviderEventIngestor, ProviderCommitBatch, FoundationPersistence and others): 296 passed. vp run check:changed: format, lint, knip, graphql, typecheck and tests pass.

Model and harness: Claude Opus 5.5, Claude Code in T3 Code

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. Approvability

      Verdict: Approved at cbf5743

      Macroscope's review found this PR approvable — The change reduces redundant SQLite index writes for four streamed projection updates while retaining full updates when indexed values change. Its scope is limited to persistence efficiency, with reported equivalence tests and replay measurements supporting the change.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. Explain Change →

      No actionable comments were generated in the recent review.

      Walkthrough

      Four orchestration projection update handlers now use shared guarded-upsert logic. The helper generates table-specific SQL, applies conflict handling, and falls back to a full upsert when needed. New tests check stored-row equivalence, schema alignment, fallback behavior, and WAL-page counts.

      Changes: Projection upserts

      Layer / File(s)Summary
      Guarded upsert metadata and execution
      apps/server/src/orchestration-v2/projectionUpsert.ts
      The new helper defines guarded and full upsert statements for four projection tables. It maps undefined values to NULL and uses the full statement when the guarded statement returns no rows. Subagent conflict handling preserves completion-delivery state and payload properties when the incoming values omit them.
      Projection update integration
      apps/server/src/orchestration-v2/ProjectionStore.ts
      Subagent, provider-thread, provider-turn, and turn-item update handlers now call the shared upsert helper.
      Upsert validation
      apps/server/src/orchestration-v2/ProjectionStore.test.ts
      New tests compare guarded and full upserts, verify fallback behavior and fresh-write equivalence, check guarded columns against schema indexes, and assert WAL-page counts for stable updates.

      Estimated code review effort: 3 (Moderate) | ~25 minutes

      Change: Refactor

      Possibly related issues

      • pingdotgg/t3code#24003: The changes reduce index-page rewrites for projection upserts, addressing part of the issue’s write-amplification concern.

      Suggested reviewers: juliusmarminge, t3dotgg, yash-singh1

      Merge Risk: Minimal · up to cbf57

      The change reduces SQLite index write amplification for four streamed projection tables while keeping stored rows equivalent, and its tests cover fallback behavior. No merge-blocking risk remains.

      Pre-merge checks: Passed 4

      Check nameStatusExplanation
      Title checkPassedThe title is specific and accurate. It names the scope (streamed projection updates), the change (no longer rewriting unchanged index entries), and the type (perf). It matches the main change: guarded…
      Description checkPassedThe description follows the repository template. It has Problem, Change, Scope, and Verification sections, each with substantive content. The Problem section explains the SQLite index-rewrite cost wit…
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Full details: Title check

      Explanation

      The title is specific and accurate. It names the scope (streamed projection updates), the change (no longer rewriting unchanged index entries), and the type (perf). It matches the main change: guarded upserts that skip rewriting index entries for unchanged indexed values in the four projection tables.

      Full details: Description check

      Explanation

      The description follows the repository template. It has Problem, Change, Scope, and Verification sections, each with substantive content. The Problem section explains the SQLite index-rewrite cost with a concrete mechanism. The Change section describes the guarded and full upsert paths. The Scope section names it as a bug fix and links the related issue #24003. The Verification section lists specific tests, measured WAL frame counts, and the commands run. The agent model and harness line is included. Minor gaps: the Scope section does not link a specific bug issue for this fix, and it cites a closed PR #19619 instead of an issue. The template asks for a linked issue showing the bug, so this is a small omission rather than a missing section.

      Finishing Touches

      Generate unit tests (beta)

      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
      Recent review info

      Run configuration

      Commits

      Reviewing files that changed from the base of the PR and between ee90bdc9405d8d4b8ff78ce2133ccb04844298ab and cbf57430576ca96f2826e22933c389cb8c152961.

      Files selected for processing: 3

      • apps/server/src/orchestration-v2/ProjectionStore.test.ts
      • apps/server/src/orchestration-v2/ProjectionStore.ts
      • apps/server/src/orchestration-v2/projectionUpsert.ts

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

    4. tanstack-source added labelsbug

    5. juliusmarminge added labelstakeover:in-progress

    6. juliusmarminge added labelstakeover:blocked

    7. juliusmarminge removed labelstakeover:in-progress

    8. maria-rckscommented

      Note

      Written by gpt-6.1-sol on behalf of Maria

      Verified in a real dev environment

      verified unchanged head cbf57430576ca96f2826e22933c389cb8c152961 against github/main at 843893e58c on this linux vm. used isolated homes, one dev server at a time, repo playwright with google chrome, projects created through the app, and real codex gpt-6.1-sol turns. no mocks or replayed events.

      main reproduced redundant writes during a real turn. parsing the live sqlite wal and comparing successive index-page bytes showed each provider-turn thread/ordinal index written 5 times, including 4 byte-identical rewrites. the captured sol turn on the pr wrote each once for insertion, with 0 identical rewrites. this is live write-path evidence, not a latency or throughput claim.

      streamed command output, file creation/readback, follow-up turns, completed tool/provider states, and history after reload worked. a real sol child returned the exact file contents; its completed subagent projection and result persisted. a neighboring 20-line command stream exited successfully and retained all output. sqlite integrity check returned ok.

      all 59 existing ProjectionStore.test.ts tests passed through blacksmith-check on the required node 26.13.1. the initial node 24 run hit an unavailable sqlite statement api; the node 26 run passed. existing forge status has 45 successful checks and one failing Agent context budget check. no source changes or pushes were needed.

      command transcript and measurement method

      real codex gpt-6.1-sol turn reaches completion

      persisted sol child result and successful neighboring stream after reload

      Not verified

      native electron shell, ios/android, macos/windows, other providers, relay/tunnel modes, and large-database throughput. app-managed completion-delivery merge transitions were covered by the existing tests rather than forced through the ui; the live child used provider-native completion.

    9. Closing in favour of #36861, which carries these commits on a branch the pipeline can push to. Thanks for taking it over.

      Model and harness: Claude Opus 5.5, Claude Code in T3 Code

Sign in to join this conversation.