You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/09 01:30:07 UTC

(maka) branch fix/daily-review-host-handoff created (now f4c8515421)

This is an automated email from the ASF dual-hosted git repository.

M4n5ter pushed a change to branch fix/daily-review-host-handoff
in repository https://gitbox.apache.org/repos/asf/maka.git


      at f4c8515421 fix(runtime-host): include daily review in safe host handoff

This branch includes the following new commits:

     new f4c8515421 fix(runtime-host): include daily review in safe host handoff

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


(maka) 01/01: fix(runtime-host): include daily review in safe host handoff

Posted by wy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

M4n5ter pushed a commit to branch fix/daily-review-host-handoff
in repository https://gitbox.apache.org/repos/asf/maka.git

commit f4c8515421ef78ee5b5adb2e43cc55b7015d4f90
Author: M4n5ter <m4...@gmail.com>
AuthorDate: Wed Sep 9 09:27:34 2026 +0800

    fix(runtime-host): include daily review in safe host handoff
    
    Pause Daily Review scheduling during cooperative handoff, wait for active generation, and restore scheduling on cancellation or successor recovery. Track generation separately so completed work can unblock automatic retries.
    
    Generated-by: OpenAI Codex
---
 .../src/__tests__/daily-review-coordinator.test.ts | 125 +++++++++++++++++++++
 .../src/__tests__/execution-composition.test.ts    |  52 +++++++++
 .../src/server/daily-review-coordinator.ts         |  73 +++++++++++-
 .../src/server/execution-composition.ts            |  15 ++-
 4 files changed, 256 insertions(+), 9 deletions(-)

diff --git a/packages/runtime-host/src/__tests__/daily-review-coordinator.test.ts b/packages/runtime-host/src/__tests__/daily-review-coordinator.test.ts
index 6eb94115c2..4571e2dd3b 100644
--- a/packages/runtime-host/src/__tests__/daily-review-coordinator.test.ts
+++ b/packages/runtime-host/src/__tests__/daily-review-coordinator.test.ts
@@ -22,6 +22,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
 import { tmpdir } from 'node:os';
 import { join } from 'node:path';
 import { test } from 'node:test';
