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 — perf(server): events stop maintaining two indexes no query needs · pingdotgg/t3code@07ab2ce

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src
    • orchestration-v2
      • FoundationPersistence.test.ts
    • persistence
      • Migrations.ts
      • Migrations
        • 055_OrchestrationV2.test.ts
        • 063_DropUnusedEventIndexes.test.ts
        • 063_DropUnusedEventIndexes.ts
      • OrchestrationEventStore.sequence.test.ts
      • OrchestrationEventStore.ts
      • reconcileV2PreviewMigration.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/orchestration-v2/FoundationPersistence.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ it.effect("verifies thread membership using only the thread-created partial inde
260260
);
261261
const details = plan.map((row) => row.detail).join("\n");
262262
assert.match(details, /USING (?:COVERING )?INDEX orchestration_events_v2_created_threads_idx/);
263-
assert.notMatch(details, /idx_orch_events_stream_sequence|TEMP B-TREE/);
263+
assert.notMatch(details, /TEMP B-TREE/);
264264
}).pipe(Effect.provide(layerTest)),
265265
);
266266

Collapse file

‎apps/server/src/persistence/Migrations.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/persistence/Migrations.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ import Migration0059 from "./Migrations/059_McpAppModelContext.ts";
7676
import Migration0060 from "./Migrations/060_ThreadSnapshotWindowIndexes.ts";
7777
import Migration0061 from "./Migrations/061_PullRequestReviewGuides.ts";
7878
import Migration0062 from "./Migrations/062_ThreadFailureLookupIndex.ts";
79+
import Migration0063 from "./Migrations/063_DropUnusedEventIndexes.ts";
7980

