You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "chihumyum (via GitHub)" <gi...@apache.org> on 2026/10/06 17:13:36 UTC

[PR] fix(runtime): apply graph stops while child work is running [maka]

chihumyum opened a new pull request, #5977:
URL: https://github.com/apache/maka/pull/5977

   ## Summary
   
   A durable `update_agent_graph.stop` now reaches a running child while its dispatch wave is still active. Schedule changes wake the existing reconciliation owner to apply controls, while the original wave retains its results, admission fences, and activation budget.
   
   Stops carry the selected Session/Run/Turn identity through SessionManager, the Hosted root authority, and the Runtime backend owner. Queued sibling work and later activations remain intact; successful cleanup releases the existing Session queue. Global Session stop keeps its broader cancellation behavior.
   
   ## Verification
   
   - Added a real SessionManager regression that failed before the fix: a committed stop timed out while the child's natural-completion gate remained closed.
   - Regression coverage includes multiple running children, queued work on one Session, new work after stop, concurrent natural completion, durable terminal/result uniqueness, coordinator recovery, missed-wake windows, repeated schedule wakes, and transient control/cleanup failures.
   - Hosted fixtures verify that the durable Host stop fence precedes backend stop and that scoped and global stops preserve their respective target boundaries.
   - Affected runtime, AgentRun recovery/continuation, Graph, and Hosted root suites: 472 passed.
   - Root lint, format, build, typecheck, both required knip checks, strict renderer architecture checks, Astryx inventory/tests, ASF headers, and model metadata checks passed.
   - Host delivery faults still follow the existing fail-stop/drain policy; this change does not promise in-place recovery from every provider or Host failure.
   - Providers are in-memory fixtures; no real model inference or Desktop interaction was exercised for this change.
   
   ## AI use
   
   - [ ] No generative tool made a substantive contribution
   - [x] Generative tooling made a substantive contribution
   
   Tool(s) and scope: OpenAI Codex (GPT-6 Astra) investigated the defect, compared cancellation designs, and authored the implementation and regression tests.
   
   ## Checklist
   
   - [x] Tests cover the change and fail without it
   - [x] Lint, format, typecheck and the affected suites pass locally
   
   Does this PR entail a change in behavior?
   
   - [x] Yes — described under Summary above
   - [ ] No
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "chihumyum (via GitHub)" <gi...@apache.org>.
chihumyum commented on PR #5977:
URL: https://github.com/apache/maka/pull/5977#issuecomment-6054758074

   Added two test-only pins for the remaining gaps (38a632d9f):
   - **Non-cooperative backend:** when one provider never returns from `stop()`, its sibling's stop in the same pass still reaches its aborted terminal right away. Making the stops run one at a time fails this test.
   - **Quarantine:** a retained stop operation refuses an unrelated Turn on that Session until a retry settles the cleanup.
   
   A stale stop intent paired with a retained operation can't be built through the public API. stopSessionAttempt clears a Session intent only after every claim it holds has settled, and a scoped intent belongs to one claim for that claim's whole life. So that side is covered by reasoning rather than a test. A restart test is out of scope for this PR.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4214233723


##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -413,15 +465,60 @@ export async function reconcileAgentGraphSchedule(
       );
     }
 
