The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 23:15 UTC
perf(server): discover compaction candidates on the reader worker (#21881)
Julius Marminge committed
Oct 19, 2026 at 20:36 UTC
fc857759c345eca6baea66bdf93a5973a2f70467
2 files changed
+97
-6
apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+92
@@ -1,3 +1,5 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3
import * as ServerSettings from "../serverSettings.ts";
4
import { assert, it } from "@effect/vitest";
5
import {
@@ -30,8 +32,10 @@ import * as Deferred from "effect/Deferred";
32
import * as Duration from "effect/Duration";
33
import * as Effect from "effect/Effect";
34
import * as Fiber from "effect/Fiber";
35
+import * as FileSystem from "effect/FileSystem";
36
import * as Layer from "effect/Layer";
37
import * as Option from "effect/Option";
38
+import * as Path from "effect/Path";
39
import * as Queue from "effect/Queue";
40
import * as Ref from "effect/Ref";
41
import * as Scheduler from "effect/Scheduler";
@@ -3551,3 +3555,91 @@ it.effect("publishes live events in commit order across concurrent writers", ()
3555
}).pipe(Effect.provide(layerEventSink));
3556
}).pipe(Effect.provide(layerDatabase)),
3557
);
3558
+
3559
+it.effect.each(["events", "receipts"] as const)(
3560
+ "allows writes while compaction waits for the reader to discover obsolete %s",
3561
+ (kind) =>
3562
+ Effect.gen(function* () {
3563
+ const fs = yield* FileSystem.FileSystem;
3564
+ const path = yield* Path.Path;
3565
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "compaction-reader-" });
3566
+ const database = SqlitePersistence.layerFromPath(path.join(directory, "statev2.sqlite"));
3567
+ const maintenanceLayer = ProjectionMaintenance.layer.pipe(
3568
+ Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
3569
+ Layer.provideMerge(database),
3570
+ );
3571
+ yield* Effect.gen(function* () {
3572
+ const sql = yield* SqlClient.SqlClient;
3573
+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
3574
+ const now = DateTime.formatIso(yield* DateTime.now);
3575
+ yield* sql`
3576
+ INSERT INTO orchestration_v2_legacy_imports (
3577
+ thread_id, source_updated_at, shell_imported_at, transcript_imported_at,
3578
+ imported_message_count, last_error
3579
+ ) VALUES ('imported', ${now}, ${now}, ${now}, 1, NULL)
3580
+ `;
3581
+ for (const threadId of ["imported", "pending"]) {
3582
+ if (kind === "events") {
3583
+ yield* sql`
3584
+ INSERT INTO orchestration_events (
3585
+ event_id, aggregate_kind, stream_id, stream_version, event_type,
3586
+ occurred_at, actor_kind, payload_json, metadata_json, application_event_version
3587
+ ) VALUES (
3588
+ ${threadId}, 'thread', ${threadId}, 1, 'thread.message-appended',
3589
+ ${now}, 'user', '{}', '{}', 1
3590
+ )
3591
+ `;
3592
+ } else {
3593
+ yield* sql`
3594
+ INSERT INTO orchestration_command_receipts (
3595
+ command_id, aggregate_kind, aggregate_id, accepted_at, result_sequence,
3596
+ status, command_type
3597
+ ) VALUES (${threadId}, 'thread', ${threadId}, ${now}, 1, 'accepted', 'legacy')
3598
+ `;
3599
+ }
3600
+ }
3601
+ yield* sql`CREATE TABLE concurrent_writes (value TEXT)`;
3602
+ const readerHeld = yield* Deferred.make<void>();
3603
+ const releaseReader = yield* Deferred.make<void>();
3604
+ const reader = yield* sql
3605
+ .withTransaction(
3606
+ Deferred.succeed(readerHeld, undefined).pipe(
3607
+ Effect.andThen(Deferred.await(releaseReader)),
3608
+ ),
3609
+ )
3610
+ .pipe(NodeSqliteClient.readOnly, Effect.forkChild);
3611
+ yield* Deferred.await(readerHeld);
3612
+ const discoveryStarted = yield* Deferred.make<Tracer.Span>();
3613
+ const observeDiscovery: Statement.Transformer = (statement, _sql, _fiber, span) => {
3614
+ const [query] = statement.compile();
3615
+ const pageQuery =
3616
+ kind === "events" ? /^\s*SELECT\s+event\.sequence/ : /^\s*SELECT\s+receipt\.rowid/;
3617
+ return pageQuery.test(query)
3618
+ ? Deferred.succeed(discoveryStarted, span).pipe(Effect.as(statement))
3619
+ : Effect.succeed(statement);
3620
+ };
3621
+ const compacted = yield* Deferred.make<void>();
3622
+ const compaction = yield* maintenance.compactEventStore.pipe(
3623
+ Effect.provideService(Statement.CurrentTransformer, observeDiscovery),
3624
+ Effect.provideService(Statement.SpanPropagationEnabled, true),
3625
+ Effect.tap(() => Deferred.succeed(compacted, undefined)),
3626
+ Effect.forkChild,
3627
+ );
3628
+ const discoverySpan = yield* Deferred.await(discoveryStarted);
3629
+ yield* sql`INSERT INTO concurrent_writes VALUES ('committed')`;
3630
+ assert.isFalse(yield* Deferred.isDone(compacted));
3631
+ assert.deepEqual(yield* sql`SELECT value FROM concurrent_writes`, [{ value: "committed" }]);
3632
+ yield* Deferred.succeed(releaseReader, undefined);
3633
+ yield* Fiber.join(reader);
3634
+ const result = yield* Fiber.join(compaction);
3635
+ assert.equal(discoverySpan.attributes.get("db.connection"), "reader");
3636
+ assert.equal(result.deletedEventCount, kind === "events" ? 1 : 0);
3637
+ assert.equal(result.deletedReceiptCount, kind === "receipts" ? 1 : 0);
3638
+ const retained =
3639
+ kind === "events"
3640
+ ? yield* sql`SELECT stream_id AS id FROM orchestration_events`
3641
+ : yield* sql`SELECT aggregate_id AS id FROM orchestration_command_receipts`;
3642
+ assert.deepEqual(retained, [{ id: "pending" }]);
3643
+ }).pipe(Effect.provide(maintenanceLayer));
3644
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
3645
+);
apps/server/src/orchestration-v2/ProjectionMaintenance.ts
+5
-6
@@ -1,4 +1,5 @@
1
import { ThreadId } from "@t3tools/contracts";
2
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3
import * as Context from "effect/Context";
4
import * as DateTime from "effect/DateTime";
5
import * as Effect from "effect/Effect";
@@ -226,8 +227,7 @@ export const layer: Layer.Layer<
227
const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
228
const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);
229
// Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.
229
- // Discovery runs on the shared synchronous connection; json_extract over
230
- // large payloads made 500-row pages block the event loop for ~90ms.
230
+ // Small pages bound work on the reader worker and synchronous fallback.
231
const COMPACTION_PAGE_SIZE = 50;
232
233
/**
@@ -299,7 +299,7 @@ export const layer: Layer.Layer<
299
WHERE event.sequence <= ${throughSequence}
300
ORDER BY event.sequence DESC
301
LIMIT ${COMPACTION_PAGE_SIZE}
302
- `;
302
+ `.pipe(NodeSqliteClient.readOnly);
303
const obsolete: number[] = [];
304
for (const row of rows) {
305
if (row.imported_legacy_thread === 1) {
@@ -342,8 +342,7 @@ export const layer: Layer.Layer<
342
}
343
}
344
}
345
- // Both discovery and deletion use the synchronous connection. Yield even
346
- // when this page has nothing to delete so startup and requests can progress.
345
+ // Yield even without deletions for clients using the synchronous fallback.
346
yield* Effect.yieldNow;
347
if (obsolete.length > 0) {
348
yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
@@ -376,7 +375,7 @@ export const layer: Layer.Layer<
375
WHERE receipt.rowid <= ${throughReceiptRowId}
376
ORDER BY receipt.rowid DESC
377
LIMIT ${COMPACTION_PAGE_SIZE}
379
- `;
378
+ `.pipe(NodeSqliteClient.readOnly);
379
const obsolete = rows
380
.filter((row) => row.imported_legacy_thread === 1)
381
.map((row) => row.command_id);