Skip to content
TypeScript

fix(server): route SQLite reads around writer contention (#23902)

Yash Singh6ed47b538c1a
diff --git a/apps/server/src/mcpApps/McpAppModelContext.ts b/apps/server/src/mcpApps/McpAppModelContext.ts
index d6894b38f8a..d50236ce6cd 100644
--- a/apps/server/src/mcpApps/McpAppModelContext.ts
+++ b/apps/server/src/mcpApps/McpAppModelContext.ts
@@ -1,5 +1,6 @@
import type { ThreadId, TurnItemId } from "@t3tools/contracts";
import * as Context from "effect/Context";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -83,7 +84,7 @@ export const layer = Layer.effect(
OR run.thread_id <> context.thread_id
)
ORDER BY context.updated_at, context.item_id
- `.pipe(Effect.mapError(fail));
+ `.pipe(NodeSqliteClient.readOnly, Effect.mapError(fail));
});
return McpAppModelContext.of({ set, forThread });
diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts
index 05be41e5728..c89beae951e 100644
--- a/apps/server/src/orchestration-v2/EffectOutbox.ts
+++ b/apps/server/src/orchestration-v2/EffectOutbox.ts
@@ -15,6 +15,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
@@ -420,6 +421,7 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
WHERE effect_id = ${effectId}
LIMIT 1
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.flatMap((rows) => {
const row = rows[0];
return row === undefined
@@ -437,6 +439,7 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
WHERE command_id = ${commandId}
ORDER BY created_at ASC, effect_id ASC
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.flatMap((rows) => decodeRows("list", rows)),
Effect.mapError((cause) =>
isEffectOutboxError(cause)
@@ -571,7 +574,7 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
SELECT MIN(candidate.available_at) AS available_at
FROM orchestration_v2_effect_outbox AS candidate
WHERE ${claimableCandidatePredicate()}
- `.pipe(Effect.withTracerEnabled(false));
+ `.pipe(NodeSqliteClient.readOnly, Effect.withTracerEnabled(false));
const availableAt = rows[0]?.available_at;
if (availableAt === undefined || availableAt === null) return Option.none();
const parsed = DateTime.make(availableAt);
diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
index accf2de7206..a37bcf8f2cd 100644
--- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
@@ -3218,3 +3218,83 @@ it.effect.each(["events", "receipts"] as const)(
}).pipe(Effect.provide(maintenanceLayer));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
+
+it.effect("routes projection node lookups to the reader connection", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "projection-reader-" });
+ const database = SqlitePersistence.layerFromPath(path.join(directory, "statev2.sqlite"));
+ const projectionLayer = ProjectionStore.layer.pipe(Layer.provideMerge(database));
+ yield* Effect.gen(function* () {
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const now = yield* DateTime.now;
+ const nodeId = NodeId.make("node:reader-routing");
+ const node = {
+ id: nodeId,
+ threadId: ThreadId.make("thread:reader-routing"),
+ runId: null,
+ parentNodeId: null,
+ rootNodeId: nodeId,
+ kind: "subagent" as const,
+ status: "running" as const,
+ countsForRun: false,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: null,
+ startedAt: now,
+ completedAt: null,
+ };
+ const spans: Array<Tracer.Span> = [];
+ const observe: Statement.Transformer = (statement, _sql, _fiber, span) => {
+ const [query] = statement.compile();
+ if (/orchestration_v2_projection_nodes WHERE node_id/.test(query)) {
+ spans.push(span);
+ }
+ return Effect.succeed(statement);
+ };
+ yield* Effect.gen(function* () {
+ assert.isFalse(yield* projections.isNodeStored(node));
+ }).pipe(
+ Effect.provideService(Statement.CurrentTransformer, observe),
+ Effect.provideService(Statement.SpanPropagationEnabled, true),
+ );
+ assert.equal(spans.length, 1);
+ assert.isTrue(
+ spans.every((span) => span.attributes.get("db.connection") === "reader"),
+ JSON.stringify(spans.map((span) => span.attributes.get("db.connection"))),
+ );
+ }).pipe(Effect.provide(projectionLayer));
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+);
+
+it.effect("loads a shell snapshot while the writer connection is occupied", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "shell-reader-" });
+ const database = SqlitePersistence.layerFromPath(path.join(directory, "statev2.sqlite"));
+ const projectionLayer = ProjectionStore.layer.pipe(Layer.provideMerge(database));
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const held = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const writer = yield* sql
+ .withTransaction(
+ sql`SELECT 1`.pipe(
+ Effect.andThen(Deferred.succeed(held, undefined)),
+ Effect.andThen(Deferred.await(release)),
+ ),
+ )
+ .pipe(Effect.forkChild);
+ yield* Deferred.await(held);
+ const snapshot = yield* projections.getShellSnapshot();
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(writer);
+ assert.deepEqual(snapshot.threads, []);
+ }).pipe(Effect.provide(projectionLayer));
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+);
diff --git a/apps/server/src/orchestration-v2/ProjectStore.ts b/apps/server/src/orchestration-v2/ProjectStore.ts
index 03206781e0f..aa7b27de604 100644
--- a/apps/server/src/orchestration-v2/ProjectStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectStore.ts
@@ -9,6 +9,7 @@ import {
ThreadEnvMode,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -191,6 +192,7 @@ export const make = Effect.gen(function* () {
const get: ProjectStoreV2["Service"]["get"] = (projectId, options) =>
selectRows({ projectId, includeDeleted: options?.includeDeleted === true }).pipe(
+ NodeSqliteClient.readOnly,
Effect.map((rows) => Option.fromUndefinedOr(rows[0])),
mapError("get"),
);
@@ -199,12 +201,13 @@ export const make = Effect.gen(function* () {
selectRows({
...(options?.projectIds === undefined ? {} : { projectIds: options.projectIds }),
includeDeleted: options?.includeDeleted === true,
- }).pipe(mapError("list"));
+ }).pipe(NodeSqliteClient.readOnly, mapError("list"));
const findActiveByWorkspaceRoot: ProjectStoreV2["Service"]["findActiveByWorkspaceRoot"] = (
workspaceRoot,
) =>
selectRows({ workspaceRoot, includeDeleted: false }).pipe(
+ NodeSqliteClient.readOnly,
Effect.map((rows) => Option.fromUndefinedOr(rows[0])),
mapError("findActiveByWorkspaceRoot"),
);
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 92ef73ebf1b..4f08378db52 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -1,6 +1,7 @@
import { applyThreadPullRequestLinkUpdate } from "@t3tools/shared/threadPullRequests";
import { projectTurnItemForWire } from "./WireProjection.ts";
import * as Stream from "effect/Stream";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import { makeThreadFind, findProjectedThreadItems } from "./ThreadFind.ts";
import type {
OrchestrationV2SearchThreadInput,
@@ -6511,47 +6512,55 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
)
.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
+ const readOnReader =
+ <Args extends ReadonlyArray<unknown>, A, E, R>(
+ method: (...args: Args) => Effect.Effect<A, E, R>,
+ ) =>
+ (...args: Args): Effect.Effect<A, E, R> =>
+ method(...args).pipe(NodeSqliteClient.readOnly);
+
return {
apply,
- getShellSnapshot,
- readShellSnapshot,
- getThreadShell,
- getThread,
- getSettlementCandidates,
- getThreadsWithPullRequests,
- getThreadWorktreePaths,
+ getShellSnapshot: readOnReader(getShellSnapshot),
+ readShellSnapshot: readOnReader(readShellSnapshot),
+ getThreadShell: readOnReader(getThreadShell),
+ getThread: readOnReader(getThread),
+ getSettlementCandidates: readOnReader(getSettlementCandidates),
+ getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests),
+ getThreadWorktreePaths: readOnReader(getThreadWorktreePaths),
getThreadProjection,
- getTurnStartContext,
- getTurnStartHistory,
- getRuntimeRecoveryProjection,
- getRunningTurnContext,
- getThreadProviderContext,
- getRuntimeResponseContext,
- getCheckpointContext,
- getCheckpointCaptureContext,
- getCheckpointRollbackContext,
- getRunMessage,
- canStartQueuedRun,
- getPendingNativeUserInputs,
- hasUnpairedRunInterruptRequest,
- isNodeStored,
- getMessageCount,
- getNextTurnItemOrdinal,
- getTurnItem,
- getThreadRecords,
- getRuntimeRequest,
- getPlan,
- getProviderControlContext,
- getLimitRecoveryCandidates,
- getRecoveryThreadIds,
- getUnreadableThreadIds,
- getThreadSnapshot,
- getThreadSnapshotWindow,
- getTimelinePage,
- getThreadHistoryPage,
- searchThread,
+ getTurnStartContext: readOnReader(getTurnStartContext),
+ getTurnStartHistory: readOnReader(getTurnStartHistory),
+ getRuntimeRecoveryProjection: readOnReader(getRuntimeRecoveryProjection),
+ getRunningTurnContext: readOnReader(getRunningTurnContext),
+ getThreadProviderContext: readOnReader(getThreadProviderContext),
+ getRuntimeResponseContext: readOnReader(getRuntimeResponseContext),
+ getCheckpointContext: readOnReader(getCheckpointContext),
+ getCheckpointCaptureContext: readOnReader(getCheckpointCaptureContext),
+ getCheckpointRollbackContext: readOnReader(getCheckpointRollbackContext),
+ getRunMessage: readOnReader(getRunMessage),
+ canStartQueuedRun: readOnReader(canStartQueuedRun),
+ getPendingNativeUserInputs: readOnReader(getPendingNativeUserInputs),
+ hasUnpairedRunInterruptRequest: readOnReader(hasUnpairedRunInterruptRequest),
+ isNodeStored: readOnReader(isNodeStored),
+ getMessageCount: readOnReader(getMessageCount),
+ getNextTurnItemOrdinal: readOnReader(getNextTurnItemOrdinal),
+ getTurnItem: readOnReader(getTurnItem),
+ getThreadRecords: (threadId, fields, filter) =>
+ getThreadRecords(threadId, fields, filter).pipe(NodeSqliteClient.readOnly),
+ getRuntimeRequest: readOnReader(getRuntimeRequest),
+ getPlan: readOnReader(getPlan),
+ getProviderControlContext: readOnReader(getProviderControlContext),
+ getLimitRecoveryCandidates: readOnReader(getLimitRecoveryCandidates),
+ getRecoveryThreadIds: readOnReader(getRecoveryThreadIds),
+ getUnreadableThreadIds: readOnReader(getUnreadableThreadIds),
+ getThreadSnapshot: readOnReader(getThreadSnapshot),
+ getThreadSnapshotWindow: readOnReader(getThreadSnapshotWindow),
+ getTimelinePage: readOnReader(getTimelinePage),
+ getThreadHistoryPage: readOnReader(getThreadHistoryPage),
+ searchThread: readOnReader(searchThread),
searchThreadStream,
- getThreadAttachmentIds,
+ getThreadAttachmentIds: readOnReader(getThreadAttachmentIds),
} satisfies ProjectionStoreV2Shape;
}),
);
diff --git a/apps/server/src/orchestration-v2/ThreadFind.ts b/apps/server/src/orchestration-v2/ThreadFind.ts
index 288737471e0..2a663ae6d08 100644
--- a/apps/server/src/orchestration-v2/ThreadFind.ts
+++ b/apps/server/src/orchestration-v2/ThreadFind.ts
@@ -14,6 +14,7 @@ import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as SqlClient from "effect/sql/SqlClient";
import {
ProjectionStoreReadError,
@@ -345,7 +346,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
}
return { payloads, cwd, sequence, cacheKey, sourceThreadIds };
},
- sql.withTransaction,
+ (effect) => sql.withTransaction(effect).pipe(NodeSqliteClient.readOnly),
(effect, input) =>
effect.pipe(
Effect.mapError((cause) =>
diff --git a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
index 9f5b3ab38c9..610be4c1ba3 100644
--- a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
+++ b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
@@ -22,6 +22,7 @@ import {
TurnItemId,
} from "@t3tools/contracts";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -359,7 +360,7 @@ const make = Effect.gen(function* () {
WHERE thread_id = ${threadId}
AND role IN ('user', 'assistant')
ORDER BY created_at ASC, message_id ASC
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const listShellMessages = Effect.fn("LegacyV1ThreadImporter.listShellMessages")(function* (
threadId: ThreadId,
@@ -669,6 +670,7 @@ const make = Effect.gen(function* () {
WHERE legacy_import.transcript_imported_at IS NULL
)
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.map((rows) => rows[0]?.count ?? 0),
Effect.mapError(
(cause) => new LegacyV1ThreadImportError({ operation: "inspect pending", cause }),
@@ -690,7 +692,7 @@ const make = Effect.gen(function* () {
FROM orchestration_v2_legacy_imports
WHERE thread_id = ${threadId}
LIMIT 1
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const imported = imports[0];
if (imported === undefined || imported.transcript_imported_at !== null) {
if (imported !== undefined) {
@@ -708,7 +710,7 @@ const make = Effect.gen(function* () {
AND aggregate_kind = 'thread'
AND stream_id = ${threadId}
AND event_id LIKE ${`${IMPORT_EVENT_PREFIX}:message:%`}
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const existing = new Set(existingRows.map((row) => row.event_id));
const missing = messages.filter(
(message) => !existing.has(`${IMPORT_EVENT_PREFIX}:message:${message.message_id}`),
@@ -772,7 +774,7 @@ const make = Effect.gen(function* () {
FROM orchestration_v2_legacy_imports
WHERE transcript_imported_at IS NULL
ORDER BY shell_imported_at ASC, thread_id ASC
- `;
+ `.pipe(NodeSqliteClient.readOnly);
let importedThreadCount = 0;
let importedMessageCount = 0;
for (const row of rows) {
diff --git a/apps/server/src/persistence/AuthPairingLinks.ts b/apps/server/src/persistence/AuthPairingLinks.ts
index 623fc8159db..4a8bc699b7d 100644
--- a/apps/server/src/persistence/AuthPairingLinks.ts
+++ b/apps/server/src/persistence/AuthPairingLinks.ts
@@ -1,4 +1,5 @@
import * as Context from "effect/Context";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -294,6 +295,7 @@ export const make = Effect.gen(function* () {
const listActive: AuthPairingLinkRepository["Service"]["listActive"] = (input) =>
listActivePairingLinkRows(input).pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthPairingLinkRepository.listActive:query",
@@ -329,6 +331,7 @@ export const make = Effect.gen(function* () {
const getByCredential: AuthPairingLinkRepository["Service"]["getByCredential"] = (input) =>
getPairingLinkRowByCredential(input).pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthPairingLinkRepository.getByCredential:query",
diff --git a/apps/server/src/persistence/AuthSessions.ts b/apps/server/src/persistence/AuthSessions.ts
index 0cb64a8e647..687c2c019b9 100644
--- a/apps/server/src/persistence/AuthSessions.ts
+++ b/apps/server/src/persistence/AuthSessions.ts
@@ -1,4 +1,5 @@
import * as Context from "effect/Context";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -416,6 +417,7 @@ export const make = Effect.gen(function* () {
const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
getSessionRowById(input).pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthSessionRepository.getById:query",
@@ -443,6 +445,7 @@ export const make = Effect.gen(function* () {
const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
listActiveSessionRows(input).pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthSessionRepository.listActive:query",
diff --git a/apps/server/src/persistence/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/OrchestrationCommandReceipts.ts
index a64e008cf91..4a39061a00c 100644
--- a/apps/server/src/persistence/OrchestrationCommandReceipts.ts
+++ b/apps/server/src/persistence/OrchestrationCommandReceipts.ts
@@ -1,4 +1,5 @@
import { CommandId, IsoDateTime, NonNegativeInt, ProjectId, ThreadId } from "@t3tools/contracts";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as SqlClient from "effect/sql/SqlClient";
import * as SqlSchema from "effect/sql/SqlSchema";
import * as Context from "effect/Context";
@@ -149,6 +150,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {
input,
) =>
findReceiptByCommandId(input).pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
toPersistenceSqlError("OrchestrationCommandReceiptRepository.getByCommandId:query"),
),
diff --git a/apps/server/src/persistence/OrchestrationEventStore.ts b/apps/server/src/persistence/OrchestrationEventStore.ts
index 394f627a4e4..265bb6ad0fb 100644
--- a/apps/server/src/persistence/OrchestrationEventStore.ts
+++ b/apps/server/src/persistence/OrchestrationEventStore.ts
@@ -15,6 +15,7 @@ import {
type OrchestrationV2DomainEvent,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as SqlClient from "effect/sql/SqlClient";
import * as SqlSchema from "effect/sql/SqlSchema";
import * as Effect from "effect/Effect";
@@ -441,7 +442,7 @@ const makeEventStore = Effect.gen(function* () {
])}
ORDER BY sequence ASC
LIMIT ${input.limit}
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const appendAgentEvents: OrchestrationEventStore["Service"]["appendAgentEvents"] = (input) =>
Effect.forEach(
@@ -617,6 +618,7 @@ const makeEventStore = Effect.gen(function* () {
LIMIT ${Math.max(0, Math.floor(input.maxEvents)) + 1}
)
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getAgentReplayStats:query")),
Effect.map((rows) => ({
eventCount: rows[0]?.eventCount ?? 0,
@@ -638,6 +640,7 @@ const makeEventStore = Effect.gen(function* () {
OR (application_event_version = 2 AND aggregate_kind = 'thread')
)
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getReplayStats:query")),
Effect.map((rows) => ({
eventCount: rows[0]?.eventCount ?? 0,
@@ -660,6 +663,7 @@ const makeEventStore = Effect.gen(function* () {
AND aggregate_kind = 'thread'
${threadId === undefined ? sql`` : sql`AND stream_id = ${threadId}`}
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.map((rows) => rows[0]?.sequence ?? 0),
Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.latestAgentSequence:query")),
);
@@ -671,6 +675,7 @@ const makeEventStore = Effect.gen(function* () {
WHERE aggregate_kind = 'project'
OR (application_event_version = 2 AND aggregate_kind = 'thread')
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.map((rows) => rows[0]?.sequence ?? 0),
Effect.mapError(
toPersistenceSqlError("OrchestrationEventStore.latestApplicationSequence:query"),
diff --git a/apps/server/src/persistence/ProviderSessionRuntime.ts b/apps/server/src/persistence/ProviderSessionRuntime.ts
index d500d2ba714..861be3c0174 100644
--- a/apps/server/src/persistence/ProviderSessionRuntime.ts
+++ b/apps/server/src/persistence/ProviderSessionRuntime.ts
@@ -1,4 +1,5 @@
import * as Arr from "effect/Array";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -357,6 +358,7 @@ export const make = Effect.gen(function* () {
const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
getRuntimeRowByThreadId(input).pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProviderSessionRuntimeRepository.getByThreadId:query",
@@ -384,6 +386,7 @@ export const make = Effect.gen(function* () {
const list: ProviderSessionRuntimeRepository["Service"]["list"] = (options) =>
listRuntimeRows({ excludeStopped: options?.excludeStopped === true }).pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProviderSessionRuntimeRepository.list:query",
diff --git a/apps/server/src/persistence/PullRequestFilesViewed.ts b/apps/server/src/persistence/PullRequestFilesViewed.ts
index ca56912e29d..99f79e4936e 100644
--- a/apps/server/src/persistence/PullRequestFilesViewed.ts
+++ b/apps/server/src/persistence/PullRequestFilesViewed.ts
@@ -1,4 +1,5 @@
import * as Context from "effect/Context";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -90,6 +91,7 @@ const make = Effect.gen(function* () {
return PullRequestFilesViewedRepository.of({
list: (input) =>
listRows(input).pipe(
+ NodeSqliteClient.readOnly,
Effect.map((rows) => ({
files: rows.slice(0, MAX_FILES_VIEWED_ROWS),
truncated: rows.length > MAX_FILES_VIEWED_ROWS,
diff --git a/apps/server/src/persistence/PullRequestReviewGuides.ts b/apps/server/src/persistence/PullRequestReviewGuides.ts
index 31c3651f912..6dd2780eceb 100644
--- a/apps/server/src/persistence/PullRequestReviewGuides.ts
+++ b/apps/server/src/persistence/PullRequestReviewGuides.ts
@@ -1,4 +1,5 @@
import * as Context from "effect/Context";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -52,6 +53,7 @@ const make = Effect.gen(function* () {
return PullRequestReviewGuideRepository.of({
get: (key) =>
findGuide(key).pipe(
+ NodeSqliteClient.readOnly,
Effect.map(Option.map((row) => row.guide)),
Effect.mapError((cause) =>
Schema.isSchemaError(cause)
diff --git a/apps/server/src/pullRequest/linkedThreads.ts b/apps/server/src/pullRequest/linkedThreads.ts
index b250ef4a6c6..fa51017ebcd 100644
--- a/apps/server/src/pullRequest/linkedThreads.ts
+++ b/apps/server/src/pullRequest/linkedThreads.ts
@@ -8,6 +8,7 @@ import {
type ThreadPullRequestKey,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
@@ -39,7 +40,7 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre
AND json_extract(link.value, '$.source') != 'stack-dismissed'
AND t.deleted_at IS NULL
ORDER BY "updatedAt" DESC, id ASC
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const threads = rows
.filter((row) => threadPullRequestKeysEqual(row, key))
.map(({ id, projectId, title, archivedAt }) => ({ id, projectId, title, archivedAt }));
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
index 374d6b38027..a4714e3ae41 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
@@ -29,6 +29,7 @@ import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Exit from "effect/Exit";
import * as Duration from "effect/Duration";
import * as Metric from "effect/Metric";
@@ -370,7 +371,7 @@ export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(funct
WHERE enabled = 1 AND next_run_at IS NOT NULL
AND next_run_at <= ${iso(now)} AND last_run_status <> 'running'
ORDER BY next_run_at ASC, task_id ASC
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const tasks: ScheduledTask[] = [];
for (const row of rows) {
const decoded = yield* Effect.result(decodeRow(row));
@@ -431,7 +432,8 @@ export const layer = Layer.effect(
const changesPubSub = yield* PubSub.sliding<void>(1);
const notifyChanged = PubSub.publish(changesPubSub, undefined).pipe(Effect.asVoid);
- const selectAllRows = () => sql<ScheduledTaskRow>`
+ const selectAllRows = () =>
+ sql<ScheduledTaskRow>`
SELECT
task_id,
title,
@@ -459,7 +461,7 @@ export const layer = Layer.effect(
-- Not updated_at: toggles, runs and edits rewrite it, and clients render
-- this order as-is, so rows would move under the pointer.
ORDER BY created_at DESC, task_id ASC
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () {
const rows = yield* selectAllRows();
@@ -467,7 +469,8 @@ export const layer = Layer.effect(
return yield* Effect.forEach(rows, (row) => decodeRow(row, origin), { concurrency: 1 });
});
- const getRows = (id: ScheduledTaskId) => sql<ScheduledTaskRow>`
+ const getRows = (id: ScheduledTaskId) =>
+ sql<ScheduledTaskRow>`
SELECT
task_id,
title,
@@ -493,7 +496,7 @@ export const layer = Layer.effect(
webhook_secret
FROM scheduled_tasks
WHERE task_id = ${id}
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const findTask = Effect.fn("ScheduledTaskService.findTask")(function* (id: ScheduledTaskId) {
const rows = yield* getRows(id).pipe(
@@ -768,8 +771,9 @@ export const layer = Layer.effect(
}
if (
webhook !== undefined &&
- (yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId} AND state = 'completed'`)
- .length > 0
+ (yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId} AND state = 'completed'`.pipe(
+ NodeSqliteClient.readOnly,
+ )).length > 0
)
return { task: { ...active, lastRunStatus: "succeeded" as const }, threadId: null };
const parsedNextRunAt =
@@ -1351,6 +1355,7 @@ export const layer = Layer.effect(
FROM scheduled_task_webhook_deliveries d WHERE task_id = ${input.id}
ORDER BY received_at DESC, rowid DESC
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.map((rows) => ({
deliveries: rows
.filter(
@@ -1371,6 +1376,7 @@ export const layer = Layer.effect(
WHERE p.delivery_id = d.delivery_id AND p.state IN ('pending', 'dispatching')) AS pending_window
FROM scheduled_task_webhook_deliveries d WHERE task_id = ${input.id} AND delivery_id = ${input.deliveryId}
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError((cause) =>
taskError("Could not load webhook delivery.", { taskId: input.id, cause }),
),
@@ -2065,7 +2071,7 @@ export const layer = Layer.effect(
yield* sql`UPDATE scheduled_task_webhook_pending SET state = 'dispatching' WHERE state = 'pending' AND due_at <= ${now}`;
const tasks = yield* sql<{ task_id: ScheduledTaskId }>`
SELECT DISTINCT task_id FROM scheduled_task_webhook_pending WHERE state IN ('dispatching', 'running', 'completed', 'failed')
- `;
+ `.pipe(NodeSqliteClient.readOnly);
yield* Effect.forEach(
tasks,
({ task_id: taskId }) =>
@@ -2089,7 +2095,7 @@ export const layer = Layer.effect(
}>`
SELECT delivery_id, task_json, request_json, state FROM scheduled_task_webhook_pending
WHERE task_id = ${taskId} AND state IN ('dispatching', 'running', 'completed', 'failed') ORDER BY due_at, rowid LIMIT 1
- `;
+ `.pipe(NodeSqliteClient.readOnly);
if (entry === undefined) return;
const remove = sql`DELETE FROM scheduled_task_webhook_pending WHERE delivery_id = ${entry.delivery_id}`;
if (entry.state === "completed" || entry.state === "failed") {
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index 65c114c75ca..47bbefa509e 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -25,6 +25,7 @@ import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Equal from "effect/Equal";
import * as Effect from "effect/Effect";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -711,6 +712,7 @@ const make = Effect.gen(function* () {
FROM provider_session_runtime
WHERE provider_name IN ('cursor', 'grok', 'opencode')
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
(cause) =>
new ServerSettingsError({
@@ -734,6 +736,7 @@ const make = Effect.gen(function* () {
FROM projection_projects
WHERE deleted_at IS NULL
`.pipe(
+ NodeSqliteClient.readOnly,
Effect.mapError(
(cause) =>
new ServerSettingsError({
diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts
index a196321e380..1a0a19682e4 100644
--- a/apps/server/src/storageCleanup.ts
+++ b/apps/server/src/storageCleanup.ts
@@ -737,7 +737,7 @@ const make = Effect.gen(function* () {
FROM orchestration_v2_projection_threads t
JOIN projection_projects p ON p.project_id = t.project_id
WHERE t.deleted_at IS NOT NULL
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
decodeCleanupThread(row.payload_json).pipe(
Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
@@ -938,7 +938,7 @@ const make = Effect.gen(function* () {
const pendingCleanup = yield* sql`
SELECT 1 FROM orchestration_v2_effect_outbox
WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
- `;
+ `.pipe(NodeSqliteClient.readOnly);
if (pendingCleanup.length > 0) return "thread deletion is still pending";
} else {
const latestShells = yield* Effect.forEach(latest, (entry) =>
@@ -970,7 +970,7 @@ const make = Effect.gen(function* () {
const sessionRows = yield* sql<{ payload_json: string }>`
SELECT payload_json FROM orchestration_v2_projection_provider_sessions
WHERE status != 'stopped'
- `;
+ `.pipe(NodeSqliteClient.readOnly);
const sessions = yield* Effect.forEach(sessionRows, (row) =>
decodeCleanupSession(row.payload_json),
);
diff --git a/apps/server/src/workspace/KnownWorkspaces.ts b/apps/server/src/workspace/KnownWorkspaces.ts
index d98939415d9..20df3033102 100644
--- a/apps/server/src/workspace/KnownWorkspaces.ts
+++ b/apps/server/src/workspace/KnownWorkspaces.ts
@@ -8,6 +8,7 @@
* @module KnownWorkspaces
*/
import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -105,7 +106,10 @@ export const make = Effect.gen(function* () {
project_id AS "projectId"
FROM orchestration_v2_projection_threads
WHERE deleted_at IS NULL AND json_extract(payload_json, '$.worktreePath') IS NOT NULL
- `.pipe(Effect.orElseSucceed(() => []));
+ `.pipe(
+ NodeSqliteClient.readOnly,
+ Effect.orElseSucceed(() => []),
+ );
const projectWorktrees = new Map<string, ReadonlyArray<string>>();
const isProjectWorktree = Effect.fnUntraced(function* (
projectId: string,
diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts
index c29652ae847..1df72d51427 100644
--- a/packages/shared/src/nodeSqliteClient.test.ts
+++ b/packages/shared/src/nodeSqliteClient.test.ts
@@ -8,6 +8,8 @@ import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as SqlClient from "effect/sql/SqlClient";
+import * as Statement from "effect/sql/Statement";
+import type * as Tracer from "effect/Tracer";
import { vi } from "vite-plus/test";
import * as SqliteClient from "./nodeSqliteClient.ts";
@@ -64,6 +66,41 @@ const countEntries = (sql: SqlClient.SqlClient) =>
const layer = it.layer(SqliteClient.layer({ filename: ":memory:" }));
layer("NodeSqliteClient", (it) => {
+ it.effect("records the writer connection owner on a waiting query", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const held = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const holder = yield* sql
+ .withTransaction(
+ sql`SELECT 1`.pipe(
+ Effect.andThen(Deferred.succeed(held, undefined)),
+ Effect.andThen(Deferred.await(release)),
+ ),
+ )
+ .pipe(Effect.withSpan("test.writerHolder"), Effect.forkChild);
+ yield* Deferred.await(held);
+
+ const waitingSpan = yield* Deferred.make<Tracer.Span>();
+ const observeWaiter: Statement.Transformer = (statement, _sql, _fiber, span) =>
+ Deferred.succeed(waitingSpan, span).pipe(Effect.as(statement));
+ const waiter = yield* sql`SELECT 1`.pipe(
+ Effect.provideService(Statement.CurrentTransformer, observeWaiter),
+ Effect.provideService(Statement.SpanPropagationEnabled, true),
+ (effect) => Effect.forkChild(effect, { startImmediately: true }),
+ );
+ const span = yield* Deferred.await(waitingSpan);
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(holder);
+ yield* Fiber.join(waiter);
+
+ assert.equal(span.attributes.get("db.lock_owner_at_start.name"), "test.writerHolder");
+ assert.typeOf(span.attributes.get("db.lock_owner_at_start.fiber_id"), "number");
+ assert.typeOf(span.attributes.get("db.lock_owner_at_start.trace_id"), "string");
+ assert.typeOf(span.attributes.get("db.lock_owner_at_start.span_id"), "string");
+ }),
+ );
+
it.effect("retries preparing a query after the missing schema becomes available", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts
index 03283a614ee..59ef57e59fe 100644
--- a/packages/shared/src/nodeSqliteClient.ts
+++ b/packages/shared/src/nodeSqliteClient.ts
@@ -70,15 +70,53 @@ interface Acquired {
readonly lockWaitMs: number;
}
-const annotateAcquired = (fiber: Fiber.Fiber<unknown, unknown>, acquired: Acquired | undefined) => {
+interface ConnectionOwner {
+ readonly fiberId: number;
+ readonly name: string;
+ readonly traceId?: string;
+ readonly spanId?: string;
+}
+
+const connectionOwner = (fiber: Fiber.Fiber<unknown, unknown>): ConnectionOwner => {
+ const current = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
+ if (current?._tag !== "Span") return { fiberId: fiber.id, name: "untraced" };
+ let span: Tracer.Span = current;
+ while (span.name === "sqlite" || span.name === "sql.transaction") {
+ const parent: Tracer.AnySpan | undefined = Option.getOrUndefined(span.parent);
+ if (parent?._tag !== "Span") break;
+ span = parent;
+ }
+ return { fiberId: fiber.id, name: span.name, traceId: span.traceId, spanId: span.spanId };
+};
+
+const annotateAcquired = (
+ fiber: Fiber.Fiber<unknown, unknown>,
+ acquired: Acquired | undefined,
+ ownerAtWaitStart?: ConnectionOwner,
+) => {
const span = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
if (span?._tag !== "Span" || acquired === undefined) return;
span.attribute("db.connection", acquired.connection);
span.attribute("db.lock_wait_ms", acquired.lockWaitMs);
+ if (ownerAtWaitStart !== undefined) {
+ span.attribute("db.lock_owner_at_start.fiber_id", ownerAtWaitStart.fiberId);
+ span.attribute("db.lock_owner_at_start.name", ownerAtWaitStart.name);
+ if (ownerAtWaitStart.traceId !== undefined) {
+ span.attribute("db.lock_owner_at_start.trace_id", ownerAtWaitStart.traceId);
+ }
+ if (ownerAtWaitStart.spanId !== undefined) {
+ span.attribute("db.lock_owner_at_start.span_id", ownerAtWaitStart.spanId);
+ }
+ }
};
const TransactionAcquire = Context.Reference<
- { acquired?: Acquired; restore: typeof Effect.interruptible | undefined } | undefined
+ | {
+ acquired?: Acquired;
+ ownerAtWaitStart: ConnectionOwner | undefined;
+ restore: typeof Effect.interruptible | undefined;
+ }
+ | undefined
>("@t3tools/shared/nodeSqliteClient/TransactionAcquire", { defaultValue: () => undefined });
export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
@@ -1070,6 +1108,7 @@ const make = Effect.fn("makeWithDatabase")(function* (
const readerSemaphore = yield* Semaphore.make(1);
const writer = { name: "writer" as const, lock: semaphore, connection };
+ let activeWriter: ConnectionOwner | undefined;
const route = Effect.withFiber((fiber) =>
acquireReader !== undefined && Context.get(fiber.context, ReadOnly)
? Effect.map(acquireReader, (readerConnection) =>
@@ -1096,19 +1135,30 @@ const make = Effect.fn("makeWithDatabase")(function* (
Effect.withFiber((fiber) => {
const clock = fiber.getRef(Clock.Clock);
const start = clock.monotonicTimeNanosUnsafe();
+ const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
+ const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
const useConnection = Effect.suspend(() => {
+ if (target.name === "writer") activeWriter = owner;
if (
fiber.getRef(References.TracerEnabled) &&
fiber.getRef(Statement.SpanPropagationEnabled)
) {
- annotateAcquired(fiber, acquired(target, clock, start));
+ annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
}
return use(target.connection);
});
+ const useOwnedConnection =
+ target.name === "writer"
+ ? Effect.onExit(useConnection, () =>
+ Effect.sync(() => {
+ if (activeWriter === owner) activeWriter = undefined;
+ }),
+ )
+ : useConnection;
if (!options.checkpointWorker || target.name !== "writer") {
- return target.lock.withPermits(1)(useConnection);
+ return target.lock.withPermits(1)(useOwnedConnection);
}
- const writerUse = Effect.onExit(useConnection, (exit) =>
+ const writerUse = Effect.onExit(useOwnedConnection, (exit) =>
Effect.sync(() => {
writerBorrowsSinceYield = Exit.hasInterrupts(exit)
? 0
@@ -1142,9 +1192,20 @@ const make = Effect.fn("makeWithDatabase")(function* (
const clock = fiber.getRef(Clock.Clock);
const start = clock.monotonicTimeNanosUnsafe();
const pending = fiber.getRef(TransactionAcquire);
+ const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
+ const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {
- if (pending !== undefined) pending.acquired = acquired(target, clock, start);
- return Scope.addFinalizer(scope, target.lock.release(1));
+ if (target.name === "writer") activeWriter = owner;
+ if (pending !== undefined) {
+ pending.acquired = acquired(target, clock, start);
+ pending.ownerAtWaitStart = ownerAtWaitStart;
+ }
+ return Scope.addFinalizer(
+ scope,
+ Effect.sync(() => {
+ if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
+ }).pipe(Effect.andThen(target.lock.release(1))),
+ );
});
return Effect.as(
// A scheduler yield after taking the permit must not precede its release finalizer.
@@ -1174,11 +1235,16 @@ const make = Effect.fn("makeWithDatabase")(function* (
withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.uninterruptibleMask((restore) => {
// SqlClient masks setup; acquisition must preserve the caller's interruptibility.
- const pending: { acquired?: Acquired; restore: typeof Effect.interruptible | undefined } = {
+ const pending: {
+ acquired?: Acquired;
+ ownerAtWaitStart: ConnectionOwner | undefined;
+ restore: typeof Effect.interruptible | undefined;
+ } = {
+ ownerAtWaitStart: undefined,
restore,
};
const body = Effect.withFiber<A, E, R>((fiber) => {
- annotateAcquired(fiber, pending.acquired);
+ annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
pending.restore = undefined;
return effect;
});