+import { deferred, waitFor } from '@maka/core/test-only/async-primitives';
 import {
   dailyReviewArchiveId,
   localDayBoundsAt,
@@ -34,6 +35,7 @@ import { resolveStorageRoot, tryAcquireInteractiveRootOwner } from '@maka/storag
 import { openInteractiveUsageStoresForWrite } from '@maka/storage/usage-stores';
 import type { ConnectionContext } from '../server/operation-dispatcher.js';
 import { HostDailyReviewCoordinator } from '../server/daily-review-coordinator.js';
+import { HostResidencyRegistry } from '../server/host-residency-registry.js';
 
 const CONTEXT: ConnectionContext = {
   hostEpoch: 'host-epoch',
@@ -42,6 +44,122 @@ const CONTEXT: ConnectionContext = {
   acquireResidency: () => ({ release: () => undefined }),
 };
 
+test('Daily Review handoff fences an admitted timer tick and cancellation resumes a due review', async () => {
+  let now = new Date(2026, 8, 9, 12).getTime();
+  const timers = new Set<() => void>();
+  const residencies = new HostResidencyRegistry();
+  await withCoordinator(
+    async ({ coordinator, store }) => {
+      const snapshot = await store.readConfig();
+      await store.updateConfig(snapshot.revision, {
+        enabled: true,
+        executeTime: '13:00',
+        modelKey: '',
+      });
+      await coordinator.recover();
+      assert.equal(timers.size, 1);
+      assert.equal(residencies.drainCount, 1);
+      const tick = [...timers][0]!;
+      now = new Date(2026, 8, 9, 13).getTime();
+      tick(); // The config read has started, but has not returned yet.
+      const hold = coordinator.holdForHandoff();
+      assert.ok(hold);
+      assert.equal(coordinator.holdForHandoff(), undefined);
+      assert.equal(timers.size, 0);
+      tick(); // A callback already queued before clearInterval must also be fenced.
+      await hold.settled();
+      const archiveId = dailyReviewArchiveId(localDayBoundsAt(now, -1), 1);
+      assert.equal(await store.getArchive(archiveId), null);
+      const proof = hold.residencies();
+      assert.ok(proof);
+      assert.equal(residencies.hasDrainResidenciesExcept(proof), false);
+      hold.release();
+      hold.release();
+      assert.equal(timers.size, 1);
+      await waitFor(async () => (await store.getArchive(archiveId)) !== null);
+      assert.equal((await store.getArchive(archiveId))?.trigger, 'cron');
+      assert.equal((await store.readConfig()).config.enabled, true);
+      const next = coordinator.holdForHandoff();
+      assert.ok(next);
+      await next.settled();
+      coordinator.beginDrain();
+      next.release();
+      assert.equal(timers.size, 0);
+      assert.equal(residencies.drainCount, 0);
+    },
+    undefined,
+    false,
+    undefined,
+    {
+      now: () => now,
+      acquireResidency: () => residencies.acquire('daily-review'),
+      setInterval: (callback) => {
+        timers.add(callback);
+        return callback;
+      },
+      clearInterval: (timer) => {
+        timers.delete(timer as () => void);
+      },
+    },
+  );
+});
+
+test('Daily Review handoff waits for an active analysis to publish without interrupting it', async () => {
+  const entered = deferred<void>();
+  const finish = deferred<void>();
+  const residencies = new HostResidencyRegistry();
+  await withCoordinator(
+    async ({ coordinator, store }) => {
+      const running = coordinator.handlers['daily-review.mutate'](
+        {
+          kind: 'run',
+          range: 1,
+          offsetDays: 0,
+          modelKeyOverride: '',
+          replaceExisting: false,
+        },
+        CONTEXT,
+      );
+      await entered.promise;
+      assert.equal(residencies.drainCount, 1);
+      const hold = coordinator.holdForHandoff();
+      assert.ok(hold);
+      try {
+        assert.equal(hold.residencies(), undefined);
+        let settled = false;
+        const waiting = hold.settled().then(() => {
+          settled = true;
+        });
+        await new Promise<void>((resolve) => setImmediate(resolve));
+        assert.equal(settled, false);
+        finish.resolve();
+        const result = await running;
+        await waiting;
+        assert.equal(result.ok, true);
+        assert.ok(hold.residencies());
+        assert.equal(residencies.drainCount, 0);
+        assert.equal((await store.listArchivePage(null, 1)).archives.length, 1);
+      } finally {
+        finish.resolve();
+        hold.release();
+        await running;
+      }
+    },
+    undefined,
+    true,
+    {
+      list: async () => {
+        entered.resolve();
+        await finish.promise;
+        return [];
+      },
+    },
+    {
+      acquireResidency: () => residencies.acquire('daily-review'),
+    },
+  );
+});
+
 test('Daily Review refuses to archive an incomplete canonical Usage projection', async () => {
   await withCoordinator(async ({ coordinator, store, root, drainCount }) => {
     appendCorruptAuthorityEvent(root, 'session-missing', 'run-missing');
@@ -401,6 +519,12 @@ async function withCoordinator(
   sessions: ConstructorParameters<typeof HostDailyReviewCoordinator>[0]['sessions'] = {
     list: async () => [],
   },
+  lifecycle: Partial<
+    Pick<
+      ConstructorParameters<typeof HostDailyReviewCoordinator>[0],
+      'now' | 'acquireResidency' | 'setInterval' | 'clearInterval'
+    >
+  > = {},
 ): Promise<void> {
   const base = await mkdtemp(join(tmpdir(), 'maka-daily-review-coordinator-'));
   const root = join(base, 'interactive');
@@ -423,6 +547,7 @@ async function withCoordinator(
     requestDrain: () => {
       drains += 1;
     },
+    ...lifecycle,
   });
   try {
     if (recoverBeforeRun) await coordinator.recover();
diff --git a/packages/runtime-host/src/__tests__/execution-composition.test.ts b/packages/runtime-host/src/__tests__/execution-composition.test.ts
index fef1a5020a..edac7361b0 100644
--- a/packages/runtime-host/src/__tests__/execution-composition.test.ts
+++ b/packages/runtime-host/src/__tests__/execution-composition.test.ts
@@ -60,6 +60,7 @@ import {
   type InteractiveRootOwner,
 } from '@maka/storage/root-authority';
 import { openInteractiveUsageStoresForWrite } from '@maka/storage/usage-stores';
+import { openInteractiveDailyReviewAuthorityForWrite } from '@maka/storage/daily-review-authority';
 import { openInteractiveShellRunStoreForWrite } from '@maka/storage/shell-run-authority';
 import { openInteractiveRuntimePolicyStoresForWrite } from '@maka/storage/runtime-policy-stores';
 import { HostResidencyRegistry } from '../server/host-residency-registry.js';
@@ -87,6 +88,57 @@ const HANDOFF_TEST_COMPOSITION = createRunCompositionSnapshot({
   contextWindow: null,
 });
 
+test('an idle enabled Daily Review scheduler participates in production handoff and recovers in the successor', {
+  timeout: 20_000,
+}, async () => {
+  await withCompositionRoot(async ({ root, owner }) => {
+    const store = await openInteractiveDailyReviewAuthorityForWrite(owner.lease);
+    const snapshot = await store.readConfig();
+    await store.updateConfig(snapshot.revision, {
+      enabled: true,
+      executeTime: '00:00',
+      modelKey: '',
+    });
+    const residencies = new HostResidencyRegistry();
+    const { composition } = await createCapturedExecutionComposition(owner, { residencies });
+    try {
+      assert.deepEqual(residencies.snapshot(), [{ label: 'daily-review', count: 1 }]);
+      const cancelled = await composition.prepareHandoff!('old-host', new AbortController().signal);
+      assert.ok(cancelled);
+      assert.equal(await cancelled.seal(), true);
+      const cancelledProof = await cancelled.residencies();
+      assert.ok(cancelledProof);
+      assert.equal(residencies.hasDrainResidenciesExcept(cancelledProof), false);
+      cancelled.cancel();
+      const prepared = await composition.prepareHandoff!('old-host', new AbortController().signal);
+      assert.ok(prepared);
+      assert.equal(await prepared.seal(), true);
+      const proof = await prepared.residencies();
+      assert.ok(proof);
+      assert.equal(residencies.hasDrainResidenciesExcept(proof), false);
+      await prepared.detach();
+    } finally {
+      await composition.close();
+    }
+    assert.equal(residencies.activeCount, 0);
+    await owner.close();
+    const successorOwner = await tryAcquireInteractiveRootOwner(
+      await resolveStorageRoot({ path: root, kind: 'interactive' }),
+    );
+    assert.ok(successorOwner);
+    try {
+      const successor = await createCapturedExecutionComposition(successorOwner, { residencies });
+      try {
+        assert.deepEqual(residencies.snapshot(), [{ label: 'daily-review', count: 1 }]);
+      } finally {
+        await successor.composition.close();
+      }
+    } finally {
+      await successorOwner.close();
+    }
+  });
+});
+
 test('production composition resumes a sealed logical Root after all stores and runtime owners reopen', {
   timeout: 20_000,
 }, async () => {
diff --git a/packages/runtime-host/src/server/daily-review-coordinator.ts b/packages/runtime-host/src/server/daily-review-coordinator.ts
index 2d62df383f..cbe0b1f2b2 100644
--- a/packages/runtime-host/src/server/daily-review-coordinator.ts
+++ b/packages/runtime-host/src/server/daily-review-coordinator.ts
@@ -103,6 +103,8 @@ export class HostDailyReviewCoordinator {
   #prepared = false;
   #started = false;
   #schedulerEnabled = false;
+  #handoffHeld = false;
+  #schedulerTask: Promise<void> | undefined;
   #draining = false;
   #timer: unknown;
   #residency: RuntimeHostResidency | undefined;
@@ -156,10 +158,51 @@ export class HostDailyReviewCoordinator {
     }
   }
 
+  holdForHandoff():
+    | {
+        settled(): Promise<void>;
+        residencies(): readonly RuntimeHostResidency[] | undefined;
+        release(): void;
+      }
+    | undefined {
+    if (this.#draining || this.#handoffHeld) return undefined;
+    this.#handoffHeld = true;
+    this.#stopTimer();
+    let released = false;
+    return {
+      settled: async () => {
+        // Include scheduler reads as well as generation: a tick may still be
+        // checking configuration or an archive when the hold is acquired.
+        while (this.#schedulerTask || this.#inFlight.size > 0) {
+          await Promise.allSettled([
+            this.#schedulerTask,
+            ...[...this.#inFlight.values()].map((entry) => entry.promise),
+          ]);
+        }
+      },
+      residencies: () => {
+        if (released || this.#draining || this.#schedulerTask || this.#inFlight.size > 0)
+          return undefined;
+        return this.#residency ? [this.#residency] : [];
+      },
+      release: () => {
+        if (released) return;
+        released = true;
+        this.#handoffHeld = false;
+        if (this.#draining) return;
+        this.#reconcileScheduler(this.#schedulerEnabled);
+        void this.#tickScheduler().catch((error: unknown) => this.#handleSchedulerError(error));
+      },
+    };
+  }
+
   close(): Promise<void> {
     this.#closeTask ??= (async () => {
       this.beginDrain();
-      await Promise.allSettled([...this.#inFlight.values()].map((entry) => entry.promise));
+      await Promise.allSettled([
+        this.#schedulerTask,
+        ...[...this.#inFlight.values()].map((entry) => entry.promise),
+      ]);
     })();
     return this.#closeTask;
   }
@@ -315,6 +358,10 @@ export class HostDailyReviewCoordinator {
       await inFlight.promise.catch(() => undefined);
       return this.#run(input);
     }
+    // Keep actual generation distinct from the idle scheduler hold. Besides
+    // protecting a run when scheduling is disabled, its release tells handoff
+    // observers that work finished after a bounded safe-pause attempt timed out.
+    const residency = this.#acquireResidency();
     const pending = this.#generateArchive(archiveId, day, now, modelKeyOverride, input);
     const entry = {
       modelKeyOverride,
@@ -327,6 +374,7 @@ export class HostDailyReviewCoordinator {
       return await pending;
     } finally {
       if (this.#inFlight.get(archiveId) === entry) this.#inFlight.delete(archiveId);
+      residency.release();
     }
   }
 
@@ -426,10 +474,12 @@ export class HostDailyReviewCoordinator {
   }
 
   #reconcileScheduler(enabled: boolean): void {
+    this.#schedulerEnabled = enabled;
     if (!enabled || this.#draining) {
       this.#stopScheduler();
       return;
     }
+    if (this.#handoffHeld) return;
     this.#residency ??= this.#acquireResidency();
     this.#timer ??= this.#setInterval(() => {
       void this.#tickScheduler().catch((error: unknown) => this.#handleSchedulerError(error));
@@ -437,17 +487,29 @@ export class HostDailyReviewCoordinator {
   }
 
   #stopScheduler(): void {
+    this.#stopTimer();
+    this.#residency?.release();
+    this.#residency = undefined;
+  }
+
+  #stopTimer(): void {
     if (this.#timer !== undefined) {
       this.#clearInterval(this.#timer);
       this.#timer = undefined;
     }
-    this.#residency?.release();
-    this.#residency = undefined;
   }
 
-  async #tickScheduler(): Promise<void> {
-    if (!this.#prepared || this.#draining) return;
+  #tickScheduler(): Promise<void> {
+    if (!this.#prepared || this.#draining || this.#handoffHeld) return Promise.resolve();
+    this.#schedulerTask ??= this.#runScheduler().finally(() => {
+      this.#schedulerTask = undefined;
+    });
+    return this.#schedulerTask;
+  }
+
+  async #runScheduler(): Promise<void> {
     const { config } = await this.#store.readConfig();
+    if (this.#draining || this.#handoffHeld) return;
     this.#reconcileScheduler(config.enabled);
     const now = this.#now();
     if (!config.enabled || !scheduledTimeHasPassed(now, config.executeTime)) return;
@@ -456,6 +518,7 @@ export class HostDailyReviewCoordinator {
     const day = localDayBoundsAt(now, -1);
     const archiveId = dailyReviewArchiveId(day, 1);
     if (await this.#store.getArchive(archiveId)) return;
+    if (this.#draining || this.#handoffHeld) return;
     await this.#run({
       range: 1,
       offsetDays: -1,
diff --git a/packages/runtime-host/src/server/execution-composition.ts b/packages/runtime-host/src/server/execution-composition.ts
index f098c3ab81..4244946b56 100644
--- a/packages/runtime-host/src/server/execution-composition.ts
+++ b/packages/runtime-host/src/server/execution-composition.ts
@@ -2127,6 +2127,7 @@ export async function createExecutionRuntimeHostComposition(
         if (draining || signal.aborted) return undefined;
         const goalHold = goal?.holdForHandoff();
         const scheduleHold = scheduledTasks?.holdForHandoff();
+        const dailyReviewHold = dailyReview?.holdForHandoff();
         let root: Awaited<ReturnType<RootTurnCoordinator['prepareHandoff']>>;
         let detached = false;
         const cancel = () => {
@@ -2134,16 +2135,21 @@ export async function createExecutionRuntimeHostComposition(
           root?.cancel();
           goalHold?.release();
           scheduleHold?.release();
+          dailyReviewHold?.release();
           signal.removeEventListener('abort', cancel);
         };
         signal.addEventListener('abort', cancel, { once: true });
         try {
-          if (!goalHold || !scheduleHold) {
+          if (!goalHold || !scheduleHold || !dailyReviewHold) {
             cancel();
             return undefined;
           }
           await waitForHostedExecutionIdleOrAbort(
-            Promise.all([goalHold.settled(), scheduleHold.settled()]).then(() => undefined),
+            Promise.all([
+              goalHold.settled(),
+              scheduleHold.settled(),
+              dailyReviewHold.settled(),
+            ]).then(() => undefined),
             signal,
           );
           root = await requireRootCoordinator(coordinator).prepareHandoff(hostEpoch, signal);
@@ -2158,8 +2164,9 @@ export async function createExecutionRuntimeHostComposition(
               await waitForHostedExecutionIdleOrAbort(scheduleHold.settled(), signal);
               const goals = await goalHold.residencies(prepared.executions);
               const roots = await prepared.residencies();
-              if (!goals || !roots || signal.aborted || draining) return undefined;
-              return [...roots, ...goals, ...scheduleHold.residencies()];
+              const reviews = dailyReviewHold.residencies();
+              if (!goals || !roots || !reviews || signal.aborted || draining) return undefined;
+              return [...roots, ...goals, ...scheduleHold.residencies(), ...reviews];
             },
             detach: async () => {
               detached = true;


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org