iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

A watch that starts while the catalog's socket is dialled again shares that dial

A session's watches ride one socket into the catalog. When it dropped, a watch that started
before the new dial answered dialled a socket of its own, and the session then held two, each
with the frames of the watches asked on it. Such a watch now waits for the dial that is on its
way and asks its query once.

The test in workerd also proves, through both ways a session ends, that the frames of one write
come as one batch with the last one marked, and that the dispose of a watch's handle takes its
query off the catalog while the session's other watches stay.

Session: agy b859a067-e1f8-4f91-8d14-337c9a19b40b on beelink
Worker: claude 02c7d409-d06c-4792-af54-c1861507c2e0 on beelink

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

Jonas Templestein, 2026-11-26 23:03 UTC · 5a3f216a5051c1f550db5f9330b938f0e89f5260 · parent ba63085

3 files changed

M core/itx/src/context/catalog-watch.test.ts
@@ -122,6 +122,41 @@
   });
 });
 
+test("a watch that starts while the socket is dialled again waits for that dial, and dials none of its own", async () => {
+  vi.useFakeTimers();
+  onTestFinished(() => void vi.useRealTimers());
+  vi.spyOn(console, "info").mockImplementation(() => {});
+  const far = catalog();
+  const relay = far.relay();
+  const first = relay.watch(ticket({ limit: 1 }), () => {});
+  const socket = await far.asked();
+  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] });
+  using _first = await first;
+  // the socket drops, and the dial that takes its place is slow
+  let answerTheDial = () => {};
+  far.before = new Promise<void>((resolve) => (answerTheDial = resolve));
+  socket.drop();
+  await vi.advanceTimersByTimeAsync(10);
+  const frames: CatalogFrame<unknown>[] = [];
+  const second = relay.watch(ticket({ limit: 2 }), (frame) => frames.push(frame));
+  await vi.advanceTimersByTimeAsync(10);
+  expect(far).toMatchObject({ dials: 2 });
+  answerTheDial();
+  await vi.advanceTimersByTimeAsync(200);
+  const again = await far.asked(2);
+  // one socket for the session: the first watch is asked again on it, and the second asks once
+  expect(far).toMatchObject({ dials: 2 });
+  expect(again.sent.toSorted((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))).toEqual(
+    [
+      { op: "subscribe", sub: "w1", query: { limit: 1 } },
+      { op: "subscribe", sub: "w2", query: { limit: 2 } },
+    ],
+  );
+  again.say({ sub: "w2", q: "q", gen: "g", rev: 5, full: false, reset: [{ path: "/a" }] });
+  using _second = await second;
+  expect(frames).toMatchObject([{ type: "reset", rows: [{ path: "/a" }] }]);
+});
+
 test("a socket whose keepalives go unanswered is taken for dead and dialled again", async () => {
   vi.useFakeTimers();
   onTestFinished(() => void vi.useRealTimers());
@@ -267,6 +302,8 @@
   const far = {
     dials: 0,
     refuses: false,
+    /** A dial answers when this settles: a catalog that is slow to come back. */
+    before: Promise.resolve(),
     /** The newest socket, once the session's end has sent it `count` messages: it listens then. */
     asked: async (count = 1) => {
       for (;;) {
@@ -279,6 +316,7 @@
       const relay = new CatalogWatchRelay({
         dial: async () => {
           far.dials += 1;
+          await far.before;
           if (far.refuses) return { status: 503 };
           const socket = new FarSocket();
           sockets.push(socket);
M core/itx/src/context/catalog-watch.ts
@@ -107,8 +107,15 @@
   /** Of the watch's last frame: a change must follow it. */
   gen: string;
   rev: number;
+  /** Its query went to the catalog on a socket: a socket that takes that one's place asks it
+   *  again. A watch that still waits for the first socket sends its query itself. */
+  asked: boolean;
   /** Settles the call that made the watch, at the catalog's first answer or its refusal. */
-  answered?: { resolve: () => void; reject: (error: Error) => void; timer: unknown };
+  answered?: {
+    resolve: () => void;
+    reject: (error: Error) => void;
+    timer: ReturnType<typeof setTimeout>;
+  };
   end: (reason: string) => void;
 };
 
@@ -174,11 +181,12 @@
       onFrame: callback,
       gen: "",
       rev: -1,
+      asked: false,
       end: (reason) => {
         if (this.#watches.get(sub) !== watch) return;
         this.#watches.delete(sub);
         if (watch.answered) {
-          clearTimeout(watch.answered.timer as never);
+          clearTimeout(watch.answered.timer);
           watch.answered.reject(codedError("UNAVAILABLE", `contexts.watch: ${reason}`));
         }
         disposeRpcStub(callback);
@@ -203,6 +211,7 @@
           ),
         };
         socket.send(JSON.stringify({ op: "subscribe", sub, query, cursor }));
+        watch.asked = true;
       });
     } catch (error) {
       watch.answered = undefined;
@@ -292,34 +301,49 @@
     socket.addEventListener("error", () => gone({ reason: "it failed" }));
   }
 
-  /** The socket ended under watches that live: dial again, and ask every query again. */
+  /** The socket ended under watches that live: dial again, and ask every query again. A watch
+   *  that starts meanwhile waits for this dial (`#open`), and dials none of its own: two sockets
+   *  of one session would each get the frames of the watches that were asked on it. */
   #lost(socket: WebSocket, why: string): void {
     if (this.#socket !== socket) return;
     this.#closeSocket();
     if (this.#over || this.#watches.size === 0) return;
+    const redialing = redial(
+      this.#dial as () => Promise<DialAnswer & { webSocket?: WebSocket | null }>,
+      () => this.#over || this.#watches.size === 0,
+      REDIAL_DEADLINE_MS,
+    ).then((redialed) => {
+      if (!redialed) throw codedError("UNAVAILABLE", "contexts.watch: the session ended");
+      if ("gaveUp" in redialed) {
+        console.error({
+          event: "catalog-watch.redial-failed",
+          message:
+            "a session's watch socket dropped and could not be dialled again: its watches end",
+          why,
+          lastFailure: redialed.gaveUp,
+        });
+        for (const watch of [...this.#watches.values()])
+          watch.end("the catalog could not be reached again: watch again");
+        throw codedError(
+          "UNAVAILABLE",
+          "contexts.watch: the catalog could not be reached again: watch again",
+        );
+      }
+      console.info({ event: "catalog-watch.redialed", why, attempt: redialed.dials });
+      this.#attach(redialed.socket);
+      for (const [sub, watch] of this.#watches) if (watch.asked) this.#askAgain(sub);
+      return redialed.socket;
+    });
+    this.#opening = redialing;
     this.#waitUntil(
-      redial(
-        this.#dial as () => Promise<DialAnswer & { webSocket?: WebSocket | null }>,
-        () => this.#over || this.#watches.size === 0,
-        REDIAL_DEADLINE_MS,
-      ).then((redialed) => {
-        if (!redialed) return;
-        if ("gaveUp" in redialed) {
-          console.error({
-            event: "catalog-watch.redial-failed",
-            message:
-              "a session's watch socket dropped and could not be dialled again: its watches end",
-            why,
-            lastFailure: redialed.gaveUp,
-          });
-          for (const watch of [...this.#watches.values()])
-            watch.end("the catalog could not be reached again: watch again");
-          return;
-        }
-        console.info({ event: "catalog-watch.redialed", why, attempt: redialed.dials });
-        this.#attach(redialed.socket);
-        for (const sub of this.#watches.keys()) this.#askAgain(sub);
-      }),
+      redialing
+        .then(
+          () => {},
+          () => {},
+        )
+        .finally(() => {
+          if (this.#opening === redialing) this.#opening = undefined;
+        }),
     );
   }
 
@@ -350,7 +374,7 @@
       if (!watch) return;
       const refusal = codedError("INVALID_INPUT", `contexts.watch: ${message.error}`);
       if (!watch.answered) return watch.end(message.error);
-      clearTimeout(watch.answered.timer as never);
+      clearTimeout(watch.answered.timer);
       watch.answered.reject(refusal);
       return;
     }
@@ -391,7 +415,7 @@
     // frame; until then the watch's end, or the deadline, still rejects it
     void handed.then(() => {
       if (watch.answered !== answered) return;
-      clearTimeout(answered.timer as never);
+      clearTimeout(answered.timer);
       watch.answered = undefined;
       answered.resolve();
     });
M core/mind-worker/src/context/catalog-watch.test.ts
@@ -91,14 +91,18 @@
   },
 );
 
-test(
-  "one write is one batch for a session: a watcher of two queries gets both frames together",
+test.for([
+  { ends: "the mind's own Worker", path: "/page" },
+  { ends: "the boundary", path: "/" },
+])(
+  "one write is one batch for a session that ends in $ends: a watcher of three queries gets their frames together, the last one marked",
   { timeout: 60_000 },
-  async () => {
+  async ({ path }) => {
     await using runtime = await mind();
-    using itx = await session(runtime, "/page");
+    using itx = await session(runtime, path);
     await described(itx, "/tasks/one", { status: "open" });
     await listed(itx, { "/tasks/one": "open" });
+    await quiet(itx);
     const batches: string[][] = [];
     let batch: string[] = [];
     const take = (name: string) => (frame: CatalogFrame) => {
@@ -111,9 +115,40 @@
     using _open = await itx.contexts.watch({ where: { status: "open" } }, take("open"));
     using _byPath = await itx.contexts.watch({ under: "/tasks", order: "path" }, take("byPath"));
     using _key = await itx.contexts.watch({ keys: ["/tasks/one"] }, take("key"));
-    await described(itx, "/tasks/one", { status: "open", title: "Renamed" });
-    await until(() => batches.length > 0);
-    expect(batches[0]!.toSorted()).toEqual(["byPath", "key", "open"]);
+    // five writes, each of which changes all three answers
+    for (let round = 1; round <= 5; round++) {
+      await described(itx, "/tasks/one", { status: "open", title: `Renamed ${round}` });
+      await listed(itx, { "/tasks/one": "open" });
+      await quiet(itx);
+    }
+    await until(() => batches.length >= 5 && batch.length === 0);
+    // every batch is whole: no frame of one write came after the frame that ends its batch
+    expect(batches.map((frames) => frames.toSorted())).toEqual(
+      batches.map(() => ["byPath", "key", "open"]),
+    );
+  },
+);
+
+test.for([
+  { ends: "the mind's own Worker", path: "/page" },
+  { ends: "the boundary", path: "/" },
+])(
+  "a session that ends in $ends: the dispose of a watch's handle takes its query off the catalog, and the others stay",
+  { timeout: 60_000 },
+  async ({ path }) => {
+    await using runtime = await mind();
+    using itx = await session(runtime, path);
+    const queries = async () =>
+      (await itx.contexts.watches()).windows.map((window) => window.query).toSorted();
+    using _kept = await itx.contexts.watch({ limit: 5 }, () => {});
+    const gone = await itx.contexts.watch({ order: "path", limit: 7 }, () => {});
+    expect(await queries()).toEqual(['{"p":[],"o":"active","l":5}', '{"p":[],"o":"path","l":7}']);
+    gone[Symbol.dispose]();
+    await until(async () => (await queries()).length === 1);
+    expect(await itx.contexts.watches()).toMatchObject({
+      sockets: 1,
+      windows: [{ query: '{"p":[],"o":"active","l":5}', watchers: 1 }],
+    });
   },
 );