Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(shared): make message seq reservation atomic (#550)

Gustavo Yeb24195b5ae9f
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index a7bc12140..99d9384c1 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -15,60 +15,46 @@ import type { Database } from "../../index";
import { createLogger } from "../../../logger";
import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
-/**
- * Atomically claim the next seq value for a channel. A single top-level UPSERT
- * — D1's single-writer serialization makes this race-free for uniqueness on
- * its own, no CTE/transaction needed (see plans/community-agent-cli-bridge.md
- * design §3 for why the CTE-fusion approach is not valid SQLite and was
- * rejected).
- *
- * Unconditional claim: always advances the counter, no matter what the
- * caller's stale view of the world was. Callers with an `expectedSeq` to
- * verify against (the agent-send race, plans/fix-agent-send-race-condition.md)
- * must use the CAS sibling `claimNextSeqIfAligned` below instead — this
- * function alone cannot detect a stale-snapshot race, only guarantee
- * uniqueness.
- */
-async function claimNextSeq(db: Database, channelId: string): Promise<number> {
+// The canonical sender admits bursts of up to 30 requests per actor. Keep the
+// ordinary-send retry budget above a full admitted collision wave so a hot
+// channel drains to distinct seqs instead of surfacing a false 500, while
+// still bounding pathological contention. Aligned sends remain single-shot:
+// their first seq conflict returns null below.
+const MAX_SEQ_CLAIM_ATTEMPTS = 64;
+
+async function getIssuedSeq(db: Database, channelId: string): Promise<number> {
const rows = await db
- .insert(communityMessageSeq)
- .values({ channelId, nextSeq: 1 })
- .onConflictDoUpdate({
- target: communityMessageSeq.channelId,
- set: { nextSeq: sql`${communityMessageSeq.nextSeq} + 1` },
- })
- .returning({ nextSeq: communityMessageSeq.nextSeq });
- return rows[0]!.nextSeq;
+ .select({ nextSeq: communityMessageSeq.nextSeq })
+ .from(communityMessageSeq)
+ .where(eq(communityMessageSeq.channelId, channelId));
+ return rows[0]?.nextSeq ?? 0;
}
-/**
- * Compare-and-swap claim: only advances `next_seq` if it currently equals
- * `expectedSeq` — the value the caller observed during its own alignment
- * check. Returns the newly claimed seq on success, or `null` if another
- * writer already advanced the counter (the caller lost the race and MUST
- * treat this as a no-op: no message row, no side effects of any kind).
- *
- * Safe for the very first message in a scope too: when no row exists yet,
- * the INSERT branch fires unconditionally (no conflict to gate), but that
- * branch can only ever be reached by the single first-ever writer for that
- * scope_key — every subsequent racer hits the conflict branch and is
- * correctly gated by `setWhere`.
- */
-async function claimNextSeqIfAligned(
- db: Database,
- channelId: string,
- expectedSeq: number
-): Promise<number | null> {
- const rows = await db
- .insert(communityMessageSeq)
- .values({ channelId, nextSeq: 1 })
- .onConflictDoUpdate({
- target: communityMessageSeq.channelId,
- set: { nextSeq: sql`${communityMessageSeq.nextSeq} + 1` },
- setWhere: sql`${communityMessageSeq.nextSeq} = ${expectedSeq}`,
- })
- .returning({ nextSeq: communityMessageSeq.nextSeq });
- return rows[0]?.nextSeq ?? null;
+function errorChainMessages(error: unknown): string[] {
+ const messages: string[] = [];
+ const visited = new Set<unknown>();
+ let current = error;
+ while (current && !visited.has(current)) {
+ visited.add(current);
+ if (current instanceof Error) {
+ messages.push(current.message);
+ current = current.cause;
+ continue;
+ }
+ messages.push(String(current));
+ break;
+ }
+ return messages;
+}
+
+function isMessageSeqConflict(error: unknown): boolean {
+ return errorChainMessages(error).some(
+ (message) =>
+ /unique constraint failed/i.test(message) &&
+ ((message.includes("community_message.channel_id") &&
+ message.includes("community_message.seq")) ||
+ message.includes("uq_community_message_channel_seq"))
+ );
}
const DEFAULT_LIMIT = 50;
@@ -146,8 +132,8 @@ export type CreateMessageData = {
* insert (zero new round-trip). The bot-send routes use this to bump the
* per-day sent activity rollup for the heatmap; human sends pass nothing. The
* statements run only if the message row is written (they share the batch's
- * all-or-nothing fate — and if the CAS seq claim above loses, the batch never
- * runs, so a lost race correctly skips them). This function stays
+ * all-or-nothing fate — a lost CAS rolls the whole batch back, so a lost race
+ * correctly skips them). This function stays
* identity-agnostic: the CALLER decides what to append, not `createMessage`.
*/
extraStatements?: unknown[];
@@ -160,8 +146,8 @@ export type CreateMessageData = {
* send, bot provisioning, and friend request, which never opt into the CAS
* guard. Only
* callers that explicitly pass a numeric `expectedSeq` (the agent-send race
- * fix) see the nullable return — `null` means "lost the race, no row was
- * written, treat as a complete no-op".
+ * fix) see the nullable return — `null` means "lost the race, the atomic batch
+ * rolled back, treat as a complete no-op".
*/
export async function createMessage(
db: Database,
@@ -175,51 +161,46 @@ export async function createMessage(
db: Database,
data: CreateMessageData & { expectedSeq?: number }
) {
- // Step 0: atomically claim this scope's next seq (own top-level statement —
- // see design §3 for why this can't be fused into the INSERT below via a
- // CTE). Accepted trade-off: if the INSERT below fails after this succeeds,
- // the counter has a harmless gap — no duplicate seq is ever possible since
- // this claim is independently atomic under D1's single-writer serialization.
- // Do NOT wrap these two statements in a transaction to "fix" this — D1
- // doesn't support one that could express it. Kept outside the batch below
- // because D1 `batch()` cannot feed one statement's `.returning()` into a
- // later statement's values.
- //
- // When `expectedSeq` is present (plans/fix-agent-send-race-condition.md),
- // the claim is a compare-and-swap gated on the caller's own alignment-check
- // snapshot: `claimNextSeqIfAligned` returns `null` with ZERO rows written
- // anywhere if another writer already advanced the counter past what this
- // caller saw — return `null` immediately, before any insert/update below.
- const seq =
- data.expectedSeq !== undefined
- ? await claimNextSeqIfAligned(db, data.channelId, data.expectedSeq)
- : await claimNextSeq(db, data.channelId);
- if (seq === null) return null;
- return insertMessageRow(db, data, seq);
+ const aligned = data.expectedSeq !== undefined;
+ let expectedSeq = data.expectedSeq ?? await getIssuedSeq(db, data.channelId);
+
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await insertMessageRow(db, data, expectedSeq);
+ } catch (error) {
+ if (!isMessageSeqConflict(error)) throw error;
+ if (aligned) return null;
+ if (attempt === MAX_SEQ_CLAIM_ATTEMPTS - 1) throw error;
+ expectedSeq = await getIssuedSeq(db, data.channelId);
+ }
+ }
}
-// Step 1+: everything after the seq claim above — message insert,
-// channel/DM `lastMessageAt` bump, and the applicable author read marker. Split out of
-// `createMessage` purely so the two overload signatures above can reference
-// its return type instead of duplicating a hand-written row type; behavior
-// is identical to having this inlined.
-async function insertMessageRow(db: Database, data: CreateMessageData, seq: number) {
+async function insertMessageRow(db: Database, data: CreateMessageData, expectedSeq: number) {
+ const seq = expectedSeq + 1;
const now = new Date().toISOString();
const messageId = data.id ?? nanoid();
const authorIsHuman = data.authorKind === "human";
- // Pass `createdAt: now` explicitly so `msg.createdAt` matches the exact
- // string we write to `channel.lastMessageAt` and to the author's read marker
- // below. Without this, the schema `$defaultFn` fires a microsecond
- // later and the timestamps diverge — the inbox predicate
- // `lastMessageAt > lastReadAt` would then wrongly fire for the author's own
- // send on a cold read.
+ // D1 batch() is one SQL transaction. The compare-and-swap counter claim and
+ // the row that makes that seq visible must commit together: otherwise a
+ // second agent send can observe the advanced counter while unread detection
+ // cannot yet see the first message, then claim the following seq and bypass
+ // channel alignment. The insert's unique (channel_id, seq) constraint turns
+ // a lost CAS into a transaction failure, rolling back every statement below.
+ const claimSeq = db
+ .insert(communityMessageSeq)
+ .values({ channelId: data.channelId, nextSeq: seq })
+ .onConflictDoUpdate({
+ target: communityMessageSeq.channelId,
+ set: { nextSeq: seq },
+ setWhere: sql`${communityMessageSeq.nextSeq} = ${expectedSeq}`,
+ })
+ .returning({ nextSeq: communityMessageSeq.nextSeq });
+
const insertMsg = db
.insert(communityMessage)
.values({
- // Drizzle's `$defaultFn` on `communityMessage.id` only fires when the
- // field is absent from `.values(...)`; passing `id` explicitly when the
- // caller supplies one keeps the pre-minted path a one-line difference.
id: messageId,
authorId: data.authorId,
content: data.content,
@@ -235,8 +216,6 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
})
.returning();
- // Message insert + channel counter/timestamp bump commit atomically via
- // `db.batch(...)`. DMs are channels now, so this is always a channel update.
const scopeUpdate = db
.update(communityChannel)
.set({
@@ -246,9 +225,6 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
.where(eq(communityChannel.id, data.channelId));
type InsertedMessage = Awaited<typeof insertMsg>[number];
- // Caller-supplied extra statements (e.g. the bot sent-activity rollup bump)
- // ride this same batch — appended AFTER insert+scope so the message row is
- // index 0. They share the batch's all-or-nothing commit.
const authorWatermark = db
.insert(communityReadState)
.values({
@@ -264,16 +240,15 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,
});
const baseStatements = [
+ claimSeq,
insertMsg,
scopeUpdate,
...(data.extraStatements ?? []),
+ authorWatermark,
];
if (!authorIsHuman) {
- const results = (await db.batch([
- ...baseStatements,
- authorWatermark,
- ] as any)) as any[];
- return (results[0] as InsertedMessage[])[0]!;
+ const results = (await db.batch(baseStatements as any)) as any[];
+ return (results[1] as InsertedMessage[])[0]!;
}
const humanRevision = db
@@ -286,10 +261,9 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
.returning({ revision: communityReadStateRevision.revision });
const results = (await db.batch([
...baseStatements,
- authorWatermark,
humanRevision,
] as any)) as any[];
- const msg = (results[0] as InsertedMessage[])[0]!;
+ const msg = (results[1] as InsertedMessage[])[0]!;
const revisionRows = results.at(-1) as Array<{ revision: number }> | undefined;
const revision = revisionRows?.[0]?.revision;
if (revision === undefined) throw new Error("human author read-state revision missing");
diff --git a/src/shared/test/community-message-createMessage.test.ts b/src/shared/test/community-message-createMessage.test.ts
index 974bdded6..39f2fbd9d 100644
--- a/src/shared/test/community-message-createMessage.test.ts
+++ b/src/shared/test/community-message-createMessage.test.ts
@@ -4,239 +4,146 @@ import { queries } from "../src/index";
import type { Database } from "../src/index";
/**
- * Unit tests for `createMessage` batch composition.
- *
- * `createMessage` was refactored from 4 sequential awaits to:
- * (1) claimNextSeq — separate await
- * (2) db.batch([insertMsg.returning(), scopeUpdate, authorWatermark]) —
- * atomic author-send aggregate write. The message id is pre-minted so
- * the watermark no longer needs a post-batch await.
- *
- * These tests mock the Database builder chain and assert the batch's
- * contents, without needing a real D1 backend.
+ * Structural guard for the D1 write transaction. The seq reservation is not
+ * allowed to commit separately from the message, author cursor, or human
+ * read-state revision that makes the send visible.
*/
type BuilderTag =
- | { kind: "insert-msg" }
+ | { kind: "insert-seq" }
+ | { kind: "insert-msg"; values: Record<string, unknown> }
| { kind: "update-channel" }
- | { kind: "update-dm" }
- | { kind: "insert-revision" }
- | { kind: "select-readstates" }
- | { kind: "insert-readstate"; values: Record<string, unknown> };
+ | { kind: "insert-readstate"; values: Record<string, unknown> }
+ | { kind: "insert-revision" };
interface MockDb {
batchCalls: Array<BuilderTag[]>;
- awaitedStatements: BuilderTag[];
- seqReturned: number;
- messageId?: string;
}
-function makeMockDb(seq: number): { db: Database; state: MockDb } {
- const state: MockDb = { batchCalls: [], awaitedStatements: [], seqReturned: seq };
+function makeMockDb(currentSeq: number): { db: Database; state: MockDb } {
+ const state: MockDb = { batchCalls: [] };
- // Every builder is thenable so `await` on it resolves; also tagged so
- // the batch inspector can identify it after composition.
- const makeReturningBuilder = (tag: BuilderTag, resolveValue: unknown) => {
- const b: any = { __tag: tag };
- b.values = () => b;
- b.set = () => b;
- b.where = () => b;
- b.onConflictDoUpdate = () => b;
- b.returning = () => b;
- // Awaiting the builder outside a batch resolves like a real query.
- b.then = (resolve: (v: unknown) => void) => {
- state.awaitedStatements.push(tag);
- resolve(resolveValue);
+ const builder = (tag: BuilderTag) => {
+ const value: any = { __tag: tag };
+ value.values = (values: Record<string, unknown>) => {
+ if ("values" in tag) tag.values = values;
+ return value;
};
- return b;
+ value.set = () => value;
+ value.where = () => value;
+ value.onConflictDoUpdate = () => value;
+ value.returning = () => value;
+ return value;
};
const db: any = {
+ select: () => {
+ const value: any = {};
+ value.from = () => value;
+ value.where = () => Promise.resolve([{ nextSeq: currentSeq }]);
+ return value;
+ },
insert: (table: any) => {
const name = getTableName(table);
- if (name.includes("read_state_revision")) {
- return makeReturningBuilder({ kind: "insert-revision" }, [{ revision: 3 }]);
- }
+ if (name.includes("message_seq")) return builder({ kind: "insert-seq" });
+ if (name.includes("read_state_revision")) return builder({ kind: "insert-revision" });
if (name.includes("read_state")) {
- // Read-state upsert captures its `values(...)` payload for assertions.
- const b: any = { __tag: { kind: "insert-readstate", values: {} } };
- b.values = (v: Record<string, unknown>) => {
- b.__tag.values = v;
- return b;
- };
- b.onConflictDoUpdate = () => b;
- b.then = (resolve: (v: unknown) => void) => {
- state.awaitedStatements.push(b.__tag);
- resolve(undefined);
- };
- return b;
+ return builder({ kind: "insert-readstate", values: {} });
}
- // Assume message insert — resolves to a row array carrying the seq we
- // stored so callers can pick out msg.id/seq.
- const b = makeReturningBuilder({ kind: "insert-msg" }, []);
- b.values = (values: { id: string }) => {
- state.messageId = values.id;
- return b;
- };
- return b;
- },
- update: (table: any) => {
- const name = getTableName(table);
- const tag: BuilderTag = name.includes("dm_conversation")
- ? { kind: "update-dm" }
- : { kind: "update-channel" };
- return makeReturningBuilder(tag, undefined);
- },
- select: () => {
- const row = {
- channelId: "chan_1",
- lastReadMessageId: state.messageId!,
- lastReadAt: "2026-01-01T00:00:00.000Z",
- lastReadSeq: state.seqReturned,
- };
- const b = makeReturningBuilder({ kind: "select-readstates" }, [row]);
- b.from = () => b;
- return b;
+ return builder({ kind: "insert-msg", values: {} });
},
- batch: (stmts: any[]) => {
- const tags = stmts.map((s) => s.__tag as BuilderTag);
+ update: () => builder({ kind: "update-channel" }),
+ batch: async (statements: any[]) => {
+ const tags = statements.map((statement) => statement.__tag as BuilderTag);
state.batchCalls.push(tags);
- // Resolve like a real batch: first stmt's `.returning()` is the msg
- // rows array, others resolve to `undefined`.
- return Promise.resolve(
- tags.map((t) =>
- t.kind === "insert-msg"
- ? [{ id: state.messageId!, seq: state.seqReturned, createdAt: "2026-01-01T00:00:00.000Z" }]
- : t.kind === "insert-revision"
- ? [{ revision: 3 }]
- : t.kind === "select-readstates"
- ? [{
- channelId: "chan_1",
- lastReadMessageId: state.messageId!,
- lastReadAt: "2026-01-01T00:00:00.000Z",
- lastReadSeq: state.seqReturned,
- }]
- : undefined
- )
- );
+ return tags.map((tag) => {
+ if (tag.kind === "insert-msg") return [tag.values];
+ if (tag.kind === "insert-revision") return [{ revision: 3 }];
+ return undefined;
+ });
},
};
- // Override insert so the message-seq table returns the shape claimNextSeq expects.
- const originalInsert = db.insert.bind(db);
- db.insert = (table: any) => {
- const name = getTableName(table);
- if (name.includes("message_seq")) {
- const b: any = { __tag: { kind: "insert-seq" } };
- b.values = () => b;
- b.onConflictDoUpdate = () => b;
- b.returning = () => Promise.resolve([{ nextSeq: state.seqReturned }]);
- return b;
- }
- return originalInsert(table);
- };
-
return { db: db as Database, state };
}
-describe("createMessage — batch composition", () => {
+describe("createMessage — atomic batch composition", () => {
beforeEach(() => {
vi.clearAllMocks();
});
- it("channel send atomically batches message, channel, and author read-state watermark", async () => {
- const { db, state } = makeMockDb(42);
+ it.each([
+ ["channel", "chan_1"],
+ ["DM channel", "dm_chan_1"],
+ ])("%s bot send batches seq, message, scope, and read-state together", async (_, channelId) => {
+ const { db, state } = makeMockDb(41);
const msg = await queries.communityMessage.createMessage(db, {
- authorId: "user_1",
+ id: "msg_test",
+ authorId: "bot_1",
+ authorKind: "bot",
content: "hello",
- channelId: "chan_1",
+ channelId,
});
expect(state.batchCalls).toHaveLength(1);
- const batchTags = state.batchCalls[0]!.map((t) => t.kind);
- expect(batchTags).toEqual(["insert-msg", "update-channel", "insert-readstate"]);
-
- const readState = state.batchCalls[0]!.find((s) => s.kind === "insert-readstate");
- expect(readState).toBeDefined();
- const values = (readState as { kind: "insert-readstate"; values: Record<string, unknown> })
- .values;
- expect(values.lastReadSeq).toBe(42);
- expect(values.lastReadMessageId).toBe(msg.id);
- expect(values.channelId).toBe("chan_1");
-
- expect(msg.id).toBe(state.messageId);
- expect(msg.seq).toBe(42);
- });
-
- it("DM send atomically batches message, channel, and author read-state watermark", async () => {
- const { db, state } = makeMockDb(7);
- const msg = await queries.communityMessage.createMessage(db, {
- authorId: "user_1",
- content: "hi",
- channelId: "dm_chan_1",
+ expect(state.batchCalls[0]!.map((tag) => tag.kind)).toEqual([
+ "insert-seq",
+ "insert-msg",
+ "update-channel",
+ "insert-readstate",
+ ]);
+ const cursor = state.batchCalls[0]!.find(
+ (tag): tag is Extract<BuilderTag, { kind: "insert-readstate" }> =>
+ tag.kind === "insert-readstate"
+ );
+ expect(cursor?.values).toMatchObject({
+ channelId,
+ lastReadSeq: 42,
+ lastReadMessageId: "msg_test",
});
-
- expect(state.batchCalls).toHaveLength(1);
- const batchTags = state.batchCalls[0]!.map((t) => t.kind);
- // DMs are channels now — the scope bump always targets communityChannel.
- expect(batchTags).toEqual(["insert-msg", "update-channel", "insert-readstate"]);
-
- const readState = state.batchCalls[0]!.find((s) => s.kind === "insert-readstate");
- expect(readState).toBeDefined();
- const values = (readState as { kind: "insert-readstate"; values: Record<string, unknown> })
- .values;
- expect(values.lastReadSeq).toBe(7);
- expect(values.lastReadMessageId).toBe(msg.id);
- expect(values.channelId).toBe("dm_chan_1");
-
- expect(msg.id).toBe(state.messageId);
- expect(msg.seq).toBe(7);
+ expect(msg).toMatchObject({ id: "msg_test", seq: 42, channelId });
});
- it("human send atomically appends a revision without materializing account rows", async () => {
- const { db, state } = makeMockDb(9);
+ it("human send appends its revision to the same atomic batch", async () => {
+ const { db, state } = makeMockDb(8);
const msg = await queries.communityMessage.createMessage(db, {
+ id: "human_msg",
authorId: "human_1",
authorKind: "human",
content: "hello from another device",
channelId: "chan_1",
});
- expect(state.batchCalls[0]!.map((statement) => statement.kind)).toEqual([
+ expect(state.batchCalls[0]!.map((tag) => tag.kind)).toEqual([
+ "insert-seq",
"insert-msg",
"update-channel",
"insert-readstate",
"insert-revision",
]);
- expect(msg.readStateRevision).toBe(3);
+ expect(msg).toMatchObject({ id: "human_msg", seq: 9, readStateRevision: 3 });
});
- it("human forum opener uses the same ordinary author cursor as every channel type", async () => {
- const { db, state } = makeMockDb(13);
+ it("human forum opener uses the same atomic cursor and revision contract", async () => {
+ const { db, state } = makeMockDb(12);
const msg = await queries.communityMessage.createMessage(db, {
+ id: "forum_msg",
authorId: "human_1",
authorKind: "human",
content: "A new forum post",
channelId: "forum_1",
});
- expect(state.batchCalls).toHaveLength(1);
- expect(state.batchCalls[0]!.map((statement) => statement.kind)).toEqual([
- "insert-msg",
- "update-channel",
- "insert-readstate",
- "insert-revision",
- ]);
const cursor = state.batchCalls[0]!.find(
- (statement): statement is Extract<BuilderTag, { kind: "insert-readstate" }> =>
- statement.kind === "insert-readstate",
+ (tag): tag is Extract<BuilderTag, { kind: "insert-readstate" }> =>
+ tag.kind === "insert-readstate"
);
expect(cursor?.values).toMatchObject({
userId: "human_1",
channelId: "forum_1",
- lastReadMessageId: msg.id,
+ lastReadMessageId: "forum_msg",
lastReadSeq: 13,
});
- expect(msg.readStateRevision).toBe(3);
+ expect(msg).toMatchObject({ seq: 13, readStateRevision: 3 });
});
});
diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.ts
index 44c3b2d28..faa951014 100644
--- a/src/shared/test/queries/community-message.test.ts
+++ b/src/shared/test/queries/community-message.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi } from "vitest";
+import { nanoid } from "nanoid";
import * as messageQueries from "../../src/db/queries/community/message";
import {
communityMessage,
@@ -7,6 +8,8 @@ import {
communityMessageSeq,
} from "../../src/db/community-schema";
+vi.mock("nanoid", () => ({ nanoid: vi.fn(() => "m_generated") }));
+
describe("community/message exports", () => {
it("exports getMessagesByIds", () => {
expect(typeof messageQueries.getMessagesByIds).toBe("function");
@@ -186,34 +189,60 @@ describe("getMessagesByIdsInScope", () => {
*
* `insert(table).values(v).returning()` resolves to `[{...v, id: v.id ?? generatedId}]`
* so the caller can read `msg.createdAt` and `msg.id` off the inserted row.
- * `insert(table).values(v).onConflictDoUpdate(cfg)` resolves to void for
- * every table EXCEPT `communityMessageSeq`, whose upsert is followed by a
- * `.returning({ nextSeq })` (`claimNextSeq`) — that one resolves to an
- * incrementing per-scopeKey counter (starting at 1), mirroring the real
- * `INSERT ... ON CONFLICT DO UPDATE SET next_seq = next_seq + 1` semantics.
+ * The mock also models the seq counter and records committed batches so a
+ * losing compare-and-swap can be distinguished from builder construction.
*/
-function createCreateMessageDbMock(opts?: { messageId?: string }) {
+type MockStatement = Promise<unknown> & { __kind?: string; __seq?: number };
+
+function mockStatement(result: unknown, kind: string, seq?: number): MockStatement {
+ return Object.assign(Promise.resolve(result), { __kind: kind, __seq: seq });
+}
+
+function seqUniqueError() {
+ return new Error(
+ "D1_ERROR: UNIQUE constraint failed: community_message.channel_id, community_message.seq"
+ );
+}
+
+function createCreateMessageDbMock(opts?: {
+ messageId?: string;
+ currentSeq?: number;
+ batchFailures?: Array<{ error: unknown; issuedSeqAfter?: number } | null>;
+}) {
const inserts: Array<{ table: unknown; values?: any; onConflict?: any }> = [];
const updates: Array<{ table: unknown; set?: any; where?: any }> = [];
const generatedId = opts?.messageId ?? "m_generated";
+ vi.mocked(nanoid).mockReturnValue(generatedId);
const seqByScope = new Map<string, number>();
+ const batches: MockStatement[][] = [];
+ const committedBatches: MockStatement[][] = [];
+ let batchAttempt = 0;
+
+ if (opts?.currentSeq !== undefined) {
+ seqByScope.set("ch_1", opts.currentSeq);
+ seqByScope.set("dm_ch_1", opts.currentSeq);
+ }
const db: any = {
+ select: vi.fn(() => {
+ const chain: any = {};
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => {
+ const first = seqByScope.entries().next().value as [string, number] | undefined;
+ return Promise.resolve(first ? [{ nextSeq: first[1] }] : []);
+ });
+ return chain;
+ }),
insert: vi.fn((table: unknown) => {
- // `claimNextSeq`'s counter-row upsert (`communityMessageSeq`) is
- // intentionally NOT recorded into `__inserts` — every existing
- // assertion below indexes `__inserts[0]`/`[1]` assuming exactly the
- // message row then the read-state upsert, and this call always
- // precedes both (see `createMessage`'s "Step 0").
+ // Keep the counter statement out of `__inserts`: assertions below use
+ // that collection for the message and read-state payloads only.
if (table === communityMessageSeq) {
return {
values: vi.fn((v: any) => ({
onConflictDoUpdate: vi.fn(() => ({
- returning: vi.fn(() => {
- const next = (seqByScope.get(v.channelId) ?? 0) + 1;
- seqByScope.set(v.channelId, next);
- return Promise.resolve([{ nextSeq: next }]);
- }),
+ returning: vi.fn(() =>
+ mockStatement([{ nextSeq: v.nextSeq }], "seq", v.nextSeq)
+ ),
})),
})),
};
@@ -224,10 +253,12 @@ function createCreateMessageDbMock(opts?: { messageId?: string }) {
values: vi.fn((v: any) => {
rec.values = v;
return {
- returning: vi.fn(() => Promise.resolve([{ ...v, id: v.id ?? generatedId }])),
+ returning: vi.fn(() =>
+ mockStatement([{ ...v, id: v.id ?? generatedId }], "message", v.seq)
+ ),
onConflictDoUpdate: vi.fn((cfg: any) => {
rec.onConflict = cfg;
- return Promise.resolve();
+ return mockStatement(undefined, "read-state", v.lastReadSeq);
}),
};
}),
@@ -242,19 +273,44 @@ function createCreateMessageDbMock(opts?: { messageId?: string }) {
return {
where: vi.fn((w: any) => {
rec.where = w;
- return Promise.resolve();
+ return mockStatement(undefined, "channel-update");
}),
};
}),
};
}),
- // `createMessage` now composes (insert msg, update scope) into a single
- // `db.batch(...)` for atomicity. The mock's `.returning()` / `.where()`
- // above already resolve to Promises, so we just await each one and
- // collect the per-statement result.
- batch: vi.fn(async (stmts: unknown[]) => Promise.all(stmts as Promise<unknown>[])),
+ batch: vi.fn(async (stmts: MockStatement[]) => {
+ batches.push(stmts);
+ const scriptedFailure = opts?.batchFailures?.[batchAttempt++];
+ if (scriptedFailure) {
+ if (scriptedFailure.issuedSeqAfter !== undefined) {
+ const seqStmt = stmts.find((stmt) => stmt.__kind === "seq");
+ const channelId = inserts.find((rec) => rec.table === communityMessage)?.values
+ ?.channelId ?? "ch_1";
+ seqByScope.set(channelId, scriptedFailure.issuedSeqAfter);
+ if (seqStmt?.__seq !== undefined && scriptedFailure.issuedSeqAfter < seqStmt.__seq) {
+ seqByScope.set(channelId, seqStmt.__seq);
+ }
+ }
+ throw scriptedFailure.error;
+ }
+
+ const messageStmt = stmts.find((stmt) => stmt.__kind === "message");
+ const messageInsert = inserts.filter((rec) => rec.table === communityMessage).at(-1);
+ const channelId = messageInsert?.values?.channelId ?? "ch_1";
+ const currentSeq = seqByScope.get(channelId) ?? 0;
+ const proposedSeq = messageStmt?.__seq ?? 0;
+ if (proposedSeq <= currentSeq) throw seqUniqueError();
+
+ seqByScope.set(channelId, proposedSeq);
+ committedBatches.push(stmts);
+ return Promise.all(stmts);
+ }),
__inserts: inserts,
__updates: updates,
+ __batches: batches,
+ __committedBatches: committedBatches,
+ __setIssuedSeq: (channelId: string, seq: number) => seqByScope.set(channelId, seq),
};
return db;
}
@@ -418,61 +474,21 @@ describe("createMessage — DM path (a DM is a type=dm channel)", () => {
});
describe("createMessage — seq assignment", () => {
- /**
- * Records every `insert(communityMessageSeq).values(v).onConflictDoUpdate(cfg)`
- * call so tests can assert the scope key and upsert shape `claimNextSeq`
- * sends, independent of the generic `createCreateMessageDbMock` helper
- * (which only exposes the DERIVED seq number, not the raw upsert args).
- */
- function createSeqSpyDbMock(opts?: { messageId?: string; seqSequence?: number[] }) {
- const base = createCreateMessageDbMock(opts);
- const seqCalls: Array<{ values: any; onConflict: any }> = [];
- let seqIdx = 0;
- const seqSequence = opts?.seqSequence;
- const originalInsert = base.insert;
- base.insert = vi.fn((table: unknown) => {
- if (table === communityMessageSeq) {
- const rec: { values: any; onConflict: any } = { values: undefined, onConflict: undefined };
- seqCalls.push(rec);
- return {
- values: vi.fn((v: any) => {
- rec.values = v;
- return {
- onConflictDoUpdate: vi.fn((cfg: any) => {
- rec.onConflict = cfg;
- return {
- returning: vi.fn(() => {
- const next = seqSequence ? seqSequence[seqIdx++] : 1;
- return Promise.resolve([{ nextSeq: next }]);
- }),
- };
- }),
- };
- }),
- };
- }
- return originalInsert(table);
- });
- base.__seqCalls = seqCalls;
- return base;
- }
-
it("claims the seq scoped to the channelId for a channel send", async () => {
- const db = createSeqSpyDbMock();
+ const db = createCreateMessageDbMock();
await messageQueries.createMessage(db, { authorId: "u_1", content: "hi", channelId: "ch_1" });
- expect(db.__seqCalls).toHaveLength(1);
- expect(db.__seqCalls[0].values).toEqual({ channelId: "ch_1", nextSeq: 1 });
- expect(db.__seqCalls[0].onConflict.target).toBe(communityMessageSeq.channelId);
+ expect(db.insert).toHaveBeenNthCalledWith(1, communityMessageSeq);
+ expect(db.__inserts[0].values.seq).toBe(1);
});
it("claims the seq scoped to the DM's channelId for a DM send", async () => {
- const db = createSeqSpyDbMock();
+ const db = createCreateMessageDbMock();
await messageQueries.createMessage(db, { authorId: "u_1", content: "hi", channelId: "dm_ch_1" });
- expect(db.__seqCalls[0].values).toEqual({ channelId: "dm_ch_1", nextSeq: 1 });
+ expect(db.__inserts[0].values).toMatchObject({ channelId: "dm_ch_1", seq: 1 });
});
it("passes the claimed seq through to the message row AND the read-state watermark", async () => {
- const db = createSeqSpyDbMock({ seqSequence: [5] });
+ const db = createCreateMessageDbMock({ currentSeq: 4 });
const msg = await messageQueries.createMessage(db, {
authorId: "u_1",
content: "hi",
@@ -485,7 +501,7 @@ describe("createMessage — seq assignment", () => {
});
it("passes the claimed seq through for the DM channel read-state watermark too", async () => {
- const db = createSeqSpyDbMock({ seqSequence: [9] });
+ const db = createCreateMessageDbMock({ currentSeq: 8 });
const msg = await messageQueries.createMessage(db, {
authorId: "u_1",
content: "hi",
@@ -497,7 +513,7 @@ describe("createMessage — seq assignment", () => {
});
it("consecutive sends in the same channel scope get strictly increasing seqs", async () => {
- const db = createSeqSpyDbMock({ seqSequence: [1, 2, 3] });
+ const db = createCreateMessageDbMock();
const first = await messageQueries.createMessage(db, {
authorId: "u_1",
content: "one",
@@ -516,63 +532,23 @@ describe("createMessage — seq assignment", () => {
expect([first.seq, second.seq, third.seq]).toEqual([1, 2, 3]);
});
- it("the seq claim (insert into communityMessageSeq) happens before the message row insert", async () => {
- const order: string[] = [];
- const db = createSeqSpyDbMock();
- const originalInsert = db.insert;
- db.insert = vi.fn((table: unknown) => {
- order.push(table === communityMessageSeq ? "seq" : "message-or-other");
- return originalInsert(table);
- });
+ it("commits seq claim, message, channel bump, and read-state in one ordered batch", async () => {
+ const db = createCreateMessageDbMock();
await messageQueries.createMessage(db, { authorId: "u_1", content: "hi", channelId: "ch_1" });
- expect(order[0]).toBe("seq");
- expect(order[1]).toBe("message-or-other");
+ expect(db.__batches).toHaveLength(1);
+ expect(db.__batches[0].map((stmt: MockStatement) => stmt.__kind)).toEqual([
+ "seq",
+ "message",
+ "channel-update",
+ "read-state",
+ ]);
+ expect(db.__committedBatches).toHaveLength(1);
});
});
describe("createMessage — CAS claim (expectedSeq, plans/fix-agent-send-race-condition.md)", () => {
- /**
- * Same shape as `createSeqSpyDbMock` above, but scripts the CAS
- * `.returning()` call per-invocation from `seqResults`: a number resolves
- * `[{ nextSeq }]` (claim won), `null` resolves `[]` — the real
- * SQLite/Drizzle no-op shape when `onConflictDoUpdate`'s `setWhere`
- * evaluates false (claim lost the race).
- */
- function createCasSpyDbMock(opts?: { messageId?: string; seqResults?: Array<number | null> }) {
- const base = createCreateMessageDbMock(opts);
- const seqCalls: Array<{ values: any; onConflict: any }> = [];
- let seqIdx = 0;
- const seqResults = opts?.seqResults;
- const originalInsert = base.insert;
- base.insert = vi.fn((table: unknown) => {
- if (table === communityMessageSeq) {
- const rec: { values: any; onConflict: any } = { values: undefined, onConflict: undefined };
- seqCalls.push(rec);
- return {
- values: vi.fn((v: any) => {
- rec.values = v;
- return {
- onConflictDoUpdate: vi.fn((cfg: any) => {
- rec.onConflict = cfg;
- return {
- returning: vi.fn(() => {
- const next = seqResults ? seqResults[seqIdx++] : 1;
- return Promise.resolve(next === null || next === undefined ? [] : [{ nextSeq: next }]);
- }),
- };
- }),
- };
- }),
- };
- }
- return originalInsert(table);
- });
- base.__seqCalls = seqCalls;
- return base;
- }
-
it("expectedSeq matching the current counter succeeds and returns a row with the expected seq", async () => {
- const db = createCasSpyDbMock({ seqResults: [20] });
+ const db = createCreateMessageDbMock({ currentSeq: 19 });
const msg = await messageQueries.createMessage(db, {
authorId: "u_1",
content: "hi",
@@ -581,12 +557,16 @@ describe("createMessage — CAS claim (expectedSeq, plans/fix-agent-send-race-co
});
expect(msg).not.toBeNull();
expect(msg!.seq).toBe(20);
- // The CAS variant carries a setWhere gate — the unconditional claim does not.
- expect(db.__seqCalls[0].onConflict.setWhere).toBeDefined();
+ expect(db.__committedBatches).toHaveLength(1);
});
- it("stale expectedSeq: CAS claim resolves [] → createMessage returns null, with ZERO message/channel/read-state writes", async () => {
- const db = createCasSpyDbMock({ seqResults: [null] });
+ it("stale expectedSeq rolls the atomic batch back and returns null", async () => {
+ const db = createCreateMessageDbMock({
+ currentSeq: 20,
+ batchFailures: [{
+ error: new Error("D1 batch failed", { cause: seqUniqueError() }),
+ }],
+ });
const result = await messageQueries.createMessage(db, {
authorId: "u_1",
content: "hi",
@@ -594,13 +574,12 @@ describe("createMessage — CAS claim (expectedSeq, plans/fix-agent-send-race-co
expectedSeq: 19,
});
expect(result).toBeNull();
- // No message insert, no read-state upsert, no channel lastMessageAt bump.
- expect(db.__inserts).toHaveLength(0);
- expect(db.__updates).toHaveLength(0);
+ expect(db.__batches).toHaveLength(1);
+ expect(db.__committedBatches).toHaveLength(0);
});
it("two racers with the same expectedSeq: first wins the CAS, second loses it", async () => {
- const db = createCasSpyDbMock({ seqResults: [20, null] });
+ const db = createCreateMessageDbMock({ currentSeq: 19 });
const first = await messageQueries.createMessage(db, {
authorId: "u_1",
content: "hi",
@@ -615,17 +594,12 @@ describe("createMessage — CAS claim (expectedSeq, plans/fix-agent-send-race-co
});
expect(first?.seq).toBe(20);
expect(second).toBeNull();
- // Both racers hit the seq-claim exactly once each, with the SAME
- // expectedSeq snapshot (they both read `latestSeq=19` before either claimed).
- expect(db.__seqCalls).toHaveLength(2);
- expect(db.__seqCalls[0].values).toEqual({ channelId: "ch_1", nextSeq: 1 });
- expect(db.__seqCalls[1].values).toEqual({ channelId: "ch_1", nextSeq: 1 });
- expect(db.__seqCalls[0].onConflict.setWhere).toBeDefined();
- expect(db.__seqCalls[1].onConflict.setWhere).toBeDefined();
+ expect(db.__batches).toHaveLength(2);
+ expect(db.__committedBatches).toHaveLength(1);
});
it("expectedSeq: 0 on a scope with no prior messages succeeds (first-message-ever INSERT branch, no conflict to gate)", async () => {
- const db = createCasSpyDbMock({ seqResults: [1] });
+ const db = createCreateMessageDbMock();
const msg = await messageQueries.createMessage(db, {
authorId: "u_1",
content: "hi",
@@ -636,16 +610,83 @@ describe("createMessage — CAS claim (expectedSeq, plans/fix-agent-send-race-co
expect(msg!.seq).toBe(1);
});
- it("no expectedSeq behaves exactly as before (regression guard — web/human send path unaffected)", async () => {
- const db = createCasSpyDbMock({ seqResults: [1] });
+ it("ordinary sends retry a lost seq race using the refreshed counter", async () => {
+ const db = createCreateMessageDbMock({
+ batchFailures: [{ error: seqUniqueError(), issuedSeqAfter: 1 }, null],
+ });
const msg = await messageQueries.createMessage(db, {
authorId: "u_1",
content: "hi",
channelId: "ch_1",
});
- expect(msg.seq).toBe(1);
- // The unconditional claim carries no setWhere gate.
- expect(db.__seqCalls[0].onConflict.setWhere).toBeUndefined();
+ expect(msg.seq).toBe(2);
+ expect(db.__batches).toHaveLength(2);
+ expect(db.__committedBatches).toHaveLength(1);
+ });
+
+ it("drains a full 30-send collision wave without exhausting ordinary retries", async () => {
+ const batchFailures = Array.from({ length: 30 }, (_, index) => ({
+ error: seqUniqueError(),
+ issuedSeqAfter: index + 1,
+ }));
+ const db = createCreateMessageDbMock({ batchFailures });
+
+ const msg = await messageQueries.createMessage(db, {
+ authorId: "u_1",
+ content: "after the burst",
+ channelId: "ch_1",
+ });
+
+ expect(msg.seq).toBe(31);
+ expect(db.__batches).toHaveLength(31);
+ expect(db.__committedBatches).toHaveLength(1);
+ });
+
+ it("stops an ordinary send after the bounded collision retry budget", async () => {
+ const lastError = seqUniqueError();
+ const batchFailures = Array.from({ length: 64 }, (_, index) => ({
+ error: index === 63 ? lastError : seqUniqueError(),
+ issuedSeqAfter: index + 1,
+ }));
+ const db = createCreateMessageDbMock({ batchFailures });
+
+ await expect(messageQueries.createMessage(db, {
+ authorId: "u_1",
+ content: "too much contention",
+ channelId: "ch_1",
+ })).rejects.toBe(lastError);
+ expect(db.__batches).toHaveLength(64);
+ expect(db.__committedBatches).toHaveLength(0);
+ });
+
+ it("recognizes a primitive D1 seq-conflict rejection", async () => {
+ const db = createCreateMessageDbMock({
+ batchFailures: [{
+ error: "D1_ERROR: UNIQUE constraint failed: community_message.channel_id, community_message.seq",
+ }],
+ });
+
+ await expect(messageQueries.createMessage(db, {
+ authorId: "u_1",
+ content: "stale aligned send",
+ channelId: "ch_1",
+ expectedSeq: 0,
+ })).resolves.toBeNull();
+ expect(db.__committedBatches).toHaveLength(0);
+ });
+
+ it("does not convert an unrelated unique violation into an alignment miss", async () => {
+ const nonceError = new Error(
+ "D1_ERROR: UNIQUE constraint failed: community_message.author_id, community_message.client_nonce"
+ );
+ const db = createCreateMessageDbMock({ batchFailures: [{ error: nonceError }] });
+ await expect(messageQueries.createMessage(db, {
+ authorId: "u_1",
+ content: "hi",
+ channelId: "ch_1",
+ expectedSeq: 0,
+ })).rejects.toBe(nonceError);
+ expect(db.__committedBatches).toHaveLength(0);
});
});
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
index 7758e5e04..084964a3c 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
@@ -2,7 +2,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })) }))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({
+ getDb: vi.fn(() => ({})),
+ getPrimaryDb: vi.fn(() => ({})),
+}))
const mockCreateMessageWithThread = vi.fn()
const mockResolveTargetForMember = vi.fn()
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index 3f00199e1..98bf8e20d 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
@@ -51,8 +51,13 @@ const mockFanOutToChannel = vi.fn()
const mockDispatchCommittedMessage = vi.fn(async () => {})
const mockBroadcastToUser = vi.fn()
const mockCheckMessageRateLimit = vi.fn()
+const mockGetDb = vi.fn(() => ({}))
+const mockGetPrimaryDb = vi.fn(() => ({}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({
+ getDb: (...a: unknown[]) => mockGetDb(...a),
+ getPrimaryDb: (...a: unknown[]) => mockGetPrimaryDb(...a),
+}))
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: (...a: unknown[]) => mockCheckMessageRateLimit(...a),
@@ -254,6 +259,14 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockRebindPendingAttachmentsToChild.mockResolvedValue(true)
})
+ it("starts the write path on a first-primary D1 session", async () => {
+ const res = await POST(postReq({ content: "hello" }), ctx)
+
+ expect(res.status).toBe(201)
+ expect(mockGetPrimaryDb).toHaveBeenCalledTimes(1)
+ expect(mockGetDb).not.toHaveBeenCalled()
+ })
+
it("accepts a bare message to a forum top-level (phase2 forum≡thread write-guard reversal — forum is now directly sendable)", async () => {
mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })
mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })
@@ -582,6 +595,37 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(mockCreateMessage).toHaveBeenCalledTimes(1)
expect(mockHasDeliverableUnreadForAgentScope).toHaveBeenCalledTimes(1)
})
+
+ it("bot send that loses the post-check seq race returns a fresh unaligned envelope", async () => {
+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "s1" }])
+ mockResolveChannelByNameForMember.mockResolvedValue([
+ { id: "c1", serverId: "s1", type: "text", parentChannelId: null },
+ ])
+ mockGetLatestSeqForScope
+ .mockResolvedValueOnce(19)
+ .mockResolvedValueOnce(20)
+ mockGetReadState.mockResolvedValue({ lastReadSeq: 19 })
+ mockHasDeliverableUnreadForAgentScope.mockResolvedValue(false)
+ mockCreateMessage.mockResolvedValue(null)
+
+ const res = await POST(botPostReq({
+ channel: "/demo#0042/text",
+ content: { text: "reply" },
+ }), ctx)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({
+ state: "blocked",
+ reason: "unaligned",
+ unreadCount: 1,
+ latestSeq: 20,
+ })
+ expect(mockCreateMessage).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ expectedSeq: 19 }),
+ )
+ expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()
+ })
})
describe("GET /api/community/channels/[id]/messages", () => {
@@ -598,6 +642,16 @@ describe("GET /api/community/channels/[id]/messages", () => {
mockGetLatestMessageSeq.mockResolvedValue(0)
})
+ it("keeps the read path on the unconstrained replica-capable session", async () => {
+ mockListMessages.mockResolvedValue([])
+
+ const res = await GET(getReq(), ctx)
+
+ expect(res.status).toBe(200)
+ expect(mockGetDb).toHaveBeenCalledTimes(1)
+ expect(mockGetPrimaryDb).not.toHaveBeenCalled()
+ })
+
it("resolves reply previews via one scoped getMessagesByIdsInScope call (never per-item getMessage)", async () => {
// 5-message page. 3 have replyToId set:
// m-a → target r-in-scope (same channel) → resolves.
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.ts
index f57a207a8..d7b6083d3 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import { queries, withD1Retry, CommunityAgentSendRequestSchema, MAX_FORUM_TAG_LENGTH, utcDayKey } from "@alook/shared"
import {
parseCursor,
@@ -185,7 +185,12 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
* SAME mask (never skipped because machine-token — ASSERT 1 ①-C).
*/
export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
- const db = getDb(ctx.env.DB)
+ // A send is read-before-write: authorization, alignment, retries, and the
+ // blocked response all depend on the latest committed channel state. Start
+ // this request on primary so a lagging replica cannot supply a stale CAS
+ // boundary or stale `latestSeq`; subsequent reads remain sequentially
+ // consistent within the same D1 session.
+ const db = getPrimaryDb(ctx.env.DB)
let raw: unknown
try {