-    const outcomes = await Promise.all(
+    let waveSettled = false;
+    const wave = Promise.all(
       prepared.map(async (work) => {
         const outcome = await dispatchScheduledWork(input, work, snapshot.schedule.revision);
         if (outcome.status === 'rejected') {
           notifySupervisor(input.supervisor?.onReconciliationFailure, outcome.failure);
         }
         return outcome;
       }),
-    );
+    ).finally(() => {
+      waveSettled = true;
+      wake.notify();
+    });
+    let controlReadFailure: AgentGraphScheduleReconciliationFailure | undefined;
+    let retryTimer: ReturnType<typeof setTimeout> | undefined;
+    let retryDelay = CONTROL_RETRY_INITIAL_DELAY_MS;
+    try {
+      while (!waveSettled) {
+        await wake.wait();
+        clearTimeout(retryTimer);
+        retryTimer = undefined;
+        if (waveSettled || input.abortSignal?.aborted) break;
+        let retry: boolean;
+        try {
+          const latest = await readScheduleSnapshot(input, selectedResultCache);
+          const controls = await applyScheduleStops(input, latest, resolvedStops);
+          recordScheduleStops(input, stops, failures, controls);
+          if (controlReadFailure) {
+            failures.splice(failures.indexOf(controlReadFailure), 1);
+            controlReadFailure = undefined;
+          }
+          retry = controls.failures.length > 0;
+        } catch (error) {
+          if (controlReadFailure) failures.splice(failures.indexOf(controlReadFailure), 1);
+          controlReadFailure = { phase: 'schedule', error };
+          recordReconciliationFailure(input, failures, controlReadFailure);
+          retry = true;
+        }
+        // A failed stop can keep its child, and so this wave, parked until a
+        // retry succeeds. Back off instead of waiting for another commit.
+        if (retry) {
+          retryTimer = setTimeout(wake.notify, retryDelay);

Review Comment:
   **P3.** The backoff caps the rate but not the count. If cleanup for a stopped child keeps failing, this retries every 5 s for as long as the wave lives, and the wave can't settle while that child's claim release is waiting on the retained operation. In hosted mode each retry is a full `stopRoot` through `runCommand`, and unexpected Host errors there request a drain. Driver abort still breaks the loop but then waits on the parked `wave` in `finally`. Could you cap the attempts, or after N failures surface a distinct 'stop cleanup stuck' state to the supervisor, so the graph doesn't sit silently parked behind one failure record?



##########
packages/runtime/src/message-authority.ts:
##########
@@ -60,10 +60,23 @@ export interface RuntimeHostedRootExecutionInput extends RuntimeMessageRunIdenti
   readonly onReady?: () => void | Promise<void>;
 }
 
+/**
+ * `run` delivers the Runtime stop to this exact Run's owner only, for an
+ * activation-scoped graph stop. The default stops the Session's live
+ * execution, including a claim that has not attached its Run yet.
+ */
+export interface RuntimeHostedRootStopOptions {
+  readonly scope?: 'session' | 'run';
+}
+
 /** Host-only root lifecycle capability. Embedded compositions must omit it. */
 export interface RuntimeHostedRootAuthority extends RuntimeMessageAuthority {
   executeRoot(input: RuntimeHostedRootExecutionInput): Promise<void>;
-  stopRoot(identity: RuntimeMessageRunIdentity, input?: StopSessionInput): Promise<void>;
+  stopRoot(
+    identity: RuntimeMessageRunIdentity,
+    input?: StopSessionInput,
+    options?: RuntimeHostedRootStopOptions,

Review Comment:
   **P3.** An authority implementation that ignores the third argument still satisfies this interface. TypeScript accepts a function with fewer parameters, so even a required `options` wouldn't catch it. Graph activation stops would then silently widen to a Session stop (you list this as a residual risk). A distinct method on `RuntimeHostedRootAuthority`, e.g. `stopRootRun(identity, input)`, would make a missing exact-Run implementation a compile error. Alternatively, a Host test through the real composition (`execution-composition.ts:1243`) could assert that a graph activation stop leaves a sibling claim on the same Session running.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "chihumyum (via GitHub)" <gi...@apache.org>.
chihumyum commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4213600319


##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -665,12 +758,18 @@ async function applyScheduleStops(
       ? activationTargets.get(claim.targetRunId)
       : activationTargets.get(targetId);
     if (activation && isTerminalActivationStatus(activation.status)) {
-      immediate.push({
+      // A durable terminal does not prove that backend cleanup succeeded.
+      // Exact stop is a no-op without a retained owner, and otherwise releases
+      // the same cleanup barrier before later work may use this operator.
+      targets.push({

Review Comment:
   Fixed in b2b9ff9a4: a terminal target reaches the runtime only while a failed stop still retains cleanup for that exact Run (hasPendingAgentGraphActivationStop). Stops already resolved in this reconciliation are skipped on later passes and wakes. Tests cover both.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -413,15 +453,46 @@ export async function reconcileAgentGraphSchedule(
       );
     }
 
-    const outcomes = await Promise.all(
+    let waveSettled = false;
+    const wave = Promise.all(
       prepared.map(async (work) => {
         const outcome = await dispatchScheduledWork(input, work, snapshot.schedule.revision);
         if (outcome.status === 'rejected') {
           notifySupervisor(input.supervisor?.onReconciliationFailure, outcome.failure);
         }
         return outcome;
       }),
-    );
+    ).finally(() => {
+      waveSettled = true;
+      wake.notify();
+    });
+    let controlReadFailure: AgentGraphScheduleReconciliationFailure | undefined;
+    try {
+      while (!waveSettled) {
+        await wake.wait();
+        if (waveSettled || input.abortSignal?.aborted) break;
+        try {
+          const latest = await readScheduleSnapshot(input, selectedResultCache);
+          const controls = await applyScheduleStops(input, latest);
+          recordScheduleStops(input, stops, failures, controls);
+          if (controlReadFailure) {
+            failures.splice(failures.indexOf(controlReadFailure), 1);
+            controlReadFailure = undefined;
+          }
+        } catch (error) {
+          if (controlReadFailure) failures.splice(failures.indexOf(controlReadFailure), 1);
+          controlReadFailure = { phase: 'schedule', error };
+          recordReconciliationFailure(input, failures, controlReadFailure);
+          // Keep consuming future control wakes while this wave still owns

Review Comment:
   Fixed in b2b9ff9a4: a failed control pass during a live wave schedules a backoff wake (100 ms, doubling, capped at 5 s), so a parked child's stop retries without another schedule commit. A repeated failure for the same target replaces the earlier one without notifying the supervisor again. Test added.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4199480553


##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -665,12 +758,18 @@ async function applyScheduleStops(
       ? activationTargets.get(claim.targetRunId)
       : activationTargets.get(targetId);
     if (activation && isTerminalActivationStatus(activation.status)) {
-      immediate.push({
+      // A durable terminal does not prove that backend cleanup succeeded.
+      // Exact stop is a no-op without a retained owner, and otherwise releases
+      // the same cleanup barrier before later work may use this operator.
+      targets.push({

Review Comment:
   P2: `stoppedTargets` and `replaces` are persistent, so this branch now runs a real `stopAgentGraphActivation` for every historical terminal target, on every reconcile attempt and every mid-wave wake. In Hosted mode that is an admission read plus a full `stopRoot` for each one: two admission lanes, a canonical snapshot read, a logical-execution read, and `listChildSessions` plus child stops. Before this PR the same branch was a free `already_terminal` result. Also, any failure here (a persistent cleanup failure on one operator, an identity mismatch, a Host error) makes the `failures.length > 0` check at the top of the loop return `failed` before any new dispatch. That wedges the whole graph, not just that operator. Could this skip targets already resolved in this reconciliation? It could also re-issue the stop only when the runtime still retains a stop operation or owner for that exact Run, or when a prior stop failure is recorded.



##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -413,15 +453,46 @@ export async function reconcileAgentGraphSchedule(
       );
     }
 
-    const outcomes = await Promise.all(
+    let waveSettled = false;
+    const wave = Promise.all(
       prepared.map(async (work) => {
         const outcome = await dispatchScheduledWork(input, work, snapshot.schedule.revision);
         if (outcome.status === 'rejected') {
           notifySupervisor(input.supervisor?.onReconciliationFailure, outcome.failure);
         }
         return outcome;
       }),
-    );
+    ).finally(() => {
+      waveSettled = true;
+      wake.notify();
+    });
+    let controlReadFailure: AgentGraphScheduleReconciliationFailure | undefined;
+    try {
+      while (!waveSettled) {
+        await wake.wait();
+        if (waveSettled || input.abortSignal?.aborted) break;
+        try {
+          const latest = await readScheduleSnapshot(input, selectedResultCache);
+          const controls = await applyScheduleStops(input, latest);
+          recordScheduleStops(input, stops, failures, controls);
+          if (controlReadFailure) {
+            failures.splice(failures.indexOf(controlReadFailure), 1);
+            controlReadFailure = undefined;
+          }
+        } catch (error) {
+          if (controlReadFailure) failures.splice(failures.indexOf(controlReadFailure), 1);
+          controlReadFailure = { phase: 'schedule', error };
+          recordReconciliationFailure(input, failures, controlReadFailure);
+          // Keep consuming future control wakes while this wave still owns

Review Comment:
   P2 (liveness): when scoped cleanup fails, `waitForExecutionStop` (session-manager.ts:2983) stays pending. The stopped child's dispatch then doesn't resolve, and `await wave` never settles. This loop retries only on another schedule wake, and the coordinator has no timer or backoff. If the stopped child was the only running work, nothing wakes the driver, and its drive (and anything awaiting `reconcile()`) stays stuck until an external action. Driver abort only breaks the loop; it still awaits the parked wave. Could a bounded backoff wake be scheduled after a `phase: 'stop'` failure while the wave is alive?



##########
packages/runtime/src/session-manager.ts:
##########
@@ -3149,6 +3199,9 @@ export class SessionManager {
     let aborted = false;
     let stopPromise: Promise<void> | undefined;
     const userMessageId = await this.claimedGraphUserMessageId(claim, input.hostedGraphExecution);
+    if (input.hostedGraphExecution && runtimeExecution.stopSignal.aborted)
+      throw runtimeExecution.stopSignal.reason;
+    input.onHostSubmission?.();

Review Comment:
   P2: `hostSubmitted` becomes true before `consumeLinkedRootExecution` makes the Host admission durable. A graph stop in that window does this: `readRootTurnAdmissionIdentity` returns none, so it calls `authority.stopRoot`. On the Host side, `declareStopFence` finds no active execution, and `prepareStopDisposition` returns `notFound('Turn was not admitted')`, which throws. The local `runtimeExecution` is never aborted, so the child is admitted and runs unstopped unless another schedule wake retries in time.
   
   (Found independently by both review lineages; see also the related P2 on `root-turn-coordinator.ts:1252`.)



##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -413,15 +453,46 @@ export async function reconcileAgentGraphSchedule(
       );
     }
 
-    const outcomes = await Promise.all(
+    let waveSettled = false;
+    const wave = Promise.all(
       prepared.map(async (work) => {
         const outcome = await dispatchScheduledWork(input, work, snapshot.schedule.revision);
         if (outcome.status === 'rejected') {
           notifySupervisor(input.supervisor?.onReconciliationFailure, outcome.failure);
         }
         return outcome;
       }),
-    );
+    ).finally(() => {
+      waveSettled = true;
+      wake.notify();
+    });
+    let controlReadFailure: AgentGraphScheduleReconciliationFailure | undefined;
+    try {
+      while (!waveSettled) {
+        await wake.wait();
+        if (waveSettled || input.abortSignal?.aborted) break;
+        try {
+          const latest = await readScheduleSnapshot(input, selectedResultCache);
+          const controls = await applyScheduleStops(input, latest);

Review Comment:
   P3 (one lineage, not reproduced): this awaits `applyScheduleStops`, which uses `allSettled` over every target, and each scoped stop awaits `execution.settled` (runtime-kernel.ts:2034). If one child's backend ignores abort, a later stop on a cooperative sibling waits for that stream to exit. There is no test with a non-cooperative backend.



##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -2878,7 +3023,7 @@ export class RuntimeKernel implements RuntimeKernelLike {
     const ownsCurrentStop =
       execution.phase === 'attached' &&
       execution.stopIntent !== undefined &&
-      this.stopIntents.get(sessionId) === execution.stopIntent;
+      execution.stopIntent.claims.has(execution);

Review Comment:
   P3: before this change, an execution could bypass quarantine only if its stop intent was the session's current one. Now any attached execution whose own (possibly stale) intent contains itself bypasses the retained-stop-operation quarantine. No test covers a stale intent paired with a retained operation.



##########
packages/runtime/src/session-manager.ts:
##########
@@ -3131,9 +3171,19 @@ export class SessionManager {
         `Claimed graph turn ${claim.targetTurnId} is already owned by run ${turnOwner.runId}`,
       );
     }
-    if (child.isArchived || child.status === 'aborted') {
+    if (child.isArchived) {
       throw new Error('Claimed graph execution target child session is terminated');
     }
+    if (child.status === 'aborted') {
+      const latest = (await this.listInvocations(child.id)).sort(
+        (left, right) => right.openedAt - left.openedAt,
+      )[0];
+      // A graph stop ends one activation, not the reusable operator. Only a
+      // durable graph-supervisor stop permits a new claim on an aborted child.
+      if (latest?.terminalEvent?.actions?.stateDelta?.abortSource !== 'graph.supervisor') {

Review Comment:
   P3: the graph-wide operator stop in the coordinator (`stream-graph-coordinator.ts:1812`, `stopSession(..., { source: 'graph_supervisor' })`) produces the same `abortSource: 'graph.supervisor'`. So after a whole-graph supervisor stop, operator children now accept new claims, which main refused. If that is the intended resume-after-stop behaviour, a test would pin it down. If not, activation-scoped stops need a distinct marker. Nit: `listInvocations(child.id)` is now read twice on this path.
   
   Related (P3, one lineage, not reproduced): a scoped stop projects the whole session as `aborted` (runtime-kernel.ts ~2257) before it writes the terminal fact (~2268). If the process crashes in that window, or the terminal append fails, the latest invocation never shows `graph.supervisor`, and this operator then refuses every future graph claim. There is no restart test: test 402 reuses the same in-memory SessionManager.



##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -2162,7 +2299,13 @@ export class RuntimeKernel implements RuntimeKernelLike {
     for (const target of operation.targets.values()) {
       if (target.delivery.kind === 'failed') failures.add(target.delivery.error);
     }
-    failures.throwIfAny(`Stop cleanup failed for session ${sessionId}`);
+    try {
+      failures.throwIfAny(`Stop cleanup failed for session ${sessionId}`);
+      if (completed) operation.resolveCompletion();
+    } catch (error) {
+      if (completed) operation.rejectCompletion(error);

Review Comment:
   P3: when the operation is `completed` but a delivery failed, completion is rejected and the operation is deleted. `release` in `enqueueClaimedAgentGraphIntent` (session-manager.ts:2983) doesn't catch `waitForExecutionStop`, so `.finally(release)` replaces the child's result with this cleanup error, even though the durable terminal is already settled. The projection comes from RuntimeEvents, so no result is lost, but the dispatch outcome becomes a reconciliation failure that is never retried. Should this be caught and surfaced as a stop failure, or is this intended fail-stop behaviour?



##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -1933,6 +1940,126 @@ export class RuntimeKernel implements RuntimeKernelLike {
     ];
   }
 
+  /** Stop one captured owner without cancelling other queued executions in its Session. */
+  stopExecution(claim: RuntimeExecutionClaim, input: StopSessionInput = {}): Promise<void> {
+    normalizeStopSessionSource(input.source, input.workHubActionId);
+    const execution = this.executionClaimStates.get(claim);
+    if (!execution) throw new Error('Runtime execution claim belongs to another owner');
+    if (execution.scopedStopAttempt) return execution.scopedStopAttempt;
+    const run = execution.run;
+    const active =
+      run &&
+      this.backendGenerationsFor(execution.sessionId).find(
+        (candidate) => candidate.activeRuns.get(run.runId) === run,
+      );
+    if (!active && (execution.phase === 'released' || execution.phase === 'failed')) {
+      return run
+        ? this.retryStoppedRun(
+            {
+              sessionId: execution.sessionId,
+              runId: run.runId,
+              turnId: run.turnId,
+            },
+            input,
+          )
+        : Promise.resolve();
+    }
+    if (active && run) this.assertScopedStopGeneration(active, run);

Review Comment:
   P3: when the generation owns any other unstopped run, this throws instead of falling back to the old session-wide behavior. The reconciler then records a stop failure on every wake. Is there a fallback, or a proof that operator generations hold a single run?



##########
packages/runtime-host/src/server/root-turn-coordinator.ts:
##########
@@ -1249,6 +1249,7 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
           () => this.messages.commitStopFence(identity),
           lease,
           input,
+          true,

Review Comment:
   P2: `stopRoot` is shared by public `turn.stop` (via `requestStop`), `stopAgentGraphSupervisor`, host shutdown (`stopActiveTurn`), and the graph execution abort. Hard-coding `scoped=true` switches all of them from kernel `stopSession` to `stopRun(identity)`. `stopRun` only matches a claim with an attached `run` or a Run already in `activeRuns`. `declareStopFence` delivers while `startSettled` is still pending, so a stop in the window between Host activation and kernel attach seems to become a no-op. `prepareStopDisposition` then sees `stopRequested` already set and returns `await_terminal` without redelivering, so the turn runs to natural completion. On main, the session-level stop intent covered pending claims, and `stopBeforeDispatch` only guards the continuation path. `assertScopedStopGeneration` can also now throw for a Stop-button press. Could the scoped delivery be limited to `graph_supervisor`, or could you add a Host test that stops a root turn before its Run attaches?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4215032936


##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -413,15 +472,66 @@ export async function reconcileAgentGraphSchedule(
       );
     }
 
-    const outcomes = await Promise.all(
+    let waveSettled = false;
+    const wave = Promise.all(
       prepared.map(async (work) => {
         const outcome = await dispatchScheduledWork(input, work, snapshot.schedule.revision);
         if (outcome.status === 'rejected') {
           notifySupervisor(input.supervisor?.onReconciliationFailure, outcome.failure);
         }
         return outcome;
       }),
-    );
+    ).finally(() => {
+      waveSettled = true;
+      wake.notify();
+    });
+    let controlReadFailure: AgentGraphScheduleReconciliationFailure | undefined;
+    let retryTimer: ReturnType<typeof setTimeout> | undefined;
+    let retryDelay = CONTROL_RETRY_INITIAL_DELAY_MS;
+    try {
+      // A driver abort does not end this loop: the wave still owns its
+      // dispatches, and a child parked behind a failed stop settles only
+      // after a retry succeeds.
+      while (!waveSettled) {
+        await wake.wait();
+        clearTimeout(retryTimer);
+        retryTimer = undefined;
+        if (waveSettled) break;
+        let retry: boolean;
+        try {
+          const latest = await readScheduleSnapshot(input, selectedResultCache);
+          const controls = await applyScheduleStops(input, latest, resolvedStops);
+          recordScheduleStops(input, stops, failures, stopFailureStreaks, controls);
+          if (controlReadFailure) {
+            failures.splice(failures.indexOf(controlReadFailure), 1);
+            controlReadFailure = undefined;
+          }
+          retry = controls.failures.length > 0;
+        } catch (error) {
+          const repeated = controlReadFailure !== undefined;
+          if (controlReadFailure) failures.splice(failures.indexOf(controlReadFailure), 1);
+          controlReadFailure = { phase: 'schedule', error };
+          // Notify once per streak of read failures, not on every retry.
+          if (repeated) failures.push(controlReadFailure);

Review Comment:
   **P3.** Stop failures now escalate to a one-time "stuck" notification at the 8th consecutive failure, but a persistent `readScheduleSnapshot` failure here notifies once, on the first failure, and then retries silently every 5 s while the wave stays parked. That is the same silent-park shape for a different cause. Could the read-failure streak use the same `STOP_CLEANUP_STUCK_FAILURES` threshold and report it as stuck once?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han merged PR #5977:
URL: https://github.com/apache/maka/pull/5977


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "chihumyum (via GitHub)" <gi...@apache.org>.
chihumyum commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4215106041


##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -413,15 +472,66 @@ export async function reconcileAgentGraphSchedule(
       );
     }
 
-    const outcomes = await Promise.all(
+    let waveSettled = false;
+    const wave = Promise.all(
       prepared.map(async (work) => {
         const outcome = await dispatchScheduledWork(input, work, snapshot.schedule.revision);
         if (outcome.status === 'rejected') {
           notifySupervisor(input.supervisor?.onReconciliationFailure, outcome.failure);
         }
         return outcome;
       }),
-    );
+    ).finally(() => {
+      waveSettled = true;
+      wake.notify();
+    });
+    let controlReadFailure: AgentGraphScheduleReconciliationFailure | undefined;
+    let retryTimer: ReturnType<typeof setTimeout> | undefined;
+    let retryDelay = CONTROL_RETRY_INITIAL_DELAY_MS;
+    try {
+      // A driver abort does not end this loop: the wave still owns its
+      // dispatches, and a child parked behind a failed stop settles only
+      // after a retry succeeds.
+      while (!waveSettled) {
+        await wake.wait();
+        clearTimeout(retryTimer);
+        retryTimer = undefined;
+        if (waveSettled) break;
+        let retry: boolean;
+        try {
+          const latest = await readScheduleSnapshot(input, selectedResultCache);
+          const controls = await applyScheduleStops(input, latest, resolvedStops);
+          recordScheduleStops(input, stops, failures, stopFailureStreaks, controls);
+          if (controlReadFailure) {
+            failures.splice(failures.indexOf(controlReadFailure), 1);
+            controlReadFailure = undefined;
+          }
+          retry = controls.failures.length > 0;
+        } catch (error) {
+          const repeated = controlReadFailure !== undefined;
+          if (controlReadFailure) failures.splice(failures.indexOf(controlReadFailure), 1);
+          controlReadFailure = { phase: 'schedule', error };
+          // Notify once per streak of read failures, not on every retry.
+          if (repeated) failures.push(controlReadFailure);

Review Comment:
   Fixed in 60bcaf190: control read failures now keep a streak like stops do. The supervisor hears the first failure and, once, the 8th as 'stuck … still retrying'; a successful read resets it and clears the failure. The threshold is now the shared CONTROL_STUCK_FAILURES. A mocked-timer test covers reads 7, 8, 12 and recovery, and fails on the previous code.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "chihumyum (via GitHub)" <gi...@apache.org>.
chihumyum commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4214293529


##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -413,15 +465,60 @@ export async function reconcileAgentGraphSchedule(
       );
     }
 
-    const outcomes = await Promise.all(
+    let waveSettled = false;
+    const wave = Promise.all(
       prepared.map(async (work) => {
         const outcome = await dispatchScheduledWork(input, work, snapshot.schedule.revision);
         if (outcome.status === 'rejected') {
           notifySupervisor(input.supervisor?.onReconciliationFailure, outcome.failure);
         }
         return outcome;
       }),
-    );
+    ).finally(() => {
+      waveSettled = true;
+      wake.notify();
+    });
+    let controlReadFailure: AgentGraphScheduleReconciliationFailure | undefined;
+    let retryTimer: ReturnType<typeof setTimeout> | undefined;
+    let retryDelay = CONTROL_RETRY_INITIAL_DELAY_MS;
+    try {
+      while (!waveSettled) {
+        await wake.wait();
+        clearTimeout(retryTimer);
+        retryTimer = undefined;
+        if (waveSettled || input.abortSignal?.aborted) break;
+        let retry: boolean;
+        try {
+          const latest = await readScheduleSnapshot(input, selectedResultCache);
+          const controls = await applyScheduleStops(input, latest, resolvedStops);
+          recordScheduleStops(input, stops, failures, controls);
+          if (controlReadFailure) {
+            failures.splice(failures.indexOf(controlReadFailure), 1);
+            controlReadFailure = undefined;
+          }
+          retry = controls.failures.length > 0;
+        } catch (error) {
+          if (controlReadFailure) failures.splice(failures.indexOf(controlReadFailure), 1);
+          controlReadFailure = { phase: 'schedule', error };
+          recordReconciliationFailure(input, failures, controlReadFailure);
+          retry = true;
+        }
+        // A failed stop can keep its child, and so this wave, parked until a
+        // retry succeeds. Back off instead of waiting for another commit.
+        if (retry) {
+          retryTimer = setTimeout(wake.notify, retryDelay);

Review Comment:
   Fixed in 8620455c4: the stop keeps retrying, but its 8th consecutive failure (about 11 s, just past the 5 s backoff cap) reaches the supervisor once as 'stuck and still retrying'; a success resets it. A driver abort no longer ends the retries, so a transient failure can't park an aborted wave.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
packages/runtime/src/message-authority.ts:
##########
@@ -60,10 +60,23 @@ export interface RuntimeHostedRootExecutionInput extends RuntimeMessageRunIdenti
   readonly onReady?: () => void | Promise<void>;
 }
 
+/**
+ * `run` delivers the Runtime stop to this exact Run's owner only, for an
+ * activation-scoped graph stop. The default stops the Session's live
+ * execution, including a claim that has not attached its Run yet.
+ */
+export interface RuntimeHostedRootStopOptions {
+  readonly scope?: 'session' | 'run';
+}
+
 /** Host-only root lifecycle capability. Embedded compositions must omit it. */
 export interface RuntimeHostedRootAuthority extends RuntimeMessageAuthority {
   executeRoot(input: RuntimeHostedRootExecutionInput): Promise<void>;
-  stopRoot(identity: RuntimeMessageRunIdentity, input?: StopSessionInput): Promise<void>;
+  stopRoot(
+    identity: RuntimeMessageRunIdentity,
+    input?: StopSessionInput,
+    options?: RuntimeHostedRootStopOptions,

Review Comment:
   Fixed in 9fff5aa05: replaced the option with a required stopRootRun(identity, input); stopRoot is byte-for-byte main's Session stop again. An authority without exact-Run support now fails typecheck (TS2741), which caught one Host test fixture that only forwarded stopRoot.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "chihumyum (via GitHub)" <gi...@apache.org>.
chihumyum commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4213604053


##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -1933,6 +1940,126 @@ export class RuntimeKernel implements RuntimeKernelLike {
     ];
   }
 
+  /** Stop one captured owner without cancelling other queued executions in its Session. */
+  stopExecution(claim: RuntimeExecutionClaim, input: StopSessionInput = {}): Promise<void> {
+    normalizeStopSessionSource(input.source, input.workHubActionId);
+    const execution = this.executionClaimStates.get(claim);
+    if (!execution) throw new Error('Runtime execution claim belongs to another owner');
+    if (execution.scopedStopAttempt) return execution.scopedStopAttempt;
+    const run = execution.run;
+    const active =
+      run &&
+      this.backendGenerationsFor(execution.sessionId).find(
+        (candidate) => candidate.activeRuns.get(run.runId) === run,
+      );
+    if (!active && (execution.phase === 'released' || execution.phase === 'failed')) {
+      return run
+        ? this.retryStoppedRun(
+            {
+              sessionId: execution.sessionId,
+              runId: run.runId,
+              turnId: run.turnId,
+            },
+            input,
+          )
+        : Promise.resolve();
+    }
+    if (active && run) this.assertScopedStopGeneration(active, run);

Review Comment:
   Not changed: an operator Session runs one Run at a time (the Host admits one active root per Session; local claims share a per-Session tail). A Session-wide fallback would stop runs the graph doesn't own; the new backoff retries the exact stop instead.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -2878,7 +3023,7 @@ export class RuntimeKernel implements RuntimeKernelLike {
     const ownsCurrentStop =
       execution.phase === 'attached' &&
       execution.stopIntent !== undefined &&
-      this.stopIntents.get(sessionId) === execution.stopIntent;
+      execution.stopIntent.claims.has(execution);

Review Comment:
   Not changed: a Session intent is cleared only after stopSessionAttempt awaits every claim it holds, so an unsettled attached claim in intent.claims always belongs to the current intent; scoped intents are per-claim.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "chihumyum (via GitHub)" <gi...@apache.org>.
chihumyum commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4213602884


##########
packages/runtime/src/stream-graph-schedule-reconcile.ts:
##########
@@ -413,15 +453,46 @@ export async function reconcileAgentGraphSchedule(
       );
     }
 
-    const outcomes = await Promise.all(
+    let waveSettled = false;
+    const wave = Promise.all(
       prepared.map(async (work) => {
         const outcome = await dispatchScheduledWork(input, work, snapshot.schedule.revision);
         if (outcome.status === 'rejected') {
           notifySupervisor(input.supervisor?.onReconciliationFailure, outcome.failure);
         }
         return outcome;
       }),
-    );
+    ).finally(() => {
+      waveSettled = true;
+      wake.notify();
+    });
+    let controlReadFailure: AgentGraphScheduleReconciliationFailure | undefined;
+    try {
+      while (!waveSettled) {
+        await wake.wait();
+        if (waveSettled || input.abortSignal?.aborted) break;
+        try {
+          const latest = await readScheduleSnapshot(input, selectedResultCache);
+          const controls = await applyScheduleStops(input, latest);

Review Comment:
   Not changed: each pass starts every target's stop concurrently, so cooperative siblings are not delayed by an abort-ignoring one; only the next pass waits, as main's awaited stopSession did, and main applied no stops mid-wave at all.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
packages/runtime/src/session-manager.ts:
##########
@@ -3131,9 +3171,19 @@ export class SessionManager {
         `Claimed graph turn ${claim.targetTurnId} is already owned by run ${turnOwner.runId}`,
       );
     }
-    if (child.isArchived || child.status === 'aborted') {
+    if (child.isArchived) {
       throw new Error('Claimed graph execution target child session is terminated');
     }
+    if (child.status === 'aborted') {
+      const latest = (await this.listInvocations(child.id)).sort(
+        (left, right) => right.openedAt - left.openedAt,
+      )[0];
+      // A graph stop ends one activation, not the reusable operator. Only a
+      // durable graph-supervisor stop permits a new claim on an aborted child.
+      if (latest?.terminalEvent?.actions?.stateDelta?.abortSource !== 'graph.supervisor') {

Review Comment:
   Intended: AgentGraphCoordinator.stop keeps schedule facts so an update can wake the same graph; main refused only operators that were mid-run. A test now pins resume-after-supervisor-stop and refusal after a stop_button stop. The duplicate listInvocations read is fixed.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "chihumyum (via GitHub)" <gi...@apache.org>.
chihumyum commented on code in PR #5977:
URL: https://github.com/apache/maka/pull/5977#discussion_r4213601321


##########
packages/runtime-host/src/server/root-turn-coordinator.ts:
##########
@@ -1249,6 +1249,7 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
           () => this.messages.commitStopFence(identity),
           lease,
           input,
+          true,

Review Comment:
   Confirmed and fixed in b2b9ff9a4: stopRoot is Session-level again unless the caller passes { scope: 'run' }, which only stopAgentGraphActivation does. turn.stop, shutdown, WorkHub and the whole-graph supervisor stop match main. Added a Host test that stops a root Turn before its Run attaches.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
packages/runtime/src/session-manager.ts:
##########
@@ -3149,6 +3199,9 @@ export class SessionManager {
     let aborted = false;
     let stopPromise: Promise<void> | undefined;
     const userMessageId = await this.claimedGraphUserMessageId(claim, input.hostedGraphExecution);
+    if (input.hostedGraphExecution && runtimeExecution.stopSignal.aborted)
+      throw runtimeExecution.stopSignal.reason;
+    input.onHostSubmission?.();

Review Comment:
   Fixed in b2b9ff9a4: Host ownership now starts when the Host admission gate, inside the Session admission lease, admits the claim. Before that, a stop cancels the local capability and the gate refuses the Turn; after it, the stop waits on the lease and goes through the Host fence. Real-Host test added.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -2162,7 +2299,13 @@ export class RuntimeKernel implements RuntimeKernelLike {
     for (const target of operation.targets.values()) {
       if (target.delivery.kind === 'failed') failures.add(target.delivery.error);
     }
-    failures.throwIfAny(`Stop cleanup failed for session ${sessionId}`);
+    try {
+      failures.throwIfAny(`Stop cleanup failed for session ${sessionId}`);
+      if (completed) operation.resolveCompletion();
+    } catch (error) {
+      if (completed) operation.rejectCompletion(error);

Review Comment:
   Not changed: locally the child's stream finalizes only after the stop operation completes, so release sees no retained operation; hosted, that delivery failure already drains the Host via runCommand. A test now pins the local path.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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


Re: [PR] fix(runtime): apply graph stops while child work is running [maka]

Posted by "chihumyum (via GitHub)" <gi...@apache.org>.
chihumyum commented on PR #5977:
URL: https://github.com/apache/maka/pull/5977#issuecomment-6050064117

   Pushed b2b9ff9a4 for the review: all four P2s are fixed with fail-before/pass-after tests, and the P3s are answered inline. `turn.stop`, host shutdown, WorkHub and the whole-graph supervisor stop are Session-level again, so the PR body's "global Session stop is unchanged" holds.
   
   Residual risks worth a reviewer's look:
   - A persistent stop failure during a live wave now retries every ≤5 s until the wave settles. The rate is capped; the count is not. In hosted mode each retry is one Host stop.
   - `hasPendingAgentGraphActivationStop` is optional on the coordinator runtime. A runtime without it falls back to main: a terminal target never retries cleanup.
   - If a future `RuntimeHostedRootAuthority` drops the new `{ scope: 'run' }` argument, graph stops widen to the whole Session instead of failing.
   - The admission gate can refuse a claim whose intent was already moved to executing. The only production caller (the schedule reconciler) cancels the intent before stopping, so this is consistent today. A future caller that stops an activation id directly would need to settle the intent itself.
   
   Verification: runtime 3736/3750 pass (14 skipped, 0 fail), runtime-host 2233/2245 (12 skipped, 0 fail), typecheck, lint, format, ASF headers, Windows inventory, Knip, and `check:release` (minus `check:stale`) all pass. No protocol changes.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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