iterate.com / kernel

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

kernel-fresh-attempt into main

kernel-fresh-attempt adds 1 commit to main.

main has moved since kernel-fresh-attempt last had it. To merge: merge main into kernel-fresh-attempt, and push.

Sign in to open a pull.

Commits

Files

3 files changed

M core/itx/src/iterate-context-durable-object.ts
@@ -1055,10 +1055,14 @@
       ...this.#durableAlarmDeadlines(),
       ...Object.values(this.#residency.deadlines()),
       ...[...this.#runsOwedToTheAlarm.values()].map(({ requestedAt }) => requestedAt),
+      this.#subscriptionDelivery.pushesOwedToTheAlarmAt(),
       // until the catalog has answered all that this context said of itself (context/awake.ts)
       this.#awakeSocket.recoverAt(),
     ],
-    held: () => this.#residency.holdsResident() || this.#runsOwedToTheAlarm.size > 0,
+    held: () =>
+      this.#residency.holdsResident() ||
+      this.#runsOwedToTheAlarm.size > 0 ||
+      this.#subscriptionDelivery.pushesOwedToTheAlarmAt() !== null,
     // The prd fault alarm's pin (PINNED_WORKAROUNDS) counts the re-arm warning.
     onOverdue: ({ armedAt, overdueMs, action, rearms }) => {
       const detail = {
@@ -1325,6 +1329,17 @@
     this.#measureSize();
     const { armedAt: fired } = this.#alarmCoordinator.snapshot();
     const wokeAt = Date.now();
+    // First, while the alarm is this context's newest request: the pushes that waited for a fresh
+    // invocation start now (subscription-delivery.ts `#nextAlarmPass`).
+    const pushesWaited = this.#subscriptionDelivery.alarmPassStarted();
+    try {
+      await this.#alarmPass(fired, wokeAt, pushesWaited);
+    } finally {
+      this.#subscriptionDelivery.alarmPassEnded();
+    }
+  }
+
+  async #alarmPass(fired: number | null, wokeAt: number, pushesWaited: boolean): Promise<void> {
     // A run a dead incarnation left open is settled by this incarnation's wake record.
     const wakeRecordSettlesARun =
       !this.#stream.wakeRecorded() &&
@@ -1334,6 +1349,7 @@
     );
     if (
       this.#runsOwedToTheAlarm.size === 0 &&
+      !pushesWaited &&
       !wakeRecordSettlesARun &&
       !(schedule || delivery || facetClaim)
     ) {
M core/itx/src/stream/facet-push-catch-up.test.ts
@@ -329,5 +329,60 @@
   };
 }
 
+// WHAT A PROCESSOR APPENDED WAITS FOR THE ALARM. Cloudflare counts a context's call from its newest
+// incoming request, so a push inside a facet's own append is 2 deeper than the push before it.
+const BY_A_PROCESSOR = { processor: { slug: "counter", version: "1" } };
+const turns = async () => {
+  for (let turn = 0; turn < 20; turn++) await Promise.resolve();
+};
+
+test("what a processor appended is pushed to a facet in the next alarm pass, not in its commit", async () => {
+  using context = await contextWithCounterFacet();
+  const offset = context.stream.append({ type: TICKED, source: BY_A_PROCESSOR })[0]!.offset;
+  await turns();
+  expect(context.trace()).toEqual([]);
+  expect(context.delivery.pushesOwedToTheAlarmAt()).toBe(Date.now());
+
+  expect(context.delivery.alarmPassStarted()).toBe(true);
+  context.delivery.alarmPassEnded();
+  await context.settled();
+  expect(context.trace()).toEqual([`event ${offset}`, "at head: 1 ticks"]);
+  expect(context.delivery.pushesOwedToTheAlarmAt()).toBeNull();
+});
+
+test("what is appended while a push waits for the alarm rides the same pass, in order and once", async () => {
+  using context = await contextWithCounterFacet();
+  const first = context.stream.append({ type: TICKED, source: BY_A_PROCESSOR })[0]!.offset;
+  const second = context.tick();
+  const third = context.stream.append({ type: TICKED, source: BY_A_PROCESSOR })[0]!.offset;
+  await turns();
+  expect(context.trace()).toEqual([]);
+
+  expect(context.delivery.alarmPassStarted()).toBe(true);
+  context.delivery.alarmPassEnded();
+  await context.settled();
+  expect(context.trace()).toEqual([
+    `event ${first}`,
+    `event ${second}`,
+    `event ${third}`,
+    "at head: 3 ticks",
+  ]);
+  expect(context.delivery.alarmPassStarted()).toBe(false);
+});
+
+test("an alarm pass holds no push that its own work causes: the pass may wait for the facet", async () => {
+  using context = await contextWithCounterFacet();
+  expect(context.delivery.alarmPassStarted()).toBe(false);
+  const offset = context.stream.append({ type: TICKED, source: BY_A_PROCESSOR })[0]!.offset;
+  await context.settled();
+  expect(context.trace()).toEqual([`event ${offset}`, "at head: 1 ticks"]);
+  context.delivery.alarmPassEnded();
+
+  context.stream.append({ type: TICKED, source: BY_A_PROCESSOR });
+  await turns();
+  expect(context.trace()).toHaveLength(2);
+  expect(context.delivery.pushesOwedToTheAlarmAt()).not.toBeNull();
+});
+
 // the kernel's reducer reads the host's roots when it resolves a row's target
 defineItxHost({ firstPartyFacets: {} });
