|
| 1 | +import { assert, it } from "@effect/vitest"; |
| 2 | +import { EventId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; |
| 3 | +import * as Clock from "effect/Clock"; |
| 4 | +import * as Deferred from "effect/Deferred"; |
| 5 | +import * as DateTime from "effect/DateTime"; |
| 6 | +import * as Effect from "effect/Effect"; |
| 7 | +import * as Fiber from "effect/Fiber"; |
| 8 | +import * as FileSystem from "effect/FileSystem"; |
| 9 | +import * as Layer from "effect/Layer"; |
| 10 | +import * as Path from "effect/Path"; |
| 11 | +import * as SqlClient from "effect/sql/SqlClient"; |
| 12 | +import * as Statement from "effect/sql/Statement"; |
| 13 | +import * as Tracer from "effect/Tracer"; |
| 14 | +import * as TestClock from "effect/testing/TestClock"; |
| 15 | +import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 16 | + |
| 17 | +import * as SqlitePersistence from "../persistence/Sqlite.ts"; |
| 18 | +import * as ProjectionStore from "./ProjectionStore.ts"; |
| 19 | + |
| 20 | +/** |
| 21 | + * A fixed timestamp for the writer's rows. |
| 22 | + * |
| 23 | + * The read does not care when the rows were written, and a fixed epoch keeps |
| 24 | + * the test free of wall-clock reads. |
| 25 | + */ |
| 26 | +const FIXED_EPOCH = "2026-01-01T00:00:00.000Z"; |
| 27 | + |
| 28 | +/** |
| 29 | + * The lock wait a read pays, and the connection it pays it on. |
| 30 | + * |
| 31 | + * The measurement is the point of the change, so it is taken the way the |
| 32 | + * server takes it: the `db.connection` and `db.lock_wait_ms` attributes that |
| 33 | + * `nodeSqliteClient` stamps on the span of the transaction that acquired the |
| 34 | + * connection. |
| 35 | + * |
| 36 | + * The database is file-backed, because the reader worker is a second |
| 37 | + * connection and an in-memory database cannot be shared between two of them. |
| 38 | + */ |
| 39 | +const measureRead = Effect.fn("measureRead")(function* (threadId: ThreadId) { |
| 40 | + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; |
| 41 | + const acquired: Array<{ readonly connection: string; readonly lockWaitMs: number }> = []; |
| 42 | + const tracer = Tracer.make({ |
| 43 | + span: (spanOptions) => { |
| 44 | + const span = new Tracer.NativeSpan(spanOptions); |
| 45 | + const end = span.end.bind(span); |
| 46 | + span.end = (endTime, exit) => { |
| 47 | + end(endTime, exit); |
| 48 | + const connection = span.attributes.get("db.connection"); |
| 49 | + if (connection !== undefined) { |
| 50 | + acquired.push({ |
| 51 | + connection, |
| 52 | + lockWaitMs: Number(span.attributes.get("db.lock_wait_ms") ?? 0), |
| 53 | + }); |
| 54 | + } |
| 55 | + }; |
| 56 | + return span; |
| 57 | + }, |
| 58 | + }); |
| 59 | + |
| 60 | + yield* projectionStore |
| 61 | + .getThreadRecords(threadId, ["runs"]) |
| 62 | + .pipe(Effect.provideService(Statement.SpanPropagationEnabled, true), Effect.withTracer(tracer)); |
| 63 | + |
| 64 | + return acquired; |
| 65 | +}); |
| 66 | + |
| 67 | +const createThread = (threadId: ThreadId) => |
| 68 | + Effect.gen(function* () { |
| 69 | + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; |
| 70 | + const now = yield* DateTime.now; |
| 71 | + yield* projectionStore.apply({ |
| 72 | + id: EventId.make(`event:${threadId}:created`), |
| 73 | + type: "thread.created", |
| 74 | + threadId, |
| 75 | + occurredAt: now, |
| 76 | + payload: { |
| 77 | + createdBy: "user", |
| 78 | + creationSource: "web", |
| 79 | + id: threadId, |
| 80 | + projectId: ProjectId.make("project:lockwait"), |
| 81 | + title: threadId, |
| 82 | + providerInstanceId: ProviderInstanceId.make("codex"), |
| 83 | + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, |
| 84 | + runtimeMode: "full-access", |
| 85 | + interactionMode: "default", |
| 86 | + branch: null, |
| 87 | + worktreePath: null, |
| 88 | + activeProviderThreadId: null, |
| 89 | + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 90 | + forkedFrom: null, |
| 91 | + createdAt: now, |
| 92 | + updatedAt: now, |
| 93 | + archivedAt: null, |
| 94 | + settledOverride: null, |
| 95 | + settledAt: null, |
| 96 | + lastVisitedAt: null, |
| 97 | + deletedAt: null, |
| 98 | + } as never, |
| 99 | + }); |
| 100 | + }); |
| 101 | + |
| 102 | +it.effect( |
| 103 | + "the projection read takes its lock on the reader connection, and the lock wait is reported", |
| 104 | + () => |
| 105 | + Effect.gen(function* () { |
| 106 | + // An isolated T3 home: a temporary directory of its own, with the |
| 107 | + // database inside it. The live T3 home is never touched. |
| 108 | + const fs = yield* FileSystem.FileSystem; |
| 109 | + const path = yield* Path.Path; |
| 110 | + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-lockwait-" }); |
| 111 | + const database = SqlitePersistence.layerFromPath(path.join(home, "statev2.sqlite")); |
| 112 | + const storeLayer = Layer.mergeAll( |
| 113 | + ProjectionStore.layer.pipe(Layer.provideMerge(database)), |
| 114 | + database, |
| 115 | + NodeServices.layer, |
| 116 | + ); |
| 117 | + |
| 118 | + const threadId = ThreadId.make("thread:lockwait:1"); |
| 119 | + const acquired = yield* Effect.gen(function* () { |
| 120 | + yield* createThread(threadId); |
| 121 | + return yield* measureRead(threadId); |
| 122 | + }).pipe(Effect.provide(storeLayer)); |
| 123 | + |
| 124 | + // The read ran on the reader connection... |
| 125 | + assert.deepEqual( |
| 126 | + acquired.map((entry) => entry.connection), |
| 127 | + ["reader"], |
| 128 | + ); |
| 129 | + // ...and the lock wait it paid is reported, so the before/after can be |
| 130 | + // compared on the same measure the server logs. |
| 131 | + assert.equal(acquired.length, 1); |
| 132 | + assert.isAtLeast(acquired[0]?.lockWaitMs ?? -1, 0); |
| 133 | + }).pipe(Effect.provide(NodeServices.layer)), |
| 134 | +); |
| 135 | + |
| 136 | +/** |
| 137 | + * The read, while a writer inserts rows the whole time. |
| 138 | + * |
| 139 | + * This is the case that was measured in the field: a busy host whose writer |
| 140 | + * is behind, and MCP reads that have to wait for the write lock. The writer |
| 141 | + * here is a stream of inserts, not a held transaction, because a held |
| 142 | + * transaction is a different (and much rarer) case. |
| 143 | + */ |
| 144 | +const measureReadUnderWriteLoad = Effect.fn("measureReadUnderWriteLoad")(function* ( |
| 145 | + threadId: ThreadId, |
| 146 | +) { |
| 147 | + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; |
| 148 | + const sql = yield* SqlClient.SqlClient; |
| 149 | + const acquired: Array<{ readonly connection: string; readonly lockWaitMs: number }> = []; |
| 150 | + const tracer = Tracer.make({ |
| 151 | + span: (spanOptions) => { |
| 152 | + const span = new Tracer.NativeSpan(spanOptions); |
| 153 | + const end = span.end.bind(span); |
| 154 | + span.end = (endTime, exit) => { |
| 155 | + end(endTime, exit); |
| 156 | + const connection = span.attributes.get("db.connection"); |
| 157 | + if (connection !== undefined) { |
| 158 | + acquired.push({ |
| 159 | + connection, |
| 160 | + lockWaitMs: Number(span.attributes.get("db.lock_wait_ms") ?? 0), |
| 161 | + }); |
| 162 | + } |
| 163 | + }; |
| 164 | + return span; |
| 165 | + }, |
| 166 | + }); |
| 167 | + |
| 168 | + // A writer, inserting rows the whole time the read runs. It signals when it |
| 169 | + // has written enough for the read to meet a busy writer. |
| 170 | + const writing = yield* Deferred.make<void>(); |
| 171 | + const writer = yield* Effect.repeat( |
| 172 | + sql`INSERT INTO orchestration_v2_projection_checkpoints (checkpoint_id, scope_id, thread_id, run_id, checkpoint_version, checkpoint_kind, payload_json, created_at) VALUES (${crypto.randomUUID()}, ${"scope"}, ${threadId}, ${"run"}, 1, 'test', '{}', ${FIXED_EPOCH})`.pipe( |
| 173 | + Effect.ignore, |
| 174 | + ), |
| 175 | + { times: 400 }, |
| 176 | + ).pipe( |
| 177 | + Effect.andThen(Deferred.succeed(writing, undefined)), |
| 178 | + Effect.forkChild({ startImmediately: true }), |
| 179 | + ); |
| 180 | + |
| 181 | + // Wait for the milestone, not for a wall-clock duration. |
| 182 | + yield* Deferred.await(writing); |
| 183 | + const started = yield* Clock.currentTimeMillis; |
| 184 | + yield* projectionStore |
| 185 | + .getThreadRecords(threadId, ["runs"]) |
| 186 | + .pipe(Effect.provideService(Statement.SpanPropagationEnabled, true), Effect.withTracer(tracer)); |
| 187 | + const elapsedMs = (yield* Clock.currentTimeMillis) - started; |
| 188 | + yield* Fiber.join(writer); |
| 189 | + |
| 190 | + return { acquired, elapsedMs }; |
| 191 | +}); |
| 192 | + |
| 193 | +/** |
| 194 | + * The same read, but on the writer connection. |
| 195 | + * |
| 196 | + * This is the "before": the read that ran on the writer, where it had to take |
| 197 | + * the write lock that the writer was holding. |
| 198 | + */ |
| 199 | +const measureReadOnWriter = Effect.fn("measureReadOnWriter")(function* (threadId: ThreadId) { |
| 200 | + const sql = yield* SqlClient.SqlClient; |
| 201 | + const acquired: Array<{ readonly connection: string; readonly lockWaitMs: number }> = []; |
| 202 | + const tracer = Tracer.make({ |
| 203 | + span: (spanOptions) => { |
| 204 | + const span = new Tracer.NativeSpan(spanOptions); |
| 205 | + const end = span.end.bind(span); |
| 206 | + span.end = (endTime, exit) => { |
| 207 | + end(endTime, exit); |
| 208 | + const connection = span.attributes.get("db.connection"); |
| 209 | + if (connection !== undefined) { |
| 210 | + acquired.push({ |
| 211 | + connection, |
| 212 | + lockWaitMs: Number(span.attributes.get("db.lock_wait_ms") ?? 0), |
| 213 | + }); |
| 214 | + } |
| 215 | + }; |
| 216 | + return span; |
| 217 | + }, |
| 218 | + }); |
| 219 | + |
| 220 | + // A writer inserting rows the whole time the read runs. |
| 221 | + const writing = yield* Deferred.make<void>(); |
| 222 | + const writer = yield* Effect.repeat( |
| 223 | + sql`INSERT INTO orchestration_v2_projection_checkpoints (checkpoint_id, scope_id, thread_id, run_id, checkpoint_version, checkpoint_kind, payload_json, created_at) VALUES (${crypto.randomUUID()}, ${"scope"}, ${threadId}, ${"run"}, 1, 'test', '{}', ${FIXED_EPOCH})`.pipe( |
| 224 | + Effect.ignore, |
| 225 | + ), |
| 226 | + { times: 400 }, |
| 227 | + ).pipe( |
| 228 | + Effect.andThen(Deferred.succeed(writing, undefined)), |
| 229 | + Effect.forkChild({ startImmediately: true }), |
| 230 | + ); |
| 231 | + |
| 232 | + yield* Deferred.await(writing); |
| 233 | + const started = yield* Clock.currentTimeMillis; |
| 234 | + // A read on the writer connection: the same statement, without the reader. |
| 235 | + yield* sql |
| 236 | + .withTransaction( |
| 237 | + sql`SELECT payload_json FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId} LIMIT 1`, |
| 238 | + ) |
| 239 | + .pipe(Effect.provideService(Statement.SpanPropagationEnabled, true), Effect.withTracer(tracer)); |
| 240 | + const elapsedMs = (yield* Clock.currentTimeMillis) - started; |
| 241 | + yield* Fiber.join(writer); |
| 242 | + |
| 243 | + return { acquired, elapsedMs }; |
| 244 | +}); |
| 245 | + |
| 246 | +it.effect("the projection read does not wait for the writer's lock", () => |
| 247 | + Effect.gen(function* () { |
| 248 | + const fs = yield* FileSystem.FileSystem; |
| 249 | + const path = yield* Path.Path; |
| 250 | + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-lockwait-load-" }); |
| 251 | + const database = SqlitePersistence.layerFromPath(path.join(home, "statev2.sqlite")); |
| 252 | + const storeLayer = Layer.mergeAll( |
| 253 | + ProjectionStore.layer.pipe(Layer.provideMerge(database)), |
| 254 | + database, |
| 255 | + NodeServices.layer, |
| 256 | + ); |
| 257 | + |
| 258 | + const threadId = ThreadId.make("thread:lockwait:load"); |
| 259 | + const { acquired, elapsedMs } = yield* Effect.gen(function* () { |
| 260 | + yield* createThread(threadId); |
| 261 | + return yield* measureReadUnderWriteLoad(threadId); |
| 262 | + }).pipe(Effect.provide(storeLayer), TestClock.withLive); |
| 263 | + |
| 264 | + // The read ran on the reader, so the writer's lock did not make it wait: |
| 265 | + // the reader has its own connection and its own lock. |
| 266 | + assert.deepEqual( |
| 267 | + acquired.map((entry) => entry.connection), |
| 268 | + ["reader"], |
| 269 | + ); |
| 270 | + assert.equal(acquired.length, 1); |
| 271 | + console.log( |
| 272 | + `MEASURE read-under-write-load: connection=${acquired[0]?.connection} lock_wait_ms=${acquired[0]?.lockWaitMs} elapsed_ms=${elapsedMs}`, |
| 273 | + ); |
| 274 | + }).pipe(Effect.provide(NodeServices.layer)), |
| 275 | +); |
| 276 | + |
| 277 | +it.effect("the same read on the writer connection waits for the writer's lock", () => |
| 278 | + Effect.gen(function* () { |
| 279 | + const fs = yield* FileSystem.FileSystem; |
| 280 | + const path = yield* Path.Path; |
| 281 | + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-lockwait-writer-" }); |
| 282 | + const database = SqlitePersistence.layerFromPath(path.join(home, "statev2.sqlite")); |
| 283 | + const storeLayer = Layer.mergeAll( |
| 284 | + ProjectionStore.layer.pipe(Layer.provideMerge(database)), |
| 285 | + database, |
| 286 | + NodeServices.layer, |
| 287 | + ); |
| 288 | + |
| 289 | + const threadId = ThreadId.make("thread:lockwait:writer"); |
| 290 | + const { acquired, elapsedMs } = yield* Effect.gen(function* () { |
| 291 | + yield* createThread(threadId); |
| 292 | + return yield* measureReadOnWriter(threadId); |
| 293 | + }).pipe(Effect.provide(storeLayer), TestClock.withLive); |
| 294 | + |
| 295 | + assert.deepEqual( |
| 296 | + acquired.map((entry) => entry.connection), |
| 297 | + ["writer"], |
| 298 | + ); |
| 299 | + console.log( |
| 300 | + `MEASURE read-on-writer: connection=${acquired[0]?.connection} lock_wait_ms=${acquired[0]?.lockWaitMs} elapsed_ms=${elapsedMs}`, |
| 301 | + ); |
| 302 | + }).pipe(Effect.provide(NodeServices.layer)), |
| 303 | +); |
0 commit comments