Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): D1 resilience on core hot paths + restore 0075/0077 migrations

Generdf259401777d
diff --git a/src/web/migrations/0075_channel_name_nocase.sql b/src/web/migrations/0075_channel_name_nocase.sql
new file mode 100644
index 000000000..9aca25cdf
--- /dev/null
+++ b/src/web/migrations/0075_channel_name_nocase.sql
@@ -0,0 +1,26 @@
+-- Case-insensitive top-level channel names (ref/id §4 + chore #52-59). The
+-- per-server unique index on `(server_id, name)` was case-SENSITIVE, so
+-- `general` and `General` were two addressable channels and a ref that only
+-- differed in case 404'd. Rebuild it with `COLLATE NOCASE` so the DB uniqueness
+-- ruler matches the case-insensitive name resolution + dedup (all three now
+-- share SQLite's NOCASE fold — see resolveChannelByNameForMember /
+-- getChildChannelByName / resolveServerByNameForMember / dedupeChildChannelSlug,
+-- which use `COLLATE NOCASE` in SQL rather than a JS fold that could drift).
+--
+-- APPLY PREREQUISITE: zero case-collisions under the NOCASE fold — i.e. no two
+-- top-level channels in the same server whose names differ only by case.
+-- Verified against the live remote D1 on 2026-07-31 (Gener's online scan: 0
+-- rows). If applying to ANY OTHER environment, re-scan first:
+-- SELECT server_id, LOWER(name), COUNT(*) FROM community_channel
+-- WHERE parent_channel_id IS NULL GROUP BY server_id, LOWER(name) HAVING COUNT(*) > 1;
+-- and resolve collisions (rename/merge) before this index will build.
+--
+-- Known scope (path A): SQLite NOCASE folds ASCII A-Z only, so non-ASCII case
+-- (e.g. `Café`/`café`) is NOT folded — treated as distinct, CONSISTENTLY across
+-- index + resolve + dedup (consistency is the invariant; folding non-ASCII is a
+-- follow-up requiring an app-layer Unicode fold + folded column, out of scope).
+
+DROP INDEX IF EXISTS idx_channel_server_name;
+CREATE UNIQUE INDEX idx_channel_server_name
+ ON community_channel(server_id, name COLLATE NOCASE)
+ WHERE parent_channel_id IS NULL;
diff --git a/src/web/migrations/0077_mention_unique.sql b/src/web/migrations/0077_mention_unique.sql
new file mode 100644
index 000000000..b7c1989a9
--- /dev/null
+++ b/src/web/migrations/0077_mention_unique.sql
@@ -0,0 +1,25 @@
+-- Natural idempotency key for community_mention: a message mentions a given
+-- user in a given kind AT MOST once. This makes `createMentions` retry-safe
+-- (onConflictDoNothing on this key), so a transient replay under `withD1Retry`
+-- re-inserts only the missing rows instead of double-inserting — a duplicate
+-- mention row would otherwise silently inflate the unread count (list has no
+-- distinct; unread counts read=0 rows) and duplicate the inbox entry.
+--
+-- All three columns are NOT NULL, so a plain UNIQUE index suffices (no partial).
+--
+-- Self-guarding: the normal send flow calls createMentions once per message, so
+-- collisions are not expected — but in case any historical duplicate rows exist
+-- (a pre-armor double-insert on a transient), collapse each (message_id,
+-- user_id, kind) group to its lowest rowid BEFORE adding the unique, so the
+-- migration is safe to apply without a separate precondition step. Keeps the
+-- oldest row; drops the accidental duplicates (they carry no distinct state —
+-- `read` is per (user, message), reconciled on next read).
+DELETE FROM community_mention
+WHERE rowid NOT IN (
+ SELECT MIN(rowid)
+ FROM community_mention
+ GROUP BY message_id, user_id, kind
+);
+
+CREATE UNIQUE INDEX uq_mention_message_user_kind
+ ON community_mention(message_id, user_id, kind);
diff --git a/src/web/src/app/api/community/inbox/unreads/route.ts b/src/web/src/app/api/community/inbox/unreads/route.ts
index 92eb8e879..e9a05784b 100644
--- a/src/web/src/app/api/community/inbox/unreads/route.ts
+++ b/src/web/src/app/api/community/inbox/unreads/route.ts
@@ -3,6 +3,7 @@ import {
DEFAULT_INBOX_PAGE_SIZE,
MAX_INBOX_PAGE_SIZE,
readOrStale,
+ withD1Retry,
} from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
@@ -125,7 +126,10 @@ export const GET = withAuth(async (req, ctx) => {
// child rows (they joined `communityServer`).
const missingParentIds = [...childrenByParent.keys()].filter((pid) => !parents.has(pid) && !mutedChannels.has(pid))
if (missingParentIds.length > 0) {
- const resolved = await queries.communityChannel.getChannelsByIds(db, missingParentIds)
+ const resolved = await withD1Retry(
+ () => queries.communityChannel.getChannelsByIds(db, missingParentIds),
+ { route: "community/inbox/unreads:missing-parents" },
+ )
const resolvedById = new Map(resolved.map((c) => [c.id, c]))
for (const pid of missingParentIds) {
const ch = resolvedById.get(pid)
diff --git a/src/web/src/app/api/community/inboxSnapshot/route.ts b/src/web/src/app/api/community/inboxSnapshot/route.ts
index b4330f74b..fd238f231 100644
--- a/src/web/src/app/api/community/inboxSnapshot/route.ts
+++ b/src/web/src/app/api/community/inboxSnapshot/route.ts
@@ -1,5 +1,5 @@
import { NextResponse, type NextRequest } from "next/server"
-import { queries } from "@alook/shared"
+import { queries, withD1Retry } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
@@ -16,8 +16,14 @@ export const POST = withCommunityActor(async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
- const snapshot = await queries.communityAgentInbox.getInboxSnapshotForAgent(db, botUserId)
- const rows = await queries.communityAgentInbox.toInboxRows(db, snapshot, botUserId)
+ const snapshot = await withD1Retry(
+ () => queries.communityAgentInbox.getInboxSnapshotForAgent(db, botUserId),
+ { route: "community/inboxSnapshot:snapshot" },
+ )
+ const rows = await withD1Retry(
+ () => queries.communityAgentInbox.toInboxRows(db, snapshot, botUserId),
+ { route: "community/inboxSnapshot:rows" },
+ )
return NextResponse.json({
rows,
diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.ts
index 8227b2976..65bdf1319 100644
--- a/src/web/src/lib/community/fanout.ts
+++ b/src/web/src/lib/community/fanout.ts
@@ -13,7 +13,7 @@
*/
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries, createLogger, WS_EVENTS, isThread, isForumPost, isDm } from "@alook/shared"
+import { queries, createLogger, WS_EVENTS, isThread, isForumPost, isDm, withD1Retry } from "@alook/shared"
import type { CommunityWsEvent, Database } from "@alook/shared"
import { getDb } from "../db"
import { broadcastToUser } from "../broadcast"
@@ -59,17 +59,26 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s
* The split lives here so fan-out and bot-wake use the same recipient set.
*/
async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {
- const rows = await queries.communityChannel.getChannelType(db, channelId)
+ const rows = await withD1Retry(
+ () => queries.communityChannel.getChannelType(db, channelId),
+ { route: "fanout:channel-type" },
+ )
if (isThread(rows) || isForumPost(rows)) {
- return queries.communityThread.listThreadParticipantUserIds(db, channelId)
+ return withD1Retry(
+ () => queries.communityThread.listThreadParticipantUserIds(db, channelId),
+ { route: "fanout:thread-participants" },
+ )
}
if (isDm(rows)) {
- return queries.communityChannel.listChannelMemberUserIds(db, channelId)
+ return withD1Retry(
+ () => queries.communityChannel.listChannelMemberUserIds(db, channelId),
+ { route: "fanout:dm-members" },
+ )
}
- return queries.communityMembersResolver.resolveScopeMemberUserIds(db, {
- scope: "channel",
- scopeId: channelId,
- })
+ return withD1Retry(
+ () => queries.communityMembersResolver.resolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId }),
+ { route: "fanout:scope-members" },
+ )
}
/**
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index ee083c28a..739403d6a 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -9,6 +9,7 @@ import {
MENTION_KIND,
createLogger,
isUniqueConstraintError,
+ withD1Retry,
} from "@alook/shared"
import type { MentionType } from "@alook/shared"
import type { Database } from "@alook/shared"
@@ -293,10 +294,9 @@ export async function createCommunityMessage(params: {
// race where two concurrent first-sends both pass this check is caught at
// insert time by the partial-unique-index handler below.
if (clientNonce !== undefined) {
- const existing = await queries.communityMessage.getMessageByAuthorAndNonce(
- db,
- authorId,
- clientNonce,
+ const existing = await withD1Retry(
+ () => queries.communityMessage.getMessageByAuthorAndNonce(db, authorId, clientNonce),
+ { route: "message-handler:nonce-precheck" },
)
if (existing) {
return { ok: true, row: existing, attachments: [], deduped: true }
@@ -325,9 +325,10 @@ export async function createCommunityMessage(params: {
| Awaited<ReturnType<typeof queries.communityMessage.getMessageInScope>>
| null = null
if (rawReplyToId !== undefined) {
- resolvedReplyMsg = await queries.communityMessage.getMessageInScope(db, rawReplyToId, {
- channelId: target.channelId,
- })
+ resolvedReplyMsg = await withD1Retry(
+ () => queries.communityMessage.getMessageInScope(db, rawReplyToId, { channelId: target.channelId }),
+ { route: "message-handler:reply-scope" },
+ )
if (!resolvedReplyMsg) {
log.warn("reply_to_out_of_scope_dropped", {
authorId,
@@ -393,10 +394,9 @@ export async function createCommunityMessage(params: {
// with no nonce) finds no matching row, so we rethrow the original error
// untouched. Only enter this branch when a nonce was actually supplied.
if (clientNonce !== undefined && isUniqueConstraintError(err)) {
- const existing = await queries.communityMessage.getMessageByAuthorAndNonce(
- db,
- authorId,
- clientNonce,
+ const existing = await withD1Retry(
+ () => queries.communityMessage.getMessageByAuthorAndNonce(db, authorId, clientNonce),
+ { route: "message-handler:nonce-insert-race" },
)
if (existing) {
return { ok: true, row: existing, attachments: [], deduped: true }
@@ -521,7 +521,10 @@ export async function createCommunityMessage(params: {
)
}
- const row = await queries.communityMessage.getMessage(db, created.id)
+ const row = await withD1Retry(
+ () => queries.communityMessage.getMessage(db, created.id),
+ { route: "message-handler:read-back" },
+ )
if (!row) {
// createMessage just inserted this row; getMessage returning null means
// the DB is gone — surface that to the caller instead of inventing data.
@@ -535,7 +538,10 @@ export async function createCommunityMessage(params: {
// the repo; this mirrors the check the daemon route did before its own
// `logAudit` call was removed. Fire-and-forget — `logAudit` already
// swallows its own errors.
- const author = await queries.user.getUserInternal(db, authorId)
+ const author = await withD1Retry(
+ () => queries.user.getUserInternal(db, authorId),
+ { route: "message-handler:author-lookup" },
+ )
if (author?.isBot === true) {
logAudit(db, {
serverId: isDmTarget(target) ? null : target.serverId,
@@ -600,14 +606,25 @@ export async function createCommunityMessage(params: {
// each climb `parentChannelId` for a thread — two parent lookups per message
// on the send path. Cheap (indexed id lookups) and not merged to keep both
// helpers single-purpose; revisit only if the send path shows up hot.
- const isPrivate = await queries.communityChannel.isChannelPrivate(db, target.channelId)
+ const isPrivate = await withD1Retry(
+ () => queries.communityChannel.isChannelPrivate(db, target.channelId),
+ { route: "message-handler:is-private" },
+ )
const audienceIds = isPrivate
- ? new Set(await queries.communityChannel.getPrivateChannelAudienceUserIds(db, target.channelId))
+ ? new Set(
+ await withD1Retry(
+ () => queries.communityChannel.getPrivateChannelAudienceUserIds(db, target.channelId),
+ { route: "message-handler:private-audience" },
+ ),
+ )
: null
const hasAtMention = typeof row.content === "string" && row.content.includes("@")
if (hasAtMention) {
- const allMembers = await queries.communityMember.listMembers(db, target.serverId)
+ const allMembers = await withD1Retry(
+ () => queries.communityMember.listMembers(db, target.serverId),
+ { route: "message-handler:list-members" },
+ )
// Scope candidates to the audience when private.
const members = audienceIds
? allMembers.filter((m) => audienceIds.has(m.userId))
@@ -629,7 +646,10 @@ export async function createCommunityMessage(params: {
} else if (mentionType === "everyone") {
const userIds = audienceIds
? [...audienceIds]
- : await queries.communityMember.listMemberUserIds(db, target.serverId)
+ : await withD1Retry(
+ () => queries.communityMember.listMemberUserIds(db, target.serverId),
+ { route: "message-handler:list-member-ids" },
+ )
for (const uid of userIds) {
if (uid !== authorId) mentionTargets.add(uid)
}
@@ -793,9 +813,9 @@ export async function createCommunityMessage(params: {
if (!isDmTarget(target)) {
if (hasParentChannel(target) && !skipChildChannelUpdate) {
- const updated = await queries.communityChannel.getChannel(
- db,
- target.channelId,
+ const updated = await withD1Retry(
+ () => queries.communityChannel.getChannel(db, target.channelId),
+ { route: "message-handler:child-channel-read" },
)
fanOutToChannel(
target.parentChannelId,
diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.ts
index 45c86d8f0..f24878889 100644
--- a/src/web/src/lib/community/wake-producer.ts
+++ b/src/web/src/lib/community/wake-producer.ts
@@ -17,7 +17,7 @@
* `wrangler dev`/`next dev` processes today).
*/
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries, createLogger } from "@alook/shared"
+import { queries, createLogger, withD1Retry } from "@alook/shared"
import type { WakePayload } from "@alook/shared"
import { getDb } from "../db"
import { shouldDeliver } from "./notify"
@@ -98,11 +98,10 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<v
if (recipients.length === 0) return
const db = getDb(env.DB)
- const candidates = await queries.communityBot.findWakeCandidates(db, {
- recipients,
- channelId,
- newSeq: messageRow.seq,
- })
+ const candidates = await withD1Retry(
+ () => queries.communityBot.findWakeCandidates(db, { recipients, channelId, newSeq: messageRow.seq }),
+ { route: "wake-producer:find-candidates" },
+ )
if (candidates.length === 0) return
// Defense-in-depth visibility + participation gate. `findWakeCandidates`
@@ -141,10 +140,14 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<v
// no server/parent row → defaults to `all`), so a `nothing` set elsewhere
// never suppresses a DM wake.
const mentioned = new Set(opts.mentionedUserIds ?? [])
- const levels = await queries.communityNotificationSetting.resolveEffectiveLevelForUsers(
- db,
- gated.map((c) => c.botUserId),
- channelId,
+ const levels = await withD1Retry(
+ () =>
+ queries.communityNotificationSetting.resolveEffectiveLevelForUsers(
+ db,
+ gated.map((c) => c.botUserId),
+ channelId,
+ ),
+ { route: "wake-producer:effective-levels" },
)
const woken = gated.filter((c) =>
shouldDeliver(levels.get(c.botUserId) ?? "all", mentioned.has(c.botUserId)),