8081
/**
8182
* Migration loader with all migrations defined inline.
@@ -152,6 +153,7 @@ export const migrationEntries = [
152153
[60, "ThreadSnapshotWindowIndexes", Migration0060],
153154
[61, "PullRequestReviewGuides", Migration0061],
154155
[62, "ThreadFailureLookupIndex", Migration0062],
156+
[63, "DropUnusedEventIndexes", Migration0063],
155157
] as const;
156158

157159
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
Collapse file

‎apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts
+3-1Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ layer("055_OrchestrationV2", (it) => {
1313
Effect.sync(() => {
1414
assert.deepStrictEqual(
1515
migrationEntries.map(([id]) => id),
16-
Array.from({ length: 62 }, (_, index) => index + 1),
16+
Array.from({ length: 63 }, (_, index) => index + 1),
1717
);
1818
}),
1919
);
@@ -34,6 +34,7 @@ layer("055_OrchestrationV2", (it) => {
3434
[60, "ThreadSnapshotWindowIndexes"],
3535
[61, "PullRequestReviewGuides"],
3636
[62, "ThreadFailureLookupIndex"],
37+
[63, "DropUnusedEventIndexes"],
3738
]);
3839
assert.deepStrictEqual(yield* runMigrations(), []);
3940

@@ -62,6 +63,7 @@ layer("055_OrchestrationV2", (it) => {
6263
{ migration_id: 60, name: "ThreadSnapshotWindowIndexes" },
6364
{ migration_id: 61, name: "PullRequestReviewGuides" },
6465
{ migration_id: 62, name: "ThreadFailureLookupIndex" },
66+
{ migration_id: 63, name: "DropUnusedEventIndexes" },
6567
]);
6668

6769
const tables = yield* sql<{ readonly name: string }>`
Collapse file

‎apps/server/src/persistence/Migrations/063_DropUnusedEventIndexes.test.ts‎

Copy file name to clipboard
+41Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { assert, it } from "@effect/vitest";
2+
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3+
import * as Effect from "effect/Effect";
4+
import * as Layer from "effect/Layer";
5+
import * as SqlClient from "effect/sql/SqlClient";
6+
7+
import { runMigrations } from "../Migrations.ts";
8+
9+
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));
10+
11+
layer("063_DropUnusedEventIndexes", (it) => {
12+
it.effect("drops the event indexes no read uses and keeps the ones reads need", () =>
13+
Effect.gen(function* () {
14+
const sql = yield* SqlClient.SqlClient;
15+
yield* runMigrations({ toMigrationInclusive: 62 });
16+
yield* runMigrations({ toMigrationInclusive: 63 });
17+
18+
const rows = yield* sql<{ readonly name: string }>`
19+
SELECT name
20+
FROM sqlite_master
21+
WHERE type = 'index'
22+
AND tbl_name = 'orchestration_events'
23+
`;
24+
const indexes = new Set(rows.map((row) => row.name));
25+
26+
for (const removed of ["idx_orch_events_correlation_id", "idx_orch_events_stream_sequence"]) {
27+
assert.isFalse(indexes.has(removed), removed);
28+
}
29+
for (const kept of [
30+
"idx_orch_events_stream_version",
31+
"idx_orch_events_command_id",
32+
"idx_orchestration_events_application_sequence",
33+
"idx_orchestration_events_application_high_water",
34+
"idx_orchestration_events_agent_stream_sequence",
35+
"orchestration_events_v2_created_threads_idx",
36+
]) {
37+
assert.isTrue(indexes.has(kept), kept);
38+
}
39+
}),
40+
);
41+
});
Collapse file

‎apps/server/src/persistence/Migrations/063_DropUnusedEventIndexes.ts‎

Copy file name to clipboard
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import * as Effect from "effect/Effect";
2+
import * as SqlClient from "effect/sql/SqlClient";
3+
4+
export default Effect.gen(function* () {
5+
const sql = yield* SqlClient.SqlClient;
6+
7+
yield* sql`DROP INDEX IF EXISTS idx_orch_events_correlation_id`;
8+
yield* sql`DROP INDEX IF EXISTS idx_orch_events_stream_sequence`;
9+
});
Collapse file

‎apps/server/src/persistence/OrchestrationEventStore.sequence.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/persistence/OrchestrationEventStore.sequence.test.ts
+77Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,83 @@ it.effect("uses indexed high-water lookups for populated history without OR scan
273273
),
274274
);
275275

276+
it.effect("reads one thread's events through the thread index, not the sequence range", () =>
277+
Effect.gen(function* () {
278+
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
279+
const sql = yield* SqlClient.SqlClient;
280+
yield* runMigrations();
281+
yield* sql`
282+
WITH RECURSIVE history(n) AS (
283+
SELECT 1 UNION ALL SELECT n + 1 FROM history WHERE n < 25000
284+
)
285+
INSERT INTO orchestration_events (
286+
event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
287+
actor_kind, payload_json, metadata_json, application_event_version
288+
)
289+
SELECT 'history:' || n, 'thread',
290+
CASE WHEN n IN (12, 24990) THEN 'target' ELSE 'other' END,
291+
n, 'provider-session.detached', ${occurredAt}, 'server',
292+
'{"providerSessionId":"session","detachedAt":"' || ${occurredAt} || '"}',
293+
'{}', 2
294+
FROM history
295+
`;
296+
const statements: Array<string> = [];
297+
const tracer = Tracer.make({
298+
span(options) {
299+
const span = new Tracer.NativeSpan(options);
300+
const end = span.end.bind(span);
301+
span.end = (endTime, exit) => {
302+
end(endTime, exit);
303+
const query = span.attributes.get("db.query.text");
304+
if (typeof query === "string") statements.push(query);
305+
};
306+
return span;
307+
},
308+
});
309+
const threadId = ThreadId.make("target");
310+
const byThread = yield* store
311+
.readAgentEvents({ threadId })
312+
.pipe(Stream.runCollect, Effect.withTracer(tracer));
313+
const byThreadAndType = yield* store
314+
.readAgentEvents({ threadId, eventType: "provider-session.detached" })
315+
.pipe(Stream.runCollect, Effect.withTracer(tracer));
316+
const stats = yield* store
317+
.getAgentReplayStats({ threadId, afterSequence: 0, throughSequence: 25_000, maxEvents: 10 })
318+
.pipe(Effect.withTracer(tracer));
319+
assert.deepEqual(
320+
byThread.map((event) => event.sequence),
321+
[12, 24990],
322+
);
323+
assert.deepEqual(
324+
byThreadAndType.map((event) => event.sequence),
325+
[12, 24990],
326+
);
327+
assert.equal(stats.eventCount, 2);
328+
assert.equal(statements.length, 3);
329+
const plans = yield* Effect.forEach(
330+
[
331+
[0, Number.MAX_SAFE_INTEGER, "target", 500],
332+
[0, Number.MAX_SAFE_INTEGER, "target", "provider-session.detached", 500],
333+
["target", 0, 25_000, 11],
334+
],
335+
(params, index) =>
336+
sql.unsafe<{ readonly detail: string }>(`EXPLAIN QUERY PLAN ${statements[index]}`, params),
337+
);
338+
for (const plan of plans) {
339+
assert.match(
340+
plan.map((row) => row.detail).join("\n"),
341+
/SEARCH orchestration_events USING INDEX idx_orchestration_events_agent_stream_sequence \(stream_id=\? AND sequence>\? AND sequence<\?\)/,
342+
);
343+
}
344+
}).pipe(
345+
Effect.provide(
346+
OrchestrationEventStore.layer.pipe(
347+
Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })),
348+
),
349+
),
350+
),
351+
);
352+
276353
it.effect("replays a command's events through the command index, not the sequence range", () =>
277354
Effect.gen(function* () {
278355
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
Collapse file

‎apps/server/src/persistence/OrchestrationEventStore.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/persistence/OrchestrationEventStore.ts
+17-10Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,21 @@ const makeEventStore = Effect.gen(function* () {
425425
),
426426
);
427427

428+
const applicationRowsIndex = (input: {
429+
readonly threadId?: ThreadId;
430+
readonly commandId?: CommandId;
431+
readonly onlyAgentEvents?: boolean;
432+
}) => {
433+
// The sequence range otherwise wins and a command lookup scans every
434+
// V2 event, which blocks the server for seconds on large histories.
435+
if (input.commandId !== undefined) return sql`INDEXED BY idx_orch_events_command_id`;
436+
if (input.onlyAgentEvents !== true) {
437+
return sql`INDEXED BY idx_orchestration_events_application_high_water`;
438+
}
439+
if (input.threadId === undefined) return sql``;
440+
return sql`INDEXED BY idx_orchestration_events_agent_stream_sequence`;
441+
};
442+
428443
const readApplicationRows = (input: {
429444
readonly afterSequence: number;
430445
readonly throughSequence?: number;
@@ -449,15 +464,7 @@ const makeEventStore = Effect.gen(function* () {
449464
causation_event_id,
450465
correlation_id
451466
FROM orchestration_events
452-
${
453-
// The sequence range otherwise wins and a command lookup scans every
454-
// V2 event, which blocks the server for seconds on large histories.
455-
input.commandId !== undefined
456-
? sql`INDEXED BY idx_orch_events_command_id`
457-
: input.onlyAgentEvents === true
458-
? sql``
459-
: sql`INDEXED BY idx_orchestration_events_application_high_water`
460-
}
467+
${applicationRowsIndex(input)}
461468
WHERE sequence > ${input.afterSequence}
462469
AND sequence <= ${input.throughSequence ?? Number.MAX_SAFE_INTEGER}
463470
AND (
@@ -643,7 +650,7 @@ const makeEventStore = Effect.gen(function* () {
643650
COALESCE(MAX(event_type = 'thread.created'), 0) AS "hasCreateEvent"
644651
FROM (
645652
SELECT ${restoredPayloadJson} AS payload_json, event_type
646-
FROM orchestration_events
653+
FROM orchestration_events INDEXED BY idx_orchestration_events_agent_stream_sequence
647654
WHERE aggregate_kind = 'thread'
648655
AND stream_id = ${input.threadId}
649656
AND application_event_version = 2
Collapse file

‎apps/server/src/persistence/reconcileV2PreviewMigration.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ describe("V2 preview upgrade", () => {
4343
[60, "ThreadSnapshotWindowIndexes"],
4444
[61, "PullRequestReviewGuides"],
4545
[62, "ThreadFailureLookupIndex"],
46+
[63, "DropUnusedEventIndexes"],
4647
]);
4748
assert.deepStrictEqual(yield* runMigrations(), []);
4849
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -128,6 +129,7 @@ describe("V2 preview upgrade", () => {
128129
[60, "ThreadSnapshotWindowIndexes"],
129130
[61, "PullRequestReviewGuides"],
130131
[62, "ThreadFailureLookupIndex"],
132+
[63, "DropUnusedEventIndexes"],
131133
]);
132134
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
133135
);

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.