GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): sync history full-table scan -> aggregate-scoped index r… · neumark/opencode@67a1b9f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • FORK.md
  • packages/opencode
    • src/server/routes/instance/httpapi/handlers
      • sync.ts
    • test/server
      • httpapi-sync.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎FORK.md‎

Copy file name to clipboardExpand all lines: FORK.md
+8Lines changed: 8 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,14 @@ Commit hashes above are the ones the tags pin (pre-rebase history); the equivale
8282

8383
**Implementation** (`c73da62`): `packages/opencode/src/util/cgroup.ts` (base resolution via `FC_AGENT_CG`, `oomKilled(pid)` leaf scan, `fenceLsp(pid, cmd)`); `packages/opencode/src/tool/shell.ts` (`Effect.catch` on `exitCode` in the exit race, `signalOf`, `meta` annotations); `packages/opencode/src/lsp/launch.ts` (fence after the stream check). Tests: `packages/opencode/test/util/cgroup.test.ts`.
8484

85+
### 6. Sync history: aggregate-scoped reads (event-table read spiral)
86+
87+
**What it does**: `POST /sync/history` (the multi-tab sync protocol's catch-up — "events with seq > value are returned for listed aggregates, unlisted aggregates get their full history") now reads each aggregate through the `event_aggregate_seq_idx` index instead of full-scanning the whole `event` table.
88+
89+
**Why it was needed** (measured live on an fc-opencode guest, INCIDENT_HISTORY #12-14): the old query shape — `WHERE NOT(OR((aggregate_id = ? AND seq <= ?), ...)) ORDER BY seq` — cannot use any index (negation of OR over composite keys, and no global seq index exists), so every sync poll full-scanned the ENTIRE event table and sorted it through a temp B-tree: O(table) disk reads per call. On a long-lived session whose aggregate held ~84MB of durable events that was **84MB of disk reads per poll**, ~once per second per reconnecting client — sustained 50-84MB/s on an otherwise idle VM (`bun:sqlite` reads are io_uring-backed, invisible to `read(2)` accounting, strace, and fanotify — only `/proc/<pid>/io` `read_bytes` and per-cgroup `io.stat` see them), superlinear across incidents (1.18TB → 3.1TB) as the event log grew with the longest-lived session. Worse, the read load starved the very HTTP responses those clients were waiting for: they timed out, reconnected, and polled again — a self-sustaining read spiral (dozens of CLOSE-WAIT sockets from the reverse proxy as evidence).
90+
91+
**Implementation**: `packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts` — enumerate aggregates from `event_sequence` (one row per aggregate; a superset of `event`'s aggregates by FK — `selectDistinct` over `event` itself would still be a full covering-index scan per poll), then one indexed range scan per aggregate (`aggregate_id = ?` [+ `seq > watermark`]), union and sort by seq in memory: cost scales with the response, not the table; a fully-watermarked aggregate reads zero rows. Row-set semantics match the old shape on a static table; within an aggregate `seq` is unique so per-aggregate order is exactly preserved (cross-aggregate tie order was unspecified before and stays unspecified); the N+1 statements are not one snapshot — aggregates created after the enumeration are caught by the next poll, benign for a watermark catch-up protocol. Large aggregates are appended with loop-push (spread-push blows the JS stack above ~500-700k events). Reviewed by an independent Qwen3.8-Max agent pass (semantics parity verified with EXPLAIN QUERY PLAN against a scratch schema; measured 413ms → ~40ms on 200k rows). Tests: `packages/opencode/test/server/httpapi-sync.test.ts` (watermark skips a caught-up aggregate, unknown aggregates keep full history, mid-watermarks return only newer events, ghost-aggregate watermarks ignored, watermark 0 valid, global seq ordering).
92+
8593
## Build and release process
8694

8795
```sh
Collapse file

‎packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts
+55-15Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@ import { Session } from "@/session/session"
44
import { Database } from "@opencode-ai/core/database/database"
55
import { EventV2 } from "@opencode-ai/core/event"
66
import { EventV2Bridge } from "@/event-v2-bridge"
7-
import { EventTable } from "@opencode-ai/core/event/sql"
7+
import { EventSequenceTable, EventTable } from "@opencode-ai/core/event/sql"
88
import { asc } from "drizzle-orm"
99
import { and } from "drizzle-orm"
1010
import { eq } from "drizzle-orm"
11-
import { lte } from "drizzle-orm"
12-
import { not } from "drizzle-orm"
13-
import { or } from "drizzle-orm"
11+
import { gt } from "drizzle-orm"
1412
import { Effect, Scope } from "effect"
1513
import { HttpApiBuilder, HttpApiError } from "effect/unstable/httpapi"
1614
import { InstanceHttpApi } from "../api"
@@ -70,18 +68,60 @@ export const syncHandlers = HttpApiBuilder.group(InstanceHttpApi, "sync", (handl
7068
})
7169

7270
const history = Effect.fn("SyncHttpApi.history")(function* (ctx: { payload: typeof HistoryPayload.Type }) {
73-
const exclude = Object.entries(ctx.payload)
74-
return yield* db
75-
.select()
76-
.from(EventTable)
77-
.where(
78-
exclude.length > 0
79-
? not(or(...exclude.map(([id, seq]) => and(eq(EventTable.aggregate_id, id), lte(EventTable.seq, seq))))!)
80-
: undefined,
81-
)
82-
.orderBy(asc(EventTable.seq))
83-
.all()
71+
const exclude = new Map(Object.entries(ctx.payload))
72+
// Aggregate-scoped reads only. The previous NOT(OR(...)) + global ORDER
73+
// BY seq shape could not use any index (a negation of OR over composite
74+
// keys, and no global seq index exists) — every sync poll full-scanned
75+
// the ENTIRE event table and sorted it through a temp B-tree: O(table)
76+
// disk reads per call. On a long-lived session whose aggregate holds
77+
// ~84MB of events that is 84MB of reads per poll, ~once per second per
78+
// reconnecting client — measured live at 84MB/s sustained on an idle VM
79+
// (bun:sqlite reads are io_uring-backed: invisible to read(2) accounting
80+
// and to strace), and the read load starved the very responses those
81+
// clients were waiting for, so they timed out, reconnected, and polled
82+
// again: a self-sustaining read spiral that grew superlinearly with the
83+
// event log. Enumerate aggregates from event_sequence (one row per
84+
// aggregate, a superset of event's aggregates by FK — selectDistinct
85+
// over event itself is a full covering-index scan per poll) and
86+
// range-scan each through event_aggregate_seq_idx instead: cost scales
87+
// with the response, not the table — a fully-watermarked aggregate
88+
// reads zero rows.
89+
//
90+
// Semantics: same row set as the old NOT(OR(...)) shape for every
91+
// payload (static table); within an aggregate seq is unique, so
92+
// per-aggregate order is exactly preserved, but cross-aggregate tie
93+
// order was unspecified before and stays unspecified (JS stable sort
94+
// over aggregate enumeration). The N+1 statements are not one snapshot
95+
// like the old single query: aggregates created after the enumeration
96+
// are missed until the next poll — benign for a watermark catch-up
97+
// protocol (un-watermarked aggregates return full history next round;
98+
// no permanent gaps), noted here so it is a decision, not an accident.
99+
const aggregates = yield* db
100+
.select({ aggregateID: EventSequenceTable.aggregate_id })
101+
.from(EventSequenceTable)
84102
.pipe(Effect.orDie)
103+
const rows: Array<typeof EventTable.$inferSelect> = []
104+
for (const { aggregateID } of aggregates) {
105+
const watermark = exclude.get(aggregateID)
106+
const events = yield* db
107+
.select()
108+
.from(EventTable)
109+
.where(
110+
watermark === undefined
111+
? eq(EventTable.aggregate_id, aggregateID)
112+
: and(eq(EventTable.aggregate_id, aggregateID), gt(EventTable.seq, watermark)),
113+
)
114+
.orderBy(asc(EventTable.seq))
115+
.all()
116+
.pipe(Effect.orDie)
117+
// loop-push, not spread-push: a single aggregate can hold hundreds of
118+
// thousands of events and push(...events) blows the JS stack above
119+
// ~500-700k elements (measured in Bun/JSC) — the runaway-aggregate
120+
// class this handler exists to survive
121+
for (const event of events) rows.push(event)
122+
}
123+
rows.sort((a, b) => a.seq - b.seq)
124+
return rows
85125
})
86126

87127
return handlers.handle("start", start).handle("replay", replay).handle("steal", steal).handle("history", history)
Collapse file

‎packages/opencode/test/server/httpapi-sync.test.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/test/server/httpapi-sync.test.ts
+81Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,87 @@ describe("sync HttpApi", () => {
122122
{ git: true, config: { formatter: false, lsp: false } },
123123
)
124124

125+
it.instance(
126+
"history watermarks skip known aggregates and return only newer events",
127+
() =>
128+
Effect.gen(function* () {
129+
Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = true
130+
const tmp = yield* TestInstance
131+
const headers = { "x-opencode-directory": tmp.directory, "content-type": "application/json" }
132+
const session = yield* Session.use.create({ title: "watermark" })
133+
const sessionB = yield* Session.use.create({ title: "watermark-b" })
134+
// a second durable event on the same aggregate (session.updated)
135+
const renamed = yield* requestInDirectory(`/session/${session.id}`, tmp.directory, {
136+
method: "PATCH",
137+
headers,
138+
body: JSON.stringify({ title: "watermark-2" }),
139+
})
140+
expect(renamed.status).toBe(200)
141+
142+
const all = yield* requestInDirectory(SyncPaths.history, tmp.directory, {
143+
method: "POST",
144+
headers,
145+
body: JSON.stringify({}),
146+
})
147+
expect(all.status).toBe(200)
148+
const rows = (yield* all.json) as Array<{ aggregate_id: string; seq: number }>
149+
const own = rows.filter((row) => row.aggregate_id === session.id)
150+
// pins the PATCH-written second durable event: without it the
151+
// mid-watermark check below degenerates into a vacuous zero-watermark
152+
expect(own.length).toBeGreaterThanOrEqual(2)
153+
const lastSeq = Math.max(...own.map((row) => row.seq))
154+
const seqs = rows.map((row) => row.seq)
155+
expect(seqs).toEqual([...seqs].sort((a, b) => a - b)) // ordered by seq
156+
157+
// a watermark at the aggregate's last seq skips it entirely
158+
const caughtUp = yield* requestInDirectory(SyncPaths.history, tmp.directory, {
159+
method: "POST",
160+
headers,
161+
body: JSON.stringify({ [session.id]: lastSeq }),
162+
})
163+
expect(caughtUp.status).toBe(200)
164+
const remaining = (yield* caughtUp.json) as Array<{ aggregate_id: string }>
165+
expect(remaining.map((row) => row.aggregate_id)).not.toContain(session.id)
166+
expect(remaining.map((row) => row.aggregate_id)).toContain(sessionB.id)
167+
168+
// a watermark for an aggregate that does not exist is silently ignored
169+
const ghost = yield* requestInDirectory(SyncPaths.history, tmp.directory, {
170+
method: "POST",
171+
headers,
172+
body: JSON.stringify({ "ses_nonexistent-ghost": lastSeq }),
173+
})
174+
expect(ghost.status).toBe(200)
175+
expect(((yield* ghost.json) as Array<{ aggregate_id: string }>).map((row) => row.aggregate_id)).toContain(
176+
sessionB.id,
177+
)
178+
179+
// watermark 0 is valid (NonNegativeInt) and excludes nothing
180+
const zero = yield* requestInDirectory(SyncPaths.history, tmp.directory, {
181+
method: "POST",
182+
headers,
183+
body: JSON.stringify({ [session.id]: 0 }),
184+
})
185+
expect(zero.status).toBe(200)
186+
expect(((yield* zero.json) as Array<{ aggregate_id: string }>).map((row) => row.aggregate_id)).toContain(
187+
session.id,
188+
)
189+
190+
// an unknown aggregate keeps its full history, a watermarked one only newer events
191+
const midSeq = Math.max(0, lastSeq - 1)
192+
const partial = yield* requestInDirectory(SyncPaths.history, tmp.directory, {
193+
method: "POST",
194+
headers,
195+
body: JSON.stringify({ [session.id]: midSeq }),
196+
})
197+
expect(partial.status).toBe(200)
198+
const newer = ((yield* partial.json) as Array<{ aggregate_id: string; seq: number }>).filter(
199+
(row) => row.aggregate_id === session.id,
200+
)
201+
expect(newer.map((row) => row.seq)).toEqual([lastSeq])
202+
}),
203+
{ git: true, config: { formatter: false, lsp: false } },
204+
)
205+
125206
it.instance.skip(
126207
"returns structured validation errors",
127208
() =>

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.