diff --git a/server/lib/storage/config-store.ts b/server/lib/storage/config-store.ts index a238e34..c77eb7b 100644 --- a/server/lib/storage/config-store.ts +++ b/server/lib/storage/config-store.ts @@ -1147,7 +1147,22 @@ export function kvConfigStore(kv: KVNamespace): ConfigStore { const raw = await kv.get(key, "json"); return Array.isArray(raw) ? raw : []; } - const loadRoutes = async (): Promise => migrateRoutes(await readList(KV_ROUTES_KEY)); + /** + * KV has no transaction spanning the group and route lists. A rename can + * therefore be interrupted between its writes, leaving routes under an id + * that is no longer a group (or under the new id before that group exists). + * Never serve those orphaned routes: they could otherwise be inherited by a + * later group that reuses the id. Repair the permanent route list while it + * is read so every public load path gets the same safety boundary. + */ + const loadRoutes = async (): Promise => { + const routes = migrateRoutes(await readList(KV_ROUTES_KEY)); + const groups = migrateGroups(await readList(KV_GROUPS_KEY)); + const groupIds = new Set(groups.map((g) => g.id)); + const kept = routes.filter((route) => !route.groupId || groupIds.has(route.groupId)); + if (kept.length !== routes.length) await kv.put(KV_ROUTES_KEY, JSON.stringify(kept)); + return kept; + }; let identitiesMigrated = false; const loadGroups = async (): Promise => { let groups = migrateGroups(await readList(KV_GROUPS_KEY)); diff --git a/tests/config-store.test.ts b/tests/config-store.test.ts index d322c91..215625b 100644 --- a/tests/config-store.test.ts +++ b/tests/config-store.test.ts @@ -380,6 +380,22 @@ describe("kvConfigStore", () => { expect(JSON.parse(store.get("config:routes")!)).toEqual([]); }); + it("repairs orphaned routes before a reused group id can inherit them", async () => { + const { kv, store } = createMemoryKV(); + store.set("config:groups", JSON.stringify([group("current")])); + store.set( + "config:routes", + JSON.stringify([route("orphan", "reused"), route("live", "current")]), + ); + const cfg = kvConfigStore(kv); + + expect((await cfg.loadRoutes()).map((r) => r.id)).toEqual(["live"]); + expect(JSON.parse(store.get("config:routes")!)).toEqual([route("live", "current")]); + + await expect(cfg.createGroup(group("reused"))).resolves.toBe(true); + expect((await cfg.loadRoutes()).map((r) => r.id)).toEqual(["live"]); + }); + it("backfills the same instance whichever cold start wins the race", async () => { const { kv, store } = createMemoryKV(); store.set("config:groups", JSON.stringify([group("legacy")]));