M core/itx/src/stream/subscription-delivery.ts
@@ -82,6 +82,8 @@
   range: ScannedRange;
   chars?: number;
   droppedEvents: number;
+  // Holds what a processor appended: pushed in the next alarm pass (`#nextAlarmPass`).
+  fresh?: true;
 };
 
 const serializedChars = (events: StreamEvent[]): number =>
@@ -219,6 +221,8 @@
   readonly #cursorDeliveryLoops = new Map<string, Promise<void>>();
   readonly #deliveryCharsInFlight = new DeliveryCharsBudget(DELIVERY_IN_FLIGHT_BUDGET_CHARS);
   readonly #cursorReadCharsInFlight = new DeliveryCharsBudget(CURSOR_READ_BUDGET_CHARS);
+  #alarmPassOwed: { started: Promise<void>; start: () => void; owedAt: number } | undefined;
+  #alarmPassInProgress = false;
 
   constructor(deps: SubscriptionDeliveryDeps) {
     this.#stream = deps.stream;
@@ -297,11 +301,47 @@
     return owed && { ...owed, at: now };
   }
 
+  // WHAT A PROCESSOR APPENDED IS PUSHED TO FACETS IN THE NEXT ALARM PASS, a fresh invocation.
+  // Cloudflare allows 16 nested calls, and a Durable Object's call counts from its newest incoming
+  // request, whichever request caused the call (measured on 28 Nov 2026). A push inside the commit
+  // counts from the facet's own append, so each round "a facet appends, the context pushes" went 2
+  // deeper, and only an alarm or a shallower caller brought it back. An alarm starts at 0. A push
+  // that a pass itself causes is not held: the pass waits for facets, and it is at most 2 deep.
+  #nextAlarmPass(): Promise<void> | undefined {
+    if (this.#alarmPassInProgress) return undefined;
+    if (!this.#alarmPassOwed) {
+      const { promise, resolve } = Promise.withResolvers<void>();
+      this.#alarmPassOwed = { started: promise, start: resolve, owedAt: Date.now() };
+      this.#reconcileAlarm();
+    }
+    return this.#alarmPassOwed.started;
+  }
+
+  // The alarm's claim for the pushes that wait for its pass. Memory alone: a facet that an
+  // incarnation's end left behind reads from the log at its next push, as after any lost push.
+  pushesOwedToTheAlarmAt(): number | null {
+    return this.#alarmPassOwed?.owedAt ?? null;
+  }
+
+  // The alarm's pass, at its start. Answers whether a push waited for it.
+  alarmPassStarted(): boolean {
+    const owed = this.#alarmPassOwed;
+    this.#alarmPassOwed = undefined;
+    this.#alarmPassInProgress = true;
+    owed?.start();
+    return !!owed;
+  }
+
+  alarmPassEnded(): void {
+    this.#alarmPassInProgress = false;
+  }
+
   // Answers whether it may have written a claim in this turn, which the commit's alarm reconcile arms.
   onCommit(freshEvents: StreamEvent[], afterOffset: number, throughOffset: number): boolean {
     const state = this.#stream.coreReducedState;
     const rows = state.subscriptions;
     const durable = freshEvents.some((event) => !event.ephemeral);
+    const fromAProcessor = (event: StreamEvent) => !event.ephemeral && !!event.source?.processor;
     let mayHaveClaimed = false;
     for (const event of freshEvents) {
       switch (event.type) {
@@ -361,7 +401,14 @@
         if (events.length === 0) continue;
         const after = record.lastDeliveredThroughOffset ?? afterOffset;
         record.lastDeliveredThroughOffset = throughOffset;
-        this.#queuePushBehindInFlightDelivery(name, events, { after, through: throughOffset });
+        // A client's callback is no part of a loop of turns: it is pushed in the commit, as before.
+        const fresh = events.some(fromAProcessor) && !targetIsLentCallback(state, row);
+        this.#queuePushBehindInFlightDelivery(
+          name,
+          events,
+          { after, through: throughOffset },
+          fresh,
+        );
         continue;
       }
       if (row.ordered === false) {
@@ -417,19 +464,28 @@
     }
   }
 
-  #queuePushBehindInFlightDelivery(name: string, events: StreamEvent[], range: ScannedRange): void {
+  #queuePushBehindInFlightDelivery(
+    name: string,
+    events: StreamEvent[],
+    range: ScannedRange,
+    fresh = false,
+  ): void {
     const record = this.#deliveryRecordFor(name);
     const pending = record.pendingPush;
     if (pending) {
+      if (fresh) pending.fresh = true;
       pending.chars = (pending.chars ?? serializedChars(pending.events)) + serializedChars(events);
       pending.events = pending.events.concat(events); // the old array may be an in-flight call's argument
       pending.range.through = range.through;
       this.#dropPendingEventsOverTotalBudget();
       return;
     }
-    record.pendingPush = { events, range, droppedEvents: 0 };
+    record.pendingPush = { events, range, droppedEvents: 0, ...(fresh && { fresh }) };
     record.deliveryChain = record.deliveryChain
       .then(async () => {
+        // Asked here, not at the commit: a batch that joined while the row's delivery was out
+        // counts too, and what joins during the wait rides the same pass.
+        if (this.#deliveryRecordByName.get(name)?.pendingPush?.fresh) await this.#nextAlarmPass();
         const current = this.#deliveryRecordByName.get(name);
         const push = current?.pendingPush;
         if (current) current.pendingPush = undefined;