Skip to content

Commit f1a4338

Browse files
committed
fix(kiloclaw): make getActiveInstance deterministic with ORDER BY created_at
Add ORDER BY created_at ASC to getActiveInstance so LIMIT 1 always returns the oldest active row. Documents the known race window in ensureActiveInstance where concurrent callers can both insert — the consequence is a benign orphan row since all subsequent reads converge on the same (oldest) row.
1 parent ad0569b commit f1a4338

1 file changed

Lines changed: 6 additions & 0 deletions

File tree

src/lib/kiloclaw/instance-registry.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ export async function ensureActiveInstance(
6868
}
6969

7070
// Personal flow: return existing active row if present.
71+
// Race note: two concurrent callers can both see no row and both insert.
72+
// This is benign — getActiveInstance uses ORDER BY created_at ASC so all
73+
// subsequent reads converge on the oldest row. The second row is an inert
74+
// orphan (no DO created for it). The window is milliseconds on a user-
75+
// initiated action already deduplicated by the frontend's useMutation.
7176
const existing = await getActiveInstance(userId);
7277
if (existing) return existing;
7378

@@ -178,6 +183,7 @@ export async function getActiveInstance(userId: string): Promise<ActiveKiloClawI
178183
isNull(kiloclaw_instances.destroyed_at)
179184
)
180185
)
186+
.orderBy(kiloclaw_instances.created_at)
181187
.limit(1);
182188

183189
return row ?? null;

0 commit comments

Comments
 (0)