You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "Astro-Han (via GitHub)" <gi...@apache.org> on 2026/08/23 14:49:11 UTC

[PR] fix: persist steering at message admission [maka]

Astro-Han opened a new pull request, #3633:
URL: https://github.com/apache/maka/pull/3633

   ## Summary
   
   Steering was accepted into the Runtime Host queue immediately, but the transcript did not expose it until the provider pulled the queue at a later step boundary. That coupled user-visible conversation state to provider delivery state and made sends appear delayed.
   
   This change makes successful steering admission durable before it enters the active Turn queue, so every client can render the accepted user message from the transcript immediately. Provider consumption remains separately ordered and exactly-once. Sent steering is non-retractable; an ordinary terminal race carries the same message into the successor without creating a second transcript row, while explicit Stop retains the message and suppresses an automatic successor.
   
   The PR also removes parallel presentation and fallback paths that encoded conflicting ownership:
   
   - removes Desktop's steering-specific IPC in favor of `sessions:enqueue`
   - removes CLI/TUI fallback retry ownership and steering queue presentation
   - removes synthetic `steering_message` projection from queue `in_flight` state
   - updates successor materialization to reuse admitted message facts
   
   Net diff: 374 insertions and 894 deletions.
   
   ## Verification
   
   - `npm run format:check`
   - affected builds: `@maka/core`, `@maka/runtime`, `@maka/runtime-host`, `maka-agent`, and Desktop main/preload/renderer
   - Runtime Host focused suites: 48/48 passing (`message-coordinator`, `execution-host-message`, `session-projector`)
   - Runtime Host coordinator/integration suites: 92/92 passing before the final main rebase; affected suites above were rerun after rebase
   - CLI/TUI focused suites: 235/235 passing
   - Desktop focused suites: 49/49 passing
   - Runtime steering recovery suite: 8/8 passing
   
   Repository-wide tests and the full Desktop Playwright suite were not run locally.
   
   ## AI use
   
   Select exactly one:
   
   - [ ] No generative tool made a substantive contribution
   - [x] Generative tooling made a substantive contribution
   
   Tool(s) and scope: Maka authored implementation and tests, performed architecture analysis, and used delegated read-only scans to identify redundant steering paths. Each affected commit includes a `Generated-by: Maka` trailer.
   
   ## 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-host): unify durable message lifecycle [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han closed pull request #3633: fix(runtime-host): unify durable message lifecycle
URL: https://github.com/apache/maka/pull/3633


-- 
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-host): unify durable message lifecycle [maka]

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

   The branch moved to `7128a97207` after my review, which was bound to `eecd4d93d`. I re-checked all three blocking findings against the new head rather than assuming either way, and **all three are unchanged**:
   
   - `bindDurableSession()` still writes only the in-memory map, and `root-turn-coordinator.ts:2384` is still its only production caller, so the replay path still never sets the marker.
   - `message-coordinator.ts:432-438` still classifies a pending admission from the root-turn receipt and the explicit Stop proof alone, while `:516` still consults the immutable steering proof. The asymmetry between the two paths is what the finding is about, and it is still there.
   - `execution-composition.test.ts` still calls `commitMessageAdmission` and then appends the same `admitted-steering` identity through the direct path, so the exact-once assertion still reads three entries.
   
   So the earlier review still applies in full; only its commit binding is stale. Nothing here asks you to re-explain the rebase — I mention it only so the moved head is not mistaken for a response to the findings.
   
   <details>
   <summary>简体中文</summary>
   
   分支在我评审之后移到了 `7128a97207`,而那次评审绑定的是 `eecd4d93d`。我没有凭任何一边的假设下结论,而是对新 head 重新核了三条阻塞项,**三条都没有变化**:
   
   - `bindDurableSession()` 仍然只写内存中的那个 map,`root-turn-coordinator.ts:2384` 仍是它在生产代码里唯一的调用者,因此重放路径依旧不会设置该标记。
   - `message-coordinator.ts:432-438` 仍然只凭 root-turn 收据和显式 Stop 证据来判定未决 admission,而 `:516` 仍然会查 immutable steering proof。这条 finding 说的正是两条路径之间的不对称,它依然存在。
   - `execution-composition.test.ts` 仍然在 `commitMessageAdmission` 之后,又用直接路径追加了同一个 `admitted-steering` identity,所以 exact-once 断言读到的仍然是三条。
   
   因此之前那条评审整体仍然成立,过期的只是它的 commit 绑定。这里不需要你解释这次 rebase——我说明它,只是为了避免把 head 的移动误当成对上述问题的回应。
   
   </details>


-- 
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: persist steering at message admission [maka]

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


##########
packages/runtime-host/src/server/root-turn-coordinator.ts:
##########
@@ -1966,6 +1990,7 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
     try {
       this.messages.reserveRootTurn(messageIdentity);
       messageReserved = true;
+      await this.messages.recoverRootTurn(messageIdentity);

Review Comment:
   [P1] This is the only production call to `recoverRootTurn`, but it sits inside `prepareAdmittedTurn`, which is reached for recovery only by a `rootReplayAdmission` planned when no Run exists. The target crash is after the durable steering append and before queue commit, so an active Run necessarily already exists (`commitSteeringAdmission` rejects otherwise). Startup first terminalizes interrupted Runs, then recovery checks existing-Run admissions without re-entering this new-root path. Therefore the guard here cannot run for the state it is meant to repair. Reproduction: seed an existing Run plus one durable steering admission and no queue/provider proof, restart the real Host, and observe `durable=1 / provider proof=0 / root chain=1` instead of the expected successor chain of 2. Existing guards do not help because control never reaches this call.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +418,75 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverRootTurn(identity: RuntimeMessageRunIdentity): Promise<void> {

Review Comment:
   [P1 corroborating evidence] The helper’s internal live-ID and immutable-proof checks are reasonable, but the new unit test calls this method directly and does not prove startup reachability. Deleting the sole production call at `root-turn-coordinator.ts:1993` left the complete Runtime Host suite green; focused coordinator/execution-host tests remained 45/45 and root-turn-coordinator tests 49/49. This mutation demonstrates that the shipped recovery behavior is untested and currently disconnected, not merely that one edge-case assertion is missing.



-- 
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-host): unify durable message lifecycle [maka]

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

   After several exact-head review rounds, it is clear that the remaining findings share structural causes rather than isolated implementation mistakes. Settlement and recovery still classify the same admission differently, the durable Session execution contract is partly represented by memory-only state, and some tests bypass the new atomic admission boundary. The repeated fixes have also expanded this PR to 80 files and 33 commits, making both review and rebasing unnecessarily difficult.\n\nI am pausing this implementation and will split it into three end-to-end changes:\n\n1. A complete durable message lifecycle, including admission, mutation, settlement, recovery, and removal of the old Runtime queue authority.\n2. Canonical CLI and Desktop conversation projection, preserving immediate send UX while reconciling by stable .\n3. Side Conversation admission and event ownership, built cleanly on the current Side Conversation architecture.\n\nI will convert this PR back to draft and s
 top updating its implementation. Once the replacement PRs are available, I will close this PR and link them here. The existing review threads remain useful evidence for the replacement design, but should not be treated as another local patch queue.\n\nThis restructuring plan was developed with Codex assistance and reviewed by me.


-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -727,17 +936,37 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
           continue;
         }
         const result = { disposition, queueRevision: candidateRevision + 1 } as const;
+        let durableAdmittedAt: number | undefined;
+        if (!durableAdmission) {
+          const admitted = await this.#root.commitMessageAdmission(

Review Comment:
   [P3] Recompute the returned revision after this durable-admission await. The preflight freezes `candidateRevision` and `result` before this call, but `#pull/#ack/#nack` intentionally mutate the same session state outside the admission lock. In a delayed-commit probe, pull+ack advanced the queue while this await was suspended; submit then appended its entry and returned `queueRevision: 2` while the authoritative projection was already revision 4. Current Desktop/CLI callers do not use this result as mutation authority, so this is non-blocking today, but the wire result is false and can mislead future clients. Fence/retry after the durable commit or construct the receipt from the final state, and cover a paused `commitMessageAdmission` racing with pull+ack.



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime-host/src/server/root-turn-coordinator.ts:
##########
@@ -1909,6 +1959,19 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
     if (unavailableReason) {
       return completedStart(operationUnavailable(unavailableReason));
     }
+    const initialUserMessagesMaterialized = admission.sourceMessages.some(
+      (source) => source.disposition === 'steering',
+    );
+    if (initialUserMessagesMaterialized) {
+      await this.manager.materializeRootSourceMessages({

Review Comment:
   [P1] A crash after source materialization but before Run creation prevents every later Host startup. For a queued root containing steering, this persists each source UserMessage first (`runtime-kernel.ts:2281-2299`) and only then checks/creates the Run. If the process exits after any append, `prepareHostedExecutionRecovery` sees a UserMessage with no Run and throws at `hosted-execution-recovery.ts:147-150`. A SQLite-backed startup probe with exactly `root admission + materialized source + no Run` exited before readiness with `Admitted Turn ... has a UserMessage but no Run`. Existing recovery tests cover the states before materialization or after Run creation, not this intermediate durable state. Please either make admission/materialization/Run establishment recoverably atomic, or teach recovery to validate and resume this partially materialized state idempotently.\n\n<details>\n<summary>中文</summary>\n\n[P1] source materialization 之后、Run 创建之前崩溃,会让此后�
 ��次 Host 启动都失败。含 steering 的 queued root 会先逐条持久化 source UserMessage(`runtime-kernel.ts:2281-2299`),之后才检查/创建 Run;进程在任一次 append 后退出,`prepareHostedExecutionRecovery` 会在 `hosted-execution-recovery.ts:147-150` 看到“有 UserMessage、无 Run”并直接抛错。SQLite-backed 启动探针精确构造 `root admission + materialized source + no Run`,实际在 readiness 前退出,错误为 `Admitted Turn ... has a UserMessage but no Run`。现有恢复测试只覆盖 materialization 前或 Run 已存在,没覆盖这个中间 durable state。请让 admission/materialization/Run 建立在恢复意义上原子,或让 recovery 能验证并幂等续跑这类部分物化状态。\n\n</details>



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -2393,175 +2278,25 @@ export class RuntimeKernel implements RuntimeKernelLike {
     );
   }
 
-  // --------------------------------------------------------------------------
-  // Steering / followup queues (authoritative source of truth)
-  // --------------------------------------------------------------------------
-
-  steer(sessionId: string, text: string): QueueEnqueueOutcome {
-    this.assertEmbeddedMessageQueue('steer');
-    // Steering's delivery contract is anchored to the runtime event ledger
-    // (fail-closed persist + durable-consume ack). Without a RuntimeEventStore
-    // that anchor does not exist — same condition as requireTerminalWrite —
-    // so fall back to a fresh turn, whose user message the SessionStore
-    // persists with the ordinary turn-open guarantee.
-    if (!this.deps.runtimeEventStore) return { kind: 'fallback' };
-    // Double responsibility (codex): with no live steering owner to inject
-    // into — the turn just ended, begin() failed, or only child/compact runs
-    // are active (they never consume this queue) — tell the caller to open a
-    // fresh turn instead so the message is never dropped.
-    const state = this.liveSteeringState(sessionId);
-    if (!state) return { kind: 'fallback' };
-    const messageId = this.deps.newId();
-    state.steering.push({ id: messageId, messageId, content: { text } });
-    this.emitQueueUpdate(sessionId, state);
-    return { kind: 'queued' };
-  }
-
-  queueMessage(sessionId: string, text: string): QueueEnqueueOutcome {
-    this.assertEmbeddedMessageQueue('queueMessage');
-    const state = this.liveSteeringState(sessionId);
-    if (!state) return { kind: 'fallback' };
-    const messageId = this.deps.newId();
-    state.followup.push({ id: messageId, messageId, content: { text } });
-    this.emitQueueUpdate(sessionId, state);
-    return { kind: 'queued' };
-  }
-
-  drainFollowup(sessionId: string): string | null {
-    this.assertEmbeddedMessageQueue('drainFollowup');
-    const state = this.steeringBySession.get(sessionId);
-    if (!state || state.followup.length === 0) return null;
-    const drained = state.followup.splice(0);
-    this.emitQueueUpdate(sessionId, state);
-    return drained.map((message) => message.content.text).join('\n\n');
-  }
-
-  retractQueue(sessionId: string): string {
-    this.assertEmbeddedMessageQueue('retractQueue');
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return '';
-    // Retract reclaims QUEUED messages only. pull() is the single atomic
-    // commit point of delivery: an in-flight lease is already committed to
-    // the running turn — its durable append may land at any moment, so
-    // handing its text back to the user here would refill AND execute the
-    // same directive. An in-flight lease settles only by the persistence
-    // fact (ack when the ledger owns it, nack back to a queue otherwise).
-    const all = [
-      ...state.steering.map((message) => message.content.text),
-      ...state.followup.map((message) => message.content.text),
-    ];
-    state.steering = [];
-    state.followup = [];
-    this.emitQueueUpdate(sessionId, state);
-    return all.join('\n\n');
-  }
-
-  private ensureSteering(sessionId: string): SessionSteeringState {
-    const existing = this.steeringBySession.get(sessionId);
-    if (existing) return existing;
-    const created: SessionSteeringState = { steering: [], inFlight: [], followup: [] };
-    this.steeringBySession.set(sessionId, created);
-    return created;
-  }
-
-  private assertEmbeddedMessageQueue(operation: string): void {
-    if (this.deps.messageAuthority) {
-      throw new RuntimeMessageAuthorityInvariantError(
-        `Hosted Runtime cannot ${operation}; the Runtime Host owns message admission and queues`,
-      );
-    }
-  }
-
-  /**
-   * The session's steering state only while a steering-capable top-level run
-   * owns it (sink registered after begin() succeeded and not yet released).
-   * Child agent and compact runs never establish ownership, so their activity
-   * alone yields undefined — enqueue must fall back rather than strand text.
-   */
-  private liveSteeringState(sessionId: string): SessionSteeringState | undefined {
-    const state = this.steeringBySession.get(sessionId);
-    return state?.sink ? state : undefined;
-  }
-
-  private emitQueueUpdate(sessionId: string, state: SessionSteeringState): void {
-    state.sink?.({
-      type: 'queue_update',
-      id: this.deps.newId(),
-      turnId: state.activeTurnId ?? '',
-      ts: this.deps.now(),
-      steering: [
-        ...state.inFlight.map((message) => message.content.text),
-        ...state.steering.map((message) => message.content.text),
-      ],
-      followup: state.followup.map((message) => message.content.text),
-      steeringEntries: [
-        ...state.inFlight.map((message) => ({
-          entryId: message.id,
-          messageId: message.messageId,
-          content: message.content,
-          placement: 'current_turn' as const,
-          state: 'in_flight' as const,
-        })),
-        ...state.steering.map((message) => ({
-          entryId: message.id,
-          messageId: message.messageId,
-          content: message.content,
-          placement: 'current_turn' as const,
-          state: 'queued' as const,
-        })),
-      ],
-      followupEntries: state.followup.map((message) => ({
-        entryId: message.id,
-        messageId: message.messageId,
-        content: message.content,
-        placement: 'next_turn' as const,
-        state: 'queued' as const,
-      })),
-    });
-  }
-
-  private clearSteering(sessionId: string): void {
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return;
-    // Same commit-point rule as retractQueue: only QUEUED messages are
-    // clearable. An in-flight lease is already committed to the running
-    // turn's delivery and settles only by the persistence fact.
-    if (state.steering.length === 0 && state.followup.length === 0) return;
-    state.steering = [];
-    state.followup = [];
-    this.emitQueueUpdate(sessionId, state);
-  }
-
-  private releaseSteeringTurn(sessionId: string, turnId: string): void {
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return;
-    // A release folds only the leases THIS turn issued; an overlapping turn's
-    // in-flight lease stays for its issuer to settle (acked = delivered, so
-    // folding it into followup would redeliver an already-executed message).
-    const own = state.inFlight.filter((message) => message.issuingTurnId === turnId);
-    if (state.activeTurnId !== turnId) {
-      // Not (or no longer) the owner. The issuer's backend settles every
-      // lease before its turn ends, so `own` is normally empty; this is a
-      // backstop that keeps a never-settled lease from stranding invisibly.
-      if (own.length === 0) return;
-      state.inFlight = state.inFlight.filter((message) => message.issuingTurnId !== turnId);
-      state.followup = [...own, ...state.followup];
-      this.emitQueueUpdate(sessionId, state);
-      return;
-    }
-    // Stranded steering (arrived after the final step boundary, so no step is
-    // left to consume it) becomes the head of the followup queue instead of
-    // vanishing — the next turn opens with it first (grok-build safety). The
-    // migration is a queue change, so emit the final snapshot BEFORE the sink
-    // is cleared; otherwise observers stay on the stale pre-fold snapshot.
-    if (state.steering.length > 0 || own.length > 0) {
-      state.followup = [...own, ...state.steering, ...state.followup];
-      state.inFlight = state.inFlight.filter((message) => message.issuingTurnId !== turnId);
-      state.steering = [];
-      this.emitQueueUpdate(sessionId, state);
+  async materializeRootSourceMessages(input: {
+    sessionId: string;
+    turnId: string;
+    messages: readonly { messageId: string; content: MessageContent }[];
+  }): Promise<void> {
+    const existingIds = new Set(
+      (await this.deps.store.readMessages(input.sessionId)).map((message) => message.id),
+    );
+    for (const message of input.messages) {
+      if (existingIds.has(message.messageId)) continue;

Review Comment:
   [P1] Steering folded into a successor is never rebound, so every later Host start fails.
   
   `materializeRootSourceMessages` dedupes across the **entire Session**: `readMessages(input.sessionId)` collects every existing message id, and a hit takes the `continue`. It only skips the write — it **does not rebind that row's `turnId` to the successor**.
   
   Trigger path: the current root accepts steering and its canonical `UserMessage` is already written under the predecessor turn; the backend reaches a terminal state before pulling that steering; the steering is folded into the successor; the successor starts with `recordInitialUserMessage:false`, and this session-wide dedupe leaves the source row under the predecessor forever.
   
   Consequence: the successor completes this time, but on the next Host start recovery sees the Run already exists while no source row sits under the successor, and throws `Admitted queued Turn <id> has incomplete source materialization`. Readiness fails, so **the Host for the whole workspace will not come up**. A mixed steering + follow-up case fails the same way at source index 0.
   
   Why the existing guards do not catch it: atomic admission binds to the predecessor; the global dedupe prevents the write rather than completing a rebind; partial-prefix recovery only applies before the Run is created.
   
   Suggested direction: keep the single canonical identity, but let the successor admission atomically rebind/move this row — or have materialization and recovery explicitly accept and validate steering provenance from the predecessor.
   
   <details>
   <summary>中文</summary>
   
   [P1] 折叠到 successor 的 steering 没有重新绑定,之后每次 Host 启动都会失败。
   
   `materializeRootSourceMessages` 的去重是**整个 Session 范围**的:`readMessages(input.sessionId)` 取出所有已存在的 message id,命中就 `continue`。它只是跳过写入,**不会把这条 row 的 `turnId` 改绑到 successor**。
   
   触发路径:当前 root 接受了 steering,canonical UserMessage 已经写在 predecessor turn 下;backend 还没 pull 这条 steering,root 就进入终态;steering 被折叠进 successor;successor 以 `recordInitialUserMessage:false` 启动,而这里的全局去重让 source row 始终留在 predecessor 名下。
   
   后果:successor 当次能跑完,但下一次 Host 启动时,恢复流程发现 Run 已存在、而 source row 不在 successor 下,抛 `Admitted queued Turn <id> has incomplete source materialization`,readiness 失败——**整个 workspace 的 Host 起不来**。混合 steering + followup 的情况会在 source index 0 上以同样方式失败。
   
   为什么现有守卫拦不住:atomic admission 绑定的是 predecessor;全局去重是阻止写入而不是完成改绑;partial-prefix recovery 只在 Run 创建之前才允许介入。
   
   修复方向:保持单一 canonical identity 不变,但让 successor admission 能够原子地改绑/移动这条 row;或者让 materialization 与 recovery 显式接受并校验来自 predecessor 的 steering provenance。
   
   </details>



##########
packages/storage/src/message-receipt-store.ts:
##########
@@ -58,6 +84,18 @@ export interface MessageReceiptStore {
     operationId: string,
     receipt: MessageOperationReceipt,
   ): Promise<MessageOperationReceipt>;
+  readMessageAdmission(
+    sessionId: string,
+    messageId: string,
+  ): Promise<PendingMessageAdmission | undefined>;
+  readMessageSettlement(
+    sessionId: string,
+    messageId: string,
+  ): Promise<MessageAdmissionSettlement | undefined>;
+  listPendingMessages(): Promise<readonly PendingMessageAdmission[]>;

Review Comment:
   [P1] A queued-message edit that already took effect reverts to the original instruction after a Host restart.
   
   This store's interface exposes `readMessageAdmission`, `listPendingMessages`, `commitMessageOrder`, `commitMessageRetractions` and `garbageCollectMessageAdmissions` — but **no method that updates a pending admission's content / modelContent / digest**.
   
   Meanwhile the edit path at `packages/runtime-host/src/server/message-coordinator.ts:1405-1407` is:
   
   ```
   queued.entry.content = content;
   queued.entry.modelContent = modelContent;
   this.#mutated(state);
   ```
   
   That is a purely in-memory rewrite. The `#commitReceipt('update_entry', ...)` that follows writes a Host-epoch receipt and does not touch the admission itself. Startup recovery goes through `listPendingMessages()` at `message-coordinator.ts:423`, so it reads back the **original content persisted at enqueue time**.
   
   Observed: the live projection shows the edited text; after SIGKILL, the successor source recovered from `core_message_admissions` is the pre-edit text.
   
   Consequence: an old instruction the user explicitly corrected can actually execute after an ordinary crash recovery, with whatever side effects it carries. This is not a display issue.
   
   Why the existing guards do not catch it: the revision / identity / capacity / snapshot checks all protect live mutation.
   
   Suggested direction: update this pending admission's content / modelContent / digest inside the same durable transaction, fencing identity, placement and settlement — or write a new identity and durably retract the old one.
   
   <details>
   <summary>中文</summary>
   
   [P1] 已经生效的 queued message 编辑,在 Host 重启后会退回成编辑前的原始指令。
   
   这个 store 的接口里有 `readMessageAdmission`、`listPendingMessages`、`commitMessageOrder`、`commitMessageRetractions`、`garbageCollectMessageAdmissions`,**唯独没有任何一个方法可以更新一条 pending admission 的 content / modelContent / digest**。
   
   而 `packages/runtime-host/src/server/message-coordinator.ts:1405-1407` 的编辑路径是纯内存改写 `queued.entry.content = content`,随后 `#commitReceipt('update_entry', ...)` 写的是一条 Host-epoch receipt,不改 admission 本身。启动恢复走的是 `message-coordinator.ts:423` 的 `listPendingMessages()`,读到的仍然是入队时落盘的**原始内容**。
   
   复现结果:live projection 显示编辑后的文本,SIGKILL 之后从 `core_message_admissions` 恢复出来的 successor source 是编辑前的原文。
   
   后果:用户已经确认改掉的旧指令,会在一次普通的崩溃恢复之后被真正执行,可能带来副作用。这不是显示问题。
   
   为什么现有守卫拦不住:revision / identity / capacity / snapshot 这几道检查保护的都是 live mutation。
   
   修复方向:在同一个 durable 事务里更新这条 pending admission 的 content / modelContent / digest,并对 identity、placement、settlement 加 fence;或者改成写入新 identity 并 durable retract 旧 identity。
   
   </details>



-- 
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-host): unify durable message lifecycle [maka]

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


##########
apps/desktop/src/renderer/features/workbar/tools/side-chat/use-quote-companion.ts:
##########
@@ -203,6 +202,11 @@ export function useQuoteCompanion(input: UseQuoteCompanionInput): UseQuoteCompan
       });
     unsubscribeRef.current = sideChat.subscribeEvents(forkId, (event: SessionEvent) => {
       if (!mountedRef.current) return;
+      if (turnInFlightRef.current && activeTurnIdRef.current === null && event.turnId) {
+        activeTurnIdRef.current = event.turnId;

Review Comment:
   [P2] The first event with any `turnId` cannot safely claim this send. `onBeforeSend` has just cleared `activeTurnIdRef`; a late terminal event from the prior root can arrive while Host admission starts a successor, claim the old ID here, and prevent the returned successor ID from being installed because the ref is non-null. Settlement then clears the wrong flight, while the real successor's messages are excluded by `ownTurnIdsRef`. Correlate ownership with the submit result/durable source identity instead of an arbitrary first event, and add the prior-terminal → successor-start race.



##########
packages/cli/src/pi-tui-runner.ts:
##########
@@ -540,8 +542,21 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         requestRender();
         return;
       }
-      rememberTranscriptModel(messages);
-      if (hydrateToolsWithStoredMessages(state, turnId, messages)) {
+      const newSteeringMessages = messages.filter(
+        (message): message is Extract<StoredMessage, { type: 'user' }> =>
+          message.type === 'user' &&
+          message.turnId === turnId &&
+          message.steeringEventId !== undefined &&
+          !transcriptMessageIds.has(message.id),
+      );
+      rememberTranscript(messages);
+      for (const message of newSteeringMessages) {

Review Comment:
   [P2] This adds a second renderer for the same steering identity. Production persists the user row and advances the transcript, so reconciliation appends it here; provider consumption later emits `steering_message`, which `applyMakaSessionEventToTranscript` appends again without consulting `transcriptMessageIds`. The reverse callback order also duplicates: the event appends first, then this branch still sees a new transcript ID. The new `SteeringTurnDriver` fake emits reconciliation but never the production `steering_message`, so its containment assertion misses the double row. Please make one path authoritative (or dedupe the event by message ID) and cover both orderings.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -1003,6 +1245,22 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
       }
       return failure('not_found', 'Message queue entry does not exist');
     }
+    const pending = await this.#root.commitMessageAdmission(

Review Comment:
   [P2] Promotion bypasses both admission-time capacity checks. The original submit was preflighted only as a `next_turn` follow-up; changing it to `current_turn` steering increases the encoded queue shape, while `worstCaseMessageQueueProjection` only changes entries already in `steering` to `in_flight` and reserves nothing for future promotion. A follow-up tuned just below `MESSAGE_QUEUE_PROJECTION_MAX_BYTES` is therefore accepted, then this durable commit plus the in-memory move creates an undecodable canonical projection and the refresh fail-stops/drains the Host. Build and preflight the promoted queue/root candidate before committing, with a boundary-size regression.



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -2393,175 +2278,25 @@ export class RuntimeKernel implements RuntimeKernelLike {
     );
   }
 
-  // --------------------------------------------------------------------------
-  // Steering / followup queues (authoritative source of truth)
-  // --------------------------------------------------------------------------
-
-  steer(sessionId: string, text: string): QueueEnqueueOutcome {
-    this.assertEmbeddedMessageQueue('steer');
-    // Steering's delivery contract is anchored to the runtime event ledger
-    // (fail-closed persist + durable-consume ack). Without a RuntimeEventStore
-    // that anchor does not exist — same condition as requireTerminalWrite —
-    // so fall back to a fresh turn, whose user message the SessionStore
-    // persists with the ordinary turn-open guarantee.
-    if (!this.deps.runtimeEventStore) return { kind: 'fallback' };
-    // Double responsibility (codex): with no live steering owner to inject
-    // into — the turn just ended, begin() failed, or only child/compact runs
-    // are active (they never consume this queue) — tell the caller to open a
-    // fresh turn instead so the message is never dropped.
-    const state = this.liveSteeringState(sessionId);
-    if (!state) return { kind: 'fallback' };
-    const messageId = this.deps.newId();
-    state.steering.push({ id: messageId, messageId, content: { text } });
-    this.emitQueueUpdate(sessionId, state);
-    return { kind: 'queued' };
-  }
-
-  queueMessage(sessionId: string, text: string): QueueEnqueueOutcome {
-    this.assertEmbeddedMessageQueue('queueMessage');
-    const state = this.liveSteeringState(sessionId);
-    if (!state) return { kind: 'fallback' };
-    const messageId = this.deps.newId();
-    state.followup.push({ id: messageId, messageId, content: { text } });
-    this.emitQueueUpdate(sessionId, state);
-    return { kind: 'queued' };
-  }
-
-  drainFollowup(sessionId: string): string | null {
-    this.assertEmbeddedMessageQueue('drainFollowup');
-    const state = this.steeringBySession.get(sessionId);
-    if (!state || state.followup.length === 0) return null;
-    const drained = state.followup.splice(0);
-    this.emitQueueUpdate(sessionId, state);
-    return drained.map((message) => message.content.text).join('\n\n');
-  }
-
-  retractQueue(sessionId: string): string {
-    this.assertEmbeddedMessageQueue('retractQueue');
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return '';
-    // Retract reclaims QUEUED messages only. pull() is the single atomic
-    // commit point of delivery: an in-flight lease is already committed to
-    // the running turn — its durable append may land at any moment, so
-    // handing its text back to the user here would refill AND execute the
-    // same directive. An in-flight lease settles only by the persistence
-    // fact (ack when the ledger owns it, nack back to a queue otherwise).
-    const all = [
-      ...state.steering.map((message) => message.content.text),
-      ...state.followup.map((message) => message.content.text),
-    ];
-    state.steering = [];
-    state.followup = [];
-    this.emitQueueUpdate(sessionId, state);
-    return all.join('\n\n');
-  }
-
-  private ensureSteering(sessionId: string): SessionSteeringState {
-    const existing = this.steeringBySession.get(sessionId);
-    if (existing) return existing;
-    const created: SessionSteeringState = { steering: [], inFlight: [], followup: [] };
-    this.steeringBySession.set(sessionId, created);
-    return created;
-  }
-
-  private assertEmbeddedMessageQueue(operation: string): void {
-    if (this.deps.messageAuthority) {
-      throw new RuntimeMessageAuthorityInvariantError(
-        `Hosted Runtime cannot ${operation}; the Runtime Host owns message admission and queues`,
-      );
-    }
-  }
-
-  /**
-   * The session's steering state only while a steering-capable top-level run
-   * owns it (sink registered after begin() succeeded and not yet released).
-   * Child agent and compact runs never establish ownership, so their activity
-   * alone yields undefined — enqueue must fall back rather than strand text.
-   */
-  private liveSteeringState(sessionId: string): SessionSteeringState | undefined {
-    const state = this.steeringBySession.get(sessionId);
-    return state?.sink ? state : undefined;
-  }
-
-  private emitQueueUpdate(sessionId: string, state: SessionSteeringState): void {
-    state.sink?.({
-      type: 'queue_update',
-      id: this.deps.newId(),
-      turnId: state.activeTurnId ?? '',
-      ts: this.deps.now(),
-      steering: [
-        ...state.inFlight.map((message) => message.content.text),
-        ...state.steering.map((message) => message.content.text),
-      ],
-      followup: state.followup.map((message) => message.content.text),
-      steeringEntries: [
-        ...state.inFlight.map((message) => ({
-          entryId: message.id,
-          messageId: message.messageId,
-          content: message.content,
-          placement: 'current_turn' as const,
-          state: 'in_flight' as const,
-        })),
-        ...state.steering.map((message) => ({
-          entryId: message.id,
-          messageId: message.messageId,
-          content: message.content,
-          placement: 'current_turn' as const,
-          state: 'queued' as const,
-        })),
-      ],
-      followupEntries: state.followup.map((message) => ({
-        entryId: message.id,
-        messageId: message.messageId,
-        content: message.content,
-        placement: 'next_turn' as const,
-        state: 'queued' as const,
-      })),
-    });
-  }
-
-  private clearSteering(sessionId: string): void {
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return;
-    // Same commit-point rule as retractQueue: only QUEUED messages are
-    // clearable. An in-flight lease is already committed to the running
-    // turn's delivery and settles only by the persistence fact.
-    if (state.steering.length === 0 && state.followup.length === 0) return;
-    state.steering = [];
-    state.followup = [];
-    this.emitQueueUpdate(sessionId, state);
-  }
-
-  private releaseSteeringTurn(sessionId: string, turnId: string): void {
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return;
-    // A release folds only the leases THIS turn issued; an overlapping turn's
-    // in-flight lease stays for its issuer to settle (acked = delivered, so
-    // folding it into followup would redeliver an already-executed message).
-    const own = state.inFlight.filter((message) => message.issuingTurnId === turnId);
-    if (state.activeTurnId !== turnId) {
-      // Not (or no longer) the owner. The issuer's backend settles every
-      // lease before its turn ends, so `own` is normally empty; this is a
-      // backstop that keeps a never-settled lease from stranding invisibly.
-      if (own.length === 0) return;
-      state.inFlight = state.inFlight.filter((message) => message.issuingTurnId !== turnId);
-      state.followup = [...own, ...state.followup];
-      this.emitQueueUpdate(sessionId, state);
-      return;
-    }
-    // Stranded steering (arrived after the final step boundary, so no step is
-    // left to consume it) becomes the head of the followup queue instead of
-    // vanishing — the next turn opens with it first (grok-build safety). The
-    // migration is a queue change, so emit the final snapshot BEFORE the sink
-    // is cleared; otherwise observers stay on the stale pre-fold snapshot.
-    if (state.steering.length > 0 || own.length > 0) {
-      state.followup = [...own, ...state.steering, ...state.followup];
-      state.inFlight = state.inFlight.filter((message) => message.issuingTurnId !== turnId);
-      state.steering = [];
-      this.emitQueueUpdate(sessionId, state);
+  async materializeRootSourceMessages(input: {
+    sessionId: string;
+    turnId: string;
+    messages: readonly { messageId: string; content: MessageContent }[];
+  }): Promise<void> {
+    const existingIds = new Set(
+      (await this.deps.store.readMessages(input.sessionId)).map((message) => message.id),
+    );
+    for (const message of input.messages) {
+      if (existingIds.has(message.messageId)) continue;

Review Comment:
   [P1] Steering folded into a successor is never rebound, so every later Host start fails.
   
   `materializeRootSourceMessages` dedupes across the **entire Session**: `readMessages(input.sessionId)` collects every existing message id, and a hit takes the `continue`. It only skips the write — it **does not rebind that row's `turnId` to the successor**.
   
   Trigger path: the current root accepts steering and its canonical `UserMessage` is already written under the predecessor turn; the backend reaches a terminal state before pulling that steering; the steering is folded into the successor; the successor starts with `recordInitialUserMessage:false`, and this session-wide dedupe leaves the source row under the predecessor forever.
   
   Consequence: the successor completes this time, but on the next Host start recovery sees the Run already exists while no source row sits under the successor, and throws `Admitted queued Turn <id> has incomplete source materialization`. Readiness fails, so **the Host for the whole workspace will not come up**. A mixed steering + follow-up case fails the same way at source index 0.
   
   Why the existing guards do not catch it: atomic admission binds to the predecessor; the global dedupe prevents the write rather than completing a rebind; partial-prefix recovery only applies before the Run is created.
   
   Suggested direction: keep the single canonical identity, but let the successor admission atomically rebind/move this row — or have materialization and recovery explicitly accept and validate steering provenance from the predecessor.
   
   <details>
   <summary>简体中文</summary>
   
   [P1] 折叠到 successor 的 steering 没有重新绑定,之后每次 Host 启动都会失败。
   
   `materializeRootSourceMessages` 的去重是**整个 Session 范围**的:`readMessages(input.sessionId)` 取出所有已存在的 message id,命中就 `continue`。它只是跳过写入,**不会把这条 row 的 `turnId` 改绑到 successor**。
   
   触发路径:当前 root 接受了 steering,canonical UserMessage 已经写在 predecessor turn 下;backend 还没 pull 这条 steering,root 就进入终态;steering 被折叠进 successor;successor 以 `recordInitialUserMessage:false` 启动,而这里的全局去重让 source row 始终留在 predecessor 名下。
   
   后果:successor 当次能跑完,但下一次 Host 启动时,恢复流程发现 Run 已存在、而 source row 不在 successor 下,抛 `Admitted queued Turn <id> has incomplete source materialization`,readiness 失败——**整个 workspace 的 Host 起不来**。混合 steering + followup 的情况会在 source index 0 上以同样方式失败。
   
   为什么现有守卫拦不住:atomic admission 绑定的是 predecessor;全局去重是阻止写入而不是完成改绑;partial-prefix recovery 只在 Run 创建之前才允许介入。
   
   修复方向:保持单一 canonical identity 不变,但让 successor admission 能够原子地改绑/移动这条 row;或者让 materialization 与 recovery 显式接受并校验来自 predecessor 的 steering provenance。
   
   </details>



##########
packages/storage/src/message-receipt-store.ts:
##########
@@ -58,6 +84,18 @@ export interface MessageReceiptStore {
     operationId: string,
     receipt: MessageOperationReceipt,
   ): Promise<MessageOperationReceipt>;
+  readMessageAdmission(
+    sessionId: string,
+    messageId: string,
+  ): Promise<PendingMessageAdmission | undefined>;
+  readMessageSettlement(
+    sessionId: string,
+    messageId: string,
+  ): Promise<MessageAdmissionSettlement | undefined>;
+  listPendingMessages(): Promise<readonly PendingMessageAdmission[]>;

Review Comment:
   [P1] A queued-message edit that already took effect reverts to the original instruction after a Host restart.
   
   This store's interface exposes `readMessageAdmission`, `listPendingMessages`, `commitMessageOrder`, `commitMessageRetractions` and `garbageCollectMessageAdmissions` — but **no method that updates a pending admission's content / modelContent / digest**.
   
   Meanwhile the edit path at `packages/runtime-host/src/server/message-coordinator.ts:1405-1407` is:
   
   ```
   queued.entry.content = content;
   queued.entry.modelContent = modelContent;
   this.#mutated(state);
   ```
   
   That is a purely in-memory rewrite. The `#commitReceipt('update_entry', ...)` that follows writes a Host-epoch receipt and does not touch the admission itself. Startup recovery goes through `listPendingMessages()` at `message-coordinator.ts:423`, so it reads back the **original content persisted at enqueue time**.
   
   Observed: the live projection shows the edited text; after SIGKILL, the successor source recovered from `core_message_admissions` is the pre-edit text.
   
   Consequence: an old instruction the user explicitly corrected can actually execute after an ordinary crash recovery, with whatever side effects it carries. This is not a display issue.
   
   Why the existing guards do not catch it: the revision / identity / capacity / snapshot checks all protect live mutation.
   
   Suggested direction: update this pending admission's content / modelContent / digest inside the same durable transaction, fencing identity, placement and settlement — or write a new identity and durably retract the old one.
   
   <details>
   <summary>简体中文</summary>
   
   [P1] 已经生效的 queued message 编辑,在 Host 重启后会退回成编辑前的原始指令。
   
   这个 store 的接口里有 `readMessageAdmission`、`listPendingMessages`、`commitMessageOrder`、`commitMessageRetractions`、`garbageCollectMessageAdmissions`,**唯独没有任何一个方法可以更新一条 pending admission 的 content / modelContent / digest**。
   
   而 `packages/runtime-host/src/server/message-coordinator.ts:1405-1407` 的编辑路径是纯内存改写 `queued.entry.content = content`,随后 `#commitReceipt('update_entry', ...)` 写的是一条 Host-epoch receipt,不改 admission 本身。启动恢复走的是 `message-coordinator.ts:423` 的 `listPendingMessages()`,读到的仍然是入队时落盘的**原始内容**。
   
   复现结果:live projection 显示编辑后的文本,SIGKILL 之后从 `core_message_admissions` 恢复出来的 successor source 是编辑前的原文。
   
   后果:用户已经确认改掉的旧指令,会在一次普通的崩溃恢复之后被真正执行,可能带来副作用。这不是显示问题。
   
   为什么现有守卫拦不住:revision / identity / capacity / snapshot 这几道检查保护的都是 live mutation。
   
   修复方向:在同一个 durable 事务里更新这条 pending admission 的 content / modelContent / digest,并对 identity、placement、settlement 加 fence;或者改成写入新 identity 并 durable retract 旧 identity。
   
   </details>



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/cli/src/pi-tui-runner.ts:
##########
@@ -540,8 +542,21 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         requestRender();
         return;
       }
-      rememberTranscriptModel(messages);
-      if (hydrateToolsWithStoredMessages(state, turnId, messages)) {
+      const newSteeringMessages = messages.filter(
+        (message): message is Extract<StoredMessage, { type: 'user' }> =>
+          message.type === 'user' &&
+          message.turnId === turnId &&
+          message.steeringEventId !== undefined &&
+          !transcriptMessageIds.has(message.id),
+      );
+      rememberTranscript(messages);
+      for (const message of newSteeringMessages) {

Review Comment:
   Fixed in 23455cca0 and c6a899ea5. Both the durable reconciliation path and the live steering event now deduplicate by the stable messageId owned by MakaPiTranscriptState; the duplicate runner-level identity set was removed. The regression covers durable-first and event-first arrival, and the focused CLI suite passes 204/204.



##########
packages/runtime-host/src/server/root-turn-coordinator.ts:
##########
@@ -1909,6 +1959,19 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
     if (unavailableReason) {
       return completedStart(operationUnavailable(unavailableReason));
     }
+    const initialUserMessagesMaterialized = admission.sourceMessages.some(
+      (source) => source.disposition === 'steering',
+    );
+    if (initialUserMessagesMaterialized) {
+      await this.manager.materializeRootSourceMessages({

Review Comment:
   Fixed in 0538200a5. Hosted recovery now validates materialized source UserMessages as the exact admission prefix and resumes the same root admission idempotently, while still rejecting wrong order, reused IDs, content mismatch, and incomplete sources when a Run already exists. SQLite-backed startup regressions cover both a partial prefix and all sources materialized before Run creation.



##########
apps/desktop/src/renderer/features/workbar/tools/side-chat/use-quote-companion.ts:
##########
@@ -203,6 +202,11 @@ export function useQuoteCompanion(input: UseQuoteCompanionInput): UseQuoteCompan
       });
     unsubscribeRef.current = sideChat.subscribeEvents(forkId, (event: SessionEvent) => {
       if (!mountedRef.current) return;
+      if (turnInFlightRef.current && activeTurnIdRef.current === null && event.turnId) {
+        activeTurnIdRef.current = event.turnId;

Review Comment:
   Fixed in 2e343a149 and 0d110db05. An arbitrary first event can no longer claim the send. Steering binds only through a queue_update or steering_message carrying the submitted messageId, while a new root binds to the Host-returned turnId. Events arriving before that authority is known are buffered transiently and only matching-turn events are replayed. Regressions cover both prior-terminal to successor steering and new-root text plus complete arriving before the send result.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +413,78 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverPendingAfterHostRestart(): Promise<void> {
+    const bySession = new Map<string, PendingMessageAdmission[]>();
+    for (const admission of await this.#receipts.listPendingMessages()) {
+      const admissions = bySession.get(admission.sessionId);
+      if (admissions) admissions.push(admission);
+      else bySession.set(admission.sessionId, [admission]);
+    }
+    for (const [sessionId, durable] of bySession) {
+      await this.#sessionAdmission.run(sessionId, async (admissionLease) => {
+        const pending: PendingMessageAdmission[] = [];
+        const settled: string[] = [];
+        for (const candidate of durable) {
+          const source = await this.#durableProof.readRootTurnSourceMessageReceipt(
+            sessionId,
+            candidate.messageId,
+          );
+          const consumed = source
+            ? undefined
+            : await this.#durableProof.readImmutableSteeringMessageProof(
+                sessionId,
+                candidate.messageId,
+              );
+          const stopped =
+            !source &&
+            !consumed &&
+            (await this.#durableProof.readExplicitStopProof(sessionId, candidate.runId));
+          if (source || consumed || stopped) settled.push(candidate.messageId);
+          else pending.push(candidate);
+        }
+        if (settled.length > 0) {
+          await this.#receipts.garbageCollectMessageAdmissions(sessionId, settled);

Review Comment:
   Fixed in c324308f7. Restart settlement now separates explicit Stop from ordinary GC and commits durable message retractions for stopped identities. The regression restarts after Stop and verifies that retrying the same message identity remains an operation_conflict.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -1003,6 +1245,22 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
       }
       return failure('not_found', 'Message queue entry does not exist');
     }
+    const pending = await this.#root.commitMessageAdmission(

Review Comment:
   Fixed in ee0529a4d. Promotion now builds the promoted queue and future root sources, runs the shared queue, canonical Session snapshot, interrupt-result, and root-admission capacity preflight, then rechecks revision, generation, root identity, and entry position before durable mutation. The boundary regression proves a follow-up that fits as next_turn but exceeds the in-flight steering limit is rejected without mutation.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +413,78 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverPendingAfterHostRestart(): Promise<void> {
+    const bySession = new Map<string, PendingMessageAdmission[]>();
+    for (const admission of await this.#receipts.listPendingMessages()) {
+      const admissions = bySession.get(admission.sessionId);
+      if (admissions) admissions.push(admission);
+      else bySession.set(admission.sessionId, [admission]);
+    }
+    for (const [sessionId, durable] of bySession) {
+      await this.#sessionAdmission.run(sessionId, async (admissionLease) => {
+        const pending: PendingMessageAdmission[] = [];
+        const settled: string[] = [];
+        for (const candidate of durable) {
+          const source = await this.#durableProof.readRootTurnSourceMessageReceipt(
+            sessionId,
+            candidate.messageId,
+          );
+          const consumed = source
+            ? undefined
+            : await this.#durableProof.readImmutableSteeringMessageProof(

Review Comment:
   Fixed in c324308f7. Restart recovery no longer treats a steering_message echo as provider consumption. Only a root source receipt settles the admission; echo-only steering remains pending and is recovered into the successor root. The focused restart regression covers exactly echo persisted with no later provider dispatch.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -727,17 +936,37 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
           continue;
         }
         const result = { disposition, queueRevision: candidateRevision + 1 } as const;
+        let durableAdmittedAt: number | undefined;
+        if (!durableAdmission) {
+          const admitted = await this.#root.commitMessageAdmission(

Review Comment:
   Fixed in 8d591b942. The submit result is now constructed after the entry mutation from the authoritative state.revision. The paused commitMessageAdmission regression races pull plus ack while the durable commit is suspended and verifies both the returned and projected revision are 4 rather than the stale preflight revision 2.



-- 
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: persist steering at message admission [maka]

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


##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -568,12 +586,27 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
             : failure('operation_conflict', 'Message identity has a different payload');
         }
       }
+      const durableAdmission = isCurrentEpoch
+        ? undefined
+        : await this.#durableProof.readSteeringAdmission(input.sessionId, input.messageId);

Review Comment:
   Fixed at the Host-owned lifecycle boundary. A steering submission now commits `core_pending_steering_admissions` before the transcript append or in-memory queue mutation. Production startup calls `recoverPendingAfterHostRestart()` only after interrupted Runs have been terminalized and root recovery has completed, then admits one successor root from the exact stored identity and payload. The production composition regression seeds an existing running Run, the durable steering transcript row, and no queue/provider proof; restart produces exactly two root admissions, clears the pending record, and keeps only the original two user messages without a duplicate resend.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +418,75 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverRootTurn(identity: RuntimeMessageRunIdentity): Promise<void> {

Review Comment:
   The direct-helper test and disconnected helper were removed. Coverage now enters through `createExecutionRuntimeHostComposition(...).recover()` with real SQLite stores, an existing running Run, one pending durable steering admission, and no in-memory queue/provider proof. The regression fails if the production startup call is removed and asserts the successor admission, old-Run terminalization, pending settlement, and non-duplicated user history.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -727,6 +795,15 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
           continue;
         }
         const result = { disposition, queueRevision: candidateRevision + 1 } as const;
+        if (disposition === 'steering' && !durableAdmission) {

Review Comment:
   Fixed for promotion through the same lifecycle. `queue.entry.promote` now commits the pending steering admission and transcript row before moving the entry from follow-up to steering. The focused promotion test verifies the durable commit happens before the entry becomes non-retractable.



##########
packages/runtime-host/src/server/root-turn-coordinator.ts:
##########
@@ -1966,6 +1990,7 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
     try {
       this.messages.reserveRootTurn(messageIdentity);
       messageReserved = true;
+      await this.messages.recoverRootTurn(messageIdentity);

Review Comment:
   Replaced the unreachable recovery path rather than extending it. `recoverRootTurn` and the transcript scan were removed. Production startup now invokes pending-steering recovery after `recoverInterruptedSessionsStrict()` and `coordinator.recover()`, when the interrupted existing Run is terminal and the root is idle. The production regression exercises this exact existing-Run crash state and observes the expected successor root chain of 2.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -1451,22 +1532,28 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
       );
     }
     state.phase = 'closed';
-    const retracted = this.#retractQueued(state);
+    const retracted = this.#retractFollowups(state);
+    this.#discardQueuedSteering(state);
     state.generation += 1;
     this.#mutated(state);
     const result = { queueRevision: state.revision, retracted };
     state.stopFence = { identity: { ...identity }, result };
     return result;
   }
 
-  #retractQueued(state: SessionState): RetractedMessageSnapshot[] {
-    const entries = [...state.steering, ...state.followup];
-    state.steering = [];
+  #retractFollowups(state: SessionState): RetractedMessageSnapshot[] {
+    const entries = state.followup;
     state.followup = [];
     for (const entry of entries) this.#releaseEntry(entry);
     return entries.map(retractedSnapshot);
   }
 
+  #discardQueuedSteering(state: SessionState): void {
+    const entries = state.steering;

Review Comment:
   Fixed at the Stop/discard boundary. Promoted and directly submitted steering now have a pending durable admission. Intentional Stop/Drain settles those pending identities before `#discardQueuedSteering`; crash recovery preserves unresolved identities instead. The drain regression verifies the pending count changes from 1 to 0 before the queue is discarded.



-- 
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: persist steering at message admission [maka]

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


##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -1003,6 +1224,24 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
       }
       return failure('not_found', 'Message queue entry does not exist');
     }
+    const pending = await this.#receipts.commitPendingSteering({

Review Comment:
   [P1] A failed promotion can later execute a message that the user successfully retracted. This call first creates the pending recovery record; if `commitSteeringAdmission` then rejects, the new regression at `message-coordinator.test.ts:664-693` deliberately leaves the entry in `followup`. `queue.retract` removes that entry via `#retractFollowups`, but never settles this pending record, so `recoverPendingAfterHostRestart()` materializes and starts it after a restart. Repro: promote → inject transcript-append failure → retract the still-visible follow-up → restart; the supposedly retracted instruction becomes a recovered root. A normal retry cannot reliably heal the cut either: callers generate a fresh `admittedAt`, while the production SQLite store treats a timestamp change for the same session/message identity as `Pending steering admission identity conflict` (the in-memory fake silently returns the old record). Once this record is committed, either make the entry non-retra
 ctable/cancel the record atomically on every retract path, and make retries identity-stable.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +430,76 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverPendingAfterHostRestart(): Promise<void> {
+    const bySession = new Map<string, PendingSteeringAdmission[]>();
+    for (const admission of await this.#receipts.listPendingSteering()) {
+      const admissions = bySession.get(admission.sessionId);
+      if (admissions) admissions.push(admission);
+      else bySession.set(admission.sessionId, [admission]);
+    }
+    for (const [sessionId, durable] of bySession) {
+      await this.#sessionAdmission.run(sessionId, async (admissionLease) => {
+        const pending: PendingSteeringAdmission[] = [];
+        const settled: string[] = [];
+        for (const candidate of durable) {
+          const source = await this.#durableProof.readRootTurnSourceMessageReceipt(
+            sessionId,
+            candidate.messageId,
+          );
+          const consumed = source
+            ? undefined
+            : await this.#durableProof.readImmutableSteeringMessageProof(
+                sessionId,
+                candidate.messageId,
+              );
+          if (source || consumed) settled.push(candidate.messageId);
+          else pending.push(candidate);
+        }
+        if (settled.length > 0) {
+          await this.#receipts.settlePendingSteering(sessionId, settled);
+        }
+        if (pending.length === 0) return;
+        const header = await this.#root.readSessionHeader(sessionId);
+        if (!header || header.isArchived || header.unavailableReason) {
+          throw new RuntimeMessageAuthorityInvariantError(
+            'Pending steering recovery found an unavailable Session',
+          );
+        }
+        if ((await this.#root.readRootState(sessionId)).kind !== 'idle') {
+          throw new RuntimeMessageAuthorityInvariantError(
+            'Pending steering recovery requires an idle root after interrupted Run recovery',
+          );
+        }
+        if (!this.#root.materializeSteeringAdmissions || !this.#root.startRecoveredSteering) {
+          throw new RuntimeMessageAuthorityInvariantError(
+            'Pending steering recovery authority is unavailable',
+          );
+        }
+        await this.#root.materializeSteeringAdmissions(pending);
+        const sources = pending.map(pendingSteeringSource);
+        const started = await this.#root.startRecoveredSteering(
+          {
+            sessionId,
+            content: aggregateMessageContent(pending.map((entry) => entry.modelContent)),
+            submittedContent: aggregateMessageContent(pending.map((entry) => entry.content)),
+            sources,
+            initiatingConnectionId: pending[0]!.initiatingConnectionId,

Review Comment:
   [P1] Restart recovery merges all pending steering for a session and binds the resulting root to only the first submitter's client capabilities. The uninterrupted handoff deliberately uses `sameInitiatingClientPrefix()` to split B-then-A follow-ups into separate roots, and `root-turn-coordinator.test.ts` verifies each root sees its own client's ephemeral tools. After a crash, two unconsumed admissions from B and A instead reach this single batch; `startRecoveredSteering()` calls `bindConfirmedFollowup` with B's ID, so A's instruction executes with B's turn-affine Host tools/capabilities. Partition recovery into the same contiguous initiating-client batches as normal terminal handoff, starting each batch under its own connection identity.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -496,6 +623,27 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     this.#draining = true;
   }
 
+  async prepareStopFence(identity: RuntimeMessageRunIdentity): Promise<void> {
+    const state = this.#sessions.get(identity.sessionId);
+    // A root handoff can durably replace or release this identity before a concurrent
+    // administrative Stop reaches the Session lane. The authoritative fence
+    // commit still rejects a genuine mismatch if the Stop disposition needs it.
+    if (!state?.reservedRoot || !sameRun(state.reservedRoot, identity)) return;
+    if (state.steeringDiscardPreparedFor) {
+      if (!sameRun(state.steeringDiscardPreparedFor, identity)) {
+        throw new RuntimeMessageAuthorityInvariantError(
+          'Steering discard preparation belongs to another root Turn',
+        );
+      }
+      return;
+    }
+    await this.#receipts.settlePendingSteering(

Review Comment:
   [P1] This deletes the only restart-delivery record before the Stop fence is committed or durable. Every Stop caller awaits `prepareStopFence()` first; only afterward does `declareStopFence()` commit the in-memory queue fence and await `claimRunClosure`. A Host crash/failure in that window leaves the admitted user row visible in the transcript but no pending record, and startup terminalizes the interrupted run before pending-steering recovery, so the message is never delivered and no successor is created even though Stop itself never became durable. The successful-Stop behavior is fine; this is the pre-fence crash window. Couple pending settlement to a durable Stop/fence fact, or reverse the durable ordering so recovery can distinguish an accepted Stop from an interrupted attempt.



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +413,78 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverPendingAfterHostRestart(): Promise<void> {
+    const bySession = new Map<string, PendingMessageAdmission[]>();
+    for (const admission of await this.#receipts.listPendingMessages()) {
+      const admissions = bySession.get(admission.sessionId);
+      if (admissions) admissions.push(admission);
+      else bySession.set(admission.sessionId, [admission]);
+    }
+    for (const [sessionId, durable] of bySession) {
+      await this.#sessionAdmission.run(sessionId, async (admissionLease) => {
+        const pending: PendingMessageAdmission[] = [];
+        const settled: string[] = [];
+        for (const candidate of durable) {
+          const source = await this.#durableProof.readRootTurnSourceMessageReceipt(
+            sessionId,
+            candidate.messageId,
+          );
+          const consumed = source
+            ? undefined
+            : await this.#durableProof.readImmutableSteeringMessageProof(
+                sessionId,
+                candidate.messageId,
+              );
+          const stopped =
+            !source &&
+            !consumed &&
+            (await this.#durableProof.readExplicitStopProof(sessionId, candidate.runId));
+          if (source || consumed || stopped) settled.push(candidate.messageId);
+          else pending.push(candidate);
+        }
+        if (settled.length > 0) {
+          await this.#receipts.garbageCollectMessageAdmissions(sessionId, settled);

Review Comment:
   [P1] Explicitly stopped messages need durable retraction settlement, not plain GC. This restart path merges `stopped` with source/consumed admissions and deletes all of them, while the live terminal path below correctly sends stopped identities to `commitMessageRetractions` (`:505-526`). After queueing a follow-up, recording the exact Run's Stop proof, restarting, and retrying the same message ID/content, my probe was accepted again instead of returning `operation_conflict`; the cancelled message can execute under its resurrected identity. Please split the recovery sets the same way as the live path: GC source/consumed, commit retractions for stopped.
   
   ---
   
   [P1] 显式 Stop 的消息需要写 durable retraction settlement,不能只做 GC。这个重启路径把 `stopped` 与 source/consumed 合并后一起删除,而下方 live terminal 路径(`:505-526`)会正确调用 `commitMessageRetractions`。我的探针先排入 follow-up、写入 exact Run 的 Stop proof、重启,再用同一 message ID/content 重试;实际重新成功,而不是 `operation_conflict`,被取消的消息身份因此可以复活并执行。请与 live 路径同样分流:source/consumed 做 GC,stopped 写 retraction settlement。



##########
packages/runtime-host/src/server/root-turn-coordinator.ts:
##########
@@ -1909,6 +1959,19 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
     if (unavailableReason) {
       return completedStart(operationUnavailable(unavailableReason));
     }
+    const initialUserMessagesMaterialized = admission.sourceMessages.some(
+      (source) => source.disposition === 'steering',
+    );
+    if (initialUserMessagesMaterialized) {
+      await this.manager.materializeRootSourceMessages({

Review Comment:
   [P1] A crash after source materialization but before Run creation prevents every later Host startup. For a queued root containing steering, this persists each source UserMessage first (`runtime-kernel.ts:2281-2299`) and only then checks/creates the Run. If the process exits after any append, `prepareHostedExecutionRecovery` sees a UserMessage with no Run and throws at `hosted-execution-recovery.ts:147-150`. A SQLite-backed startup probe with exactly `root admission + materialized source + no Run` exited before readiness with `Admitted Turn ... has a UserMessage but no Run`. Existing recovery tests cover the states before materialization or after Run creation, not this intermediate durable state. Please either make admission/materialization/Run establishment recoverably atomic, or teach recovery to validate and resume this partially materialized state idempotently.
   
   ---
   
   [P1] source materialization 之后、Run 创建之前崩溃,会让此后每次 Host 启动都失败。含 steering 的 queued root 会先逐条持久化 source UserMessage(`runtime-kernel.ts:2281-2299`),之后才检查/创建 Run;进程在任一次 append 后退出,`prepareHostedExecutionRecovery` 会在 `hosted-execution-recovery.ts:147-150` 看到“有 UserMessage、无 Run”并直接抛错。SQLite-backed 启动探针精确构造 `root admission + materialized source + no Run`,实际在 readiness 前退出,错误为 `Admitted Turn ... has a UserMessage but no Run`。现有恢复测试只覆盖 materialization 前或 Run 已存在,没覆盖这个中间 durable state。请让 admission/materialization/Run 建立在恢复意义上原子,或让 recovery 能验证并幂等续跑这类部分物化状态。



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +413,78 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverPendingAfterHostRestart(): Promise<void> {
+    const bySession = new Map<string, PendingMessageAdmission[]>();
+    for (const admission of await this.#receipts.listPendingMessages()) {
+      const admissions = bySession.get(admission.sessionId);
+      if (admissions) admissions.push(admission);
+      else bySession.set(admission.sessionId, [admission]);
+    }
+    for (const [sessionId, durable] of bySession) {
+      await this.#sessionAdmission.run(sessionId, async (admissionLease) => {
+        const pending: PendingMessageAdmission[] = [];
+        const settled: string[] = [];
+        for (const candidate of durable) {
+          const source = await this.#durableProof.readRootTurnSourceMessageReceipt(
+            sessionId,
+            candidate.messageId,
+          );
+          const consumed = source
+            ? undefined
+            : await this.#durableProof.readImmutableSteeringMessageProof(

Review Comment:
   [P1] A persisted steering echo is not proof that the provider consumed the message. `AiSdkBackend` persists the `steering_message` event before adding it to the provider input and before the next request is dispatched (`ai-sdk-backend.ts:4532-4553`). Its own abort comment says the ledger owns the message and **the next turn replays it**, while also stating that no request has yet been built. A stop or process exit can therefore land after this proof exists but before the model sees the message; the existing final-drain test demonstrates exactly that window with one provider call. On restart, this branch treats the echo as settled and GC's the admission, so the promised next-turn replay cannot happen. My focused probe inserted an admission plus only this immutable echo; recovery produced zero batches and deleted the admission. Please represent provider consumption with a fact that is actually downstream of dispatch, or keep echo-only admissions unresolved and carry them into the su
 ccessor root.
   
   ---
   
   [P1] 已持久化的 steering echo 不能证明 provider 已经消费消息。`AiSdkBackend` 在把 steering 加入 provider 输入、发起下一次请求之前,就先持久化 `steering_message`(`ai-sdk-backend.ts:4532-4553`);它自己的 abort 注释同时写明“请求尚未构建”且“下一 turn 会重放”。Stop 或进程退出因此可以落在“echo 已存在、模型尚未看到消息”的窗口,现有 final-drain 测试也已经证明该窗口只发生一次 provider call。重启后这里却把 echo 当成 settled 并 GC admission,作者声明的 next-turn replay 根本不会发生。我的定向探针只写 admission + immutable echo,实际 recovery batch=0 且 admission 被删除。请使用真正位于 dispatch 下游的消费事实,或把只有 echo 的 admission 继续视为 unresolved 并带入 successor root。



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +430,76 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverPendingAfterHostRestart(): Promise<void> {
+    const bySession = new Map<string, PendingSteeringAdmission[]>();
+    for (const admission of await this.#receipts.listPendingSteering()) {
+      const admissions = bySession.get(admission.sessionId);
+      if (admissions) admissions.push(admission);
+      else bySession.set(admission.sessionId, [admission]);
+    }
+    for (const [sessionId, durable] of bySession) {
+      await this.#sessionAdmission.run(sessionId, async (admissionLease) => {
+        const pending: PendingSteeringAdmission[] = [];
+        const settled: string[] = [];
+        for (const candidate of durable) {
+          const source = await this.#durableProof.readRootTurnSourceMessageReceipt(
+            sessionId,
+            candidate.messageId,
+          );
+          const consumed = source
+            ? undefined
+            : await this.#durableProof.readImmutableSteeringMessageProof(
+                sessionId,
+                candidate.messageId,
+              );
+          if (source || consumed) settled.push(candidate.messageId);
+          else pending.push(candidate);
+        }
+        if (settled.length > 0) {
+          await this.#receipts.settlePendingSteering(sessionId, settled);
+        }
+        if (pending.length === 0) return;
+        const header = await this.#root.readSessionHeader(sessionId);
+        if (!header || header.isArchived || header.unavailableReason) {
+          throw new RuntimeMessageAuthorityInvariantError(
+            'Pending steering recovery found an unavailable Session',
+          );
+        }
+        if ((await this.#root.readRootState(sessionId)).kind !== 'idle') {
+          throw new RuntimeMessageAuthorityInvariantError(
+            'Pending steering recovery requires an idle root after interrupted Run recovery',
+          );
+        }
+        if (!this.#root.materializeSteeringAdmissions || !this.#root.startRecoveredSteering) {
+          throw new RuntimeMessageAuthorityInvariantError(
+            'Pending steering recovery authority is unavailable',
+          );
+        }
+        await this.#root.materializeSteeringAdmissions(pending);
+        const sources = pending.map(pendingSteeringSource);
+        const started = await this.#root.startRecoveredSteering(
+          {
+            sessionId,
+            content: aggregateMessageContent(pending.map((entry) => entry.modelContent)),
+            submittedContent: aggregateMessageContent(pending.map((entry) => entry.content)),
+            sources,
+            initiatingConnectionId: pending[0]!.initiatingConnectionId,

Review Comment:
   Superseded by the durable Session execution contract in 1343cee25. Queued and recovered roots no longer inherit ephemeral capability bindings from the initiating Client. `admitQueuedMessageRoot` installs an explicit durable Session binding through `bindDurableSession`, and recovery preserves durable queue order under that single contract. The recovery regression covers admissions from two Clients aggregating into one recovered batch, while capability tests verify that dynamic Client tools are excluded.



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -2393,175 +2278,25 @@ export class RuntimeKernel implements RuntimeKernelLike {
     );
   }
 
-  // --------------------------------------------------------------------------
-  // Steering / followup queues (authoritative source of truth)
-  // --------------------------------------------------------------------------
-
-  steer(sessionId: string, text: string): QueueEnqueueOutcome {
-    this.assertEmbeddedMessageQueue('steer');
-    // Steering's delivery contract is anchored to the runtime event ledger
-    // (fail-closed persist + durable-consume ack). Without a RuntimeEventStore
-    // that anchor does not exist — same condition as requireTerminalWrite —
-    // so fall back to a fresh turn, whose user message the SessionStore
-    // persists with the ordinary turn-open guarantee.
-    if (!this.deps.runtimeEventStore) return { kind: 'fallback' };
-    // Double responsibility (codex): with no live steering owner to inject
-    // into — the turn just ended, begin() failed, or only child/compact runs
-    // are active (they never consume this queue) — tell the caller to open a
-    // fresh turn instead so the message is never dropped.
-    const state = this.liveSteeringState(sessionId);
-    if (!state) return { kind: 'fallback' };
-    const messageId = this.deps.newId();
-    state.steering.push({ id: messageId, messageId, content: { text } });
-    this.emitQueueUpdate(sessionId, state);
-    return { kind: 'queued' };
-  }
-
-  queueMessage(sessionId: string, text: string): QueueEnqueueOutcome {
-    this.assertEmbeddedMessageQueue('queueMessage');
-    const state = this.liveSteeringState(sessionId);
-    if (!state) return { kind: 'fallback' };
-    const messageId = this.deps.newId();
-    state.followup.push({ id: messageId, messageId, content: { text } });
-    this.emitQueueUpdate(sessionId, state);
-    return { kind: 'queued' };
-  }
-
-  drainFollowup(sessionId: string): string | null {
-    this.assertEmbeddedMessageQueue('drainFollowup');
-    const state = this.steeringBySession.get(sessionId);
-    if (!state || state.followup.length === 0) return null;
-    const drained = state.followup.splice(0);
-    this.emitQueueUpdate(sessionId, state);
-    return drained.map((message) => message.content.text).join('\n\n');
-  }
-
-  retractQueue(sessionId: string): string {
-    this.assertEmbeddedMessageQueue('retractQueue');
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return '';
-    // Retract reclaims QUEUED messages only. pull() is the single atomic
-    // commit point of delivery: an in-flight lease is already committed to
-    // the running turn — its durable append may land at any moment, so
-    // handing its text back to the user here would refill AND execute the
-    // same directive. An in-flight lease settles only by the persistence
-    // fact (ack when the ledger owns it, nack back to a queue otherwise).
-    const all = [
-      ...state.steering.map((message) => message.content.text),
-      ...state.followup.map((message) => message.content.text),
-    ];
-    state.steering = [];
-    state.followup = [];
-    this.emitQueueUpdate(sessionId, state);
-    return all.join('\n\n');
-  }
-
-  private ensureSteering(sessionId: string): SessionSteeringState {
-    const existing = this.steeringBySession.get(sessionId);
-    if (existing) return existing;
-    const created: SessionSteeringState = { steering: [], inFlight: [], followup: [] };
-    this.steeringBySession.set(sessionId, created);
-    return created;
-  }
-
-  private assertEmbeddedMessageQueue(operation: string): void {
-    if (this.deps.messageAuthority) {
-      throw new RuntimeMessageAuthorityInvariantError(
-        `Hosted Runtime cannot ${operation}; the Runtime Host owns message admission and queues`,
-      );
-    }
-  }
-
-  /**
-   * The session's steering state only while a steering-capable top-level run
-   * owns it (sink registered after begin() succeeded and not yet released).
-   * Child agent and compact runs never establish ownership, so their activity
-   * alone yields undefined — enqueue must fall back rather than strand text.
-   */
-  private liveSteeringState(sessionId: string): SessionSteeringState | undefined {
-    const state = this.steeringBySession.get(sessionId);
-    return state?.sink ? state : undefined;
-  }
-
-  private emitQueueUpdate(sessionId: string, state: SessionSteeringState): void {
-    state.sink?.({
-      type: 'queue_update',
-      id: this.deps.newId(),
-      turnId: state.activeTurnId ?? '',
-      ts: this.deps.now(),
-      steering: [
-        ...state.inFlight.map((message) => message.content.text),
-        ...state.steering.map((message) => message.content.text),
-      ],
-      followup: state.followup.map((message) => message.content.text),
-      steeringEntries: [
-        ...state.inFlight.map((message) => ({
-          entryId: message.id,
-          messageId: message.messageId,
-          content: message.content,
-          placement: 'current_turn' as const,
-          state: 'in_flight' as const,
-        })),
-        ...state.steering.map((message) => ({
-          entryId: message.id,
-          messageId: message.messageId,
-          content: message.content,
-          placement: 'current_turn' as const,
-          state: 'queued' as const,
-        })),
-      ],
-      followupEntries: state.followup.map((message) => ({
-        entryId: message.id,
-        messageId: message.messageId,
-        content: message.content,
-        placement: 'next_turn' as const,
-        state: 'queued' as const,
-      })),
-    });
-  }
-
-  private clearSteering(sessionId: string): void {
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return;
-    // Same commit-point rule as retractQueue: only QUEUED messages are
-    // clearable. An in-flight lease is already committed to the running
-    // turn's delivery and settles only by the persistence fact.
-    if (state.steering.length === 0 && state.followup.length === 0) return;
-    state.steering = [];
-    state.followup = [];
-    this.emitQueueUpdate(sessionId, state);
-  }
-
-  private releaseSteeringTurn(sessionId: string, turnId: string): void {
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return;
-    // A release folds only the leases THIS turn issued; an overlapping turn's
-    // in-flight lease stays for its issuer to settle (acked = delivered, so
-    // folding it into followup would redeliver an already-executed message).
-    const own = state.inFlight.filter((message) => message.issuingTurnId === turnId);
-    if (state.activeTurnId !== turnId) {
-      // Not (or no longer) the owner. The issuer's backend settles every
-      // lease before its turn ends, so `own` is normally empty; this is a
-      // backstop that keeps a never-settled lease from stranding invisibly.
-      if (own.length === 0) return;
-      state.inFlight = state.inFlight.filter((message) => message.issuingTurnId !== turnId);
-      state.followup = [...own, ...state.followup];
-      this.emitQueueUpdate(sessionId, state);
-      return;
-    }
-    // Stranded steering (arrived after the final step boundary, so no step is
-    // left to consume it) becomes the head of the followup queue instead of
-    // vanishing — the next turn opens with it first (grok-build safety). The
-    // migration is a queue change, so emit the final snapshot BEFORE the sink
-    // is cleared; otherwise observers stay on the stale pre-fold snapshot.
-    if (state.steering.length > 0 || own.length > 0) {
-      state.followup = [...own, ...state.steering, ...state.followup];
-      state.inFlight = state.inFlight.filter((message) => message.issuingTurnId !== turnId);
-      state.steering = [];
-      this.emitQueueUpdate(sessionId, state);
+  async materializeRootSourceMessages(input: {
+    sessionId: string;
+    turnId: string;
+    messages: readonly { messageId: string; content: MessageContent }[];
+  }): Promise<void> {
+    const existingIds = new Set(
+      (await this.deps.store.readMessages(input.sessionId)).map((message) => message.id),
+    );
+    for (const message of input.messages) {
+      if (existingIds.has(message.messageId)) continue;

Review Comment:
   Fixed on the current head. Folded steering keeps its single transcript row under the predecessor, while successor materialization and startup recovery now explicitly validate that predecessor provenance instead of requiring a duplicate successor row. The regression now covers an edited predecessor steering source executing in the successor and surviving another Host restart.



##########
packages/storage/src/message-receipt-store.ts:
##########
@@ -58,6 +84,18 @@ export interface MessageReceiptStore {
     operationId: string,
     receipt: MessageOperationReceipt,
   ): Promise<MessageOperationReceipt>;
+  readMessageAdmission(
+    sessionId: string,
+    messageId: string,
+  ): Promise<PendingMessageAdmission | undefined>;
+  readMessageSettlement(
+    sessionId: string,
+    messageId: string,
+  ): Promise<MessageAdmissionSettlement | undefined>;
+  listPendingMessages(): Promise<readonly PendingMessageAdmission[]>;

Review Comment:
   Fixed on the current head. Queued edits now go through SessionAuthorityStore.updateMessageAdmission(), which atomically updates the exact unsettled admission and its existing steering transcript when applicable. MessageReceiptStore no longer owns a parallel content-update path. Identity, placement, disposition, timestamp, and settlement are fenced before the live queue mutates; focused storage, coordinator, and restart regressions pass.



-- 
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: persist steering at message admission [maka]

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

   Follow-up on the CI caveat in my review: the hosted run at `946f4268282146af26f4ab2502fbcecba8fdfc35` has since finished and `test` is `completed/success`. Correcting the note that it was still in progress — the two findings above are unchanged, since neither depended on that result.


-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +413,78 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverPendingAfterHostRestart(): Promise<void> {
+    const bySession = new Map<string, PendingMessageAdmission[]>();
+    for (const admission of await this.#receipts.listPendingMessages()) {
+      const admissions = bySession.get(admission.sessionId);
+      if (admissions) admissions.push(admission);
+      else bySession.set(admission.sessionId, [admission]);
+    }
+    for (const [sessionId, durable] of bySession) {
+      await this.#sessionAdmission.run(sessionId, async (admissionLease) => {
+        const pending: PendingMessageAdmission[] = [];
+        const settled: string[] = [];
+        for (const candidate of durable) {
+          const source = await this.#durableProof.readRootTurnSourceMessageReceipt(
+            sessionId,
+            candidate.messageId,
+          );
+          const consumed = source
+            ? undefined
+            : await this.#durableProof.readImmutableSteeringMessageProof(

Review Comment:
   [P1] A persisted steering echo is not proof that the provider consumed the message. `AiSdkBackend` persists the `steering_message` event before adding it to the provider input and before the next request is dispatched (`ai-sdk-backend.ts:4532-4553`). Its own abort comment says the ledger owns the message and **the next turn replays it**, while also stating that no request has yet been built. A stop or process exit can therefore land after this proof exists but before the model sees the message; the existing final-drain test demonstrates exactly that window with one provider call. On restart, this branch treats the echo as settled and GC's the admission, so the promised next-turn replay cannot happen. My focused probe inserted an admission plus only this immutable echo; recovery produced zero batches and deleted the admission. Please represent provider consumption with a fact that is actually downstream of dispatch, or keep echo-only admissions unresolved and carry them into the su
 ccessor root.\n\n<details>\n<summary>中文</summary>\n\n[P1] 已持久化的 steering echo 不能证明 provider 已经消费消息。`AiSdkBackend` 在把 steering 加入 provider 输入、发起下一次请求之前,就先持久化 `steering_message`(`ai-sdk-backend.ts:4532-4553`);它自己的 abort 注释同时写明“请求尚未构建”且“下一 turn 会重放”。Stop 或进程退出因此可以落在“echo 已存在、模型尚未看到消息”的窗口,现有 final-drain 测试也已经证明该窗口只发生一次 provider call。重启后这里却把 echo 当成 settled 并 GC admission,作者声明的 next-turn replay 根本不会发生。我的定向探针只写 admission + immutable echo,实际 recovery batch=0 且 admission 被删除。请使用真正位于 dispatch 下游的消费事实,或把只有 echo 的 admission 继续视为 unresolved 并带入 successor root。\n\n</details>



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -396,6 +413,78 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     state.phase = 'open';
   }
 
+  async recoverPendingAfterHostRestart(): Promise<void> {
+    const bySession = new Map<string, PendingMessageAdmission[]>();
+    for (const admission of await this.#receipts.listPendingMessages()) {
+      const admissions = bySession.get(admission.sessionId);
+      if (admissions) admissions.push(admission);
+      else bySession.set(admission.sessionId, [admission]);
+    }
+    for (const [sessionId, durable] of bySession) {
+      await this.#sessionAdmission.run(sessionId, async (admissionLease) => {
+        const pending: PendingMessageAdmission[] = [];
+        const settled: string[] = [];
+        for (const candidate of durable) {
+          const source = await this.#durableProof.readRootTurnSourceMessageReceipt(
+            sessionId,
+            candidate.messageId,
+          );
+          const consumed = source
+            ? undefined
+            : await this.#durableProof.readImmutableSteeringMessageProof(
+                sessionId,
+                candidate.messageId,
+              );
+          const stopped =
+            !source &&
+            !consumed &&
+            (await this.#durableProof.readExplicitStopProof(sessionId, candidate.runId));
+          if (source || consumed || stopped) settled.push(candidate.messageId);
+          else pending.push(candidate);
+        }
+        if (settled.length > 0) {
+          await this.#receipts.garbageCollectMessageAdmissions(sessionId, settled);

Review Comment:
   [P1] Explicitly stopped messages need durable retraction settlement, not plain GC. This restart path merges `stopped` with source/consumed admissions and deletes all of them, while the live terminal path below correctly sends stopped identities to `commitMessageRetractions` (`:505-526`). After queueing a follow-up, recording the exact Run's Stop proof, restarting, and retrying the same message ID/content, my probe was accepted again instead of returning `operation_conflict`; the cancelled message can execute under its resurrected identity. Please split the recovery sets the same way as the live path: GC source/consumed, commit retractions for stopped.\n\n<details>\n<summary>中文</summary>\n\n[P1] 显式 Stop 的消息需要写 durable retraction settlement,不能只做 GC。这个重启路径把 `stopped` 与 source/consumed 合并后一起删除,而下方 live terminal 路径(`:505-526`)会正确调用 `commitMessageRetractions`。我的探针先排入 follow-up、写�
 � exact Run 的 Stop proof、重启,再用同一 message ID/content 重试;实际重新成功,而不是 `operation_conflict`,被取消的消息身份因此可以复活并执行。请与 live 路径同样分流:source/consumed 做 GC,stopped 写 retraction settlement。\n\n</details>



-- 
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: persist steering at message admission [maka]

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


##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -727,6 +795,15 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
           continue;
         }
         const result = { disposition, queueRevision: candidateRevision + 1 } as const;
+        if (disposition === 'steering' && !durableAdmission) {

Review Comment:
   [P1] Durability is added only on the direct submit path. `queue.entry.promote` still moves a follow-up into `state.steering` and immediately makes it non-retractable without calling `commitSteeringAdmission`. The real Desktop path is the queue card's “Send now” action. If the user stops before the next provider step pulls it (or the Host dies), there is no transcript record that can recover the message. Commit the steering admission before exposing the promoted state, or keep the entry retractable until that commit succeeds; add a promote→Stop/crash regression.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -568,12 +586,27 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
             : failure('operation_conflict', 'Message identity has a different payload');
         }
       }
+      const durableAdmission = isCurrentEpoch
+        ? undefined
+        : await this.#durableProof.readSteeringAdmission(input.sessionId, input.messageId);

Review Comment:
   [P1] This recovery proof has no production caller that can present its key after the fault it is meant to recover. A crash after `commitSteeringAdmission` durably appends the user row but before the queue push/submit receipt causes the mutation request to end as outcome-unknown. The reconnecting client does not replay mutations; CLI and Desktop both generate `messageId` inside each new submission, so a user resend uses the new epoch and a new ID and never reaches this old-epoch/same-ID branch. A production-shaped fault probe therefore produced durable admissions `[oldId, newId]`: the transcript contains two identical user rows, while only `newId` enters the delivery queue. The added test manually reuses the old ID, proving a protocol capability that the clients do not retain or invoke. Please either make this durable fact self-rehydrate admission on Host recovery, or persist and automatically replay the exact original submit identity/payload from the client, with a reconnect fault
  test through the real client seam.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -1451,22 +1532,28 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
       );
     }
     state.phase = 'closed';
-    const retracted = this.#retractQueued(state);
+    const retracted = this.#retractFollowups(state);
+    this.#discardQueuedSteering(state);
     state.generation += 1;
     this.#mutated(state);
     const result = { queueRevision: state.revision, retracted };
     state.stopFence = { identity: { ...identity }, result };
     return result;
   }
 
-  #retractQueued(state: SessionState): RetractedMessageSnapshot[] {
-    const entries = [...state.steering, ...state.followup];
-    state.steering = [];
+  #retractFollowups(state: SessionState): RetractedMessageSnapshot[] {
+    const entries = state.followup;
     state.followup = [];
     for (const entry of entries) this.#releaseEntry(entry);
     return entries.map(retractedSnapshot);
   }
 
+  #discardQueuedSteering(state: SessionState): void {
+    const entries = state.steering;

Review Comment:
   [P1 — same promotion finding] This silent discard is the reachable loss sink for an undurable promoted entry. Stop returns snapshots only from `#retractFollowups`; `#discardQueuedSteering` releases entries without returning them. Diagnostic path: follow-up submit → promote succeeds with zero steering admissions → Stop yields `retracted=[]`, `steering=[]`, `followup=[]`. Because promotion created no durable row, the text is neither in the transcript nor restored to the draft.



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -1003,6 +1224,24 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
       }
       return failure('not_found', 'Message queue entry does not exist');
     }
+    const pending = await this.#receipts.commitPendingSteering({

Review Comment:
   Addressed in 1343cee25. Retraction now commits a durable settlement before removing the in-memory queue entry. The settlement records the original placement and content digest, so retries from both the old and current Host epochs return operation_conflict. The regression `retract settles a failed promotion so restart cannot recover it` covers promotion failure → retract → restart → retry, and promotion retries reuse the canonical durable admission timestamp.



##########
packages/runtime-host/src/server/message-coordinator.ts:
##########
@@ -496,6 +623,27 @@ export class HostMessageCoordinator implements RuntimeMessageAuthority {
     this.#draining = true;
   }
 
+  async prepareStopFence(identity: RuntimeMessageRunIdentity): Promise<void> {
+    const state = this.#sessions.get(identity.sessionId);
+    // A root handoff can durably replace or release this identity before a concurrent
+    // administrative Stop reaches the Session lane. The authoritative fence
+    // commit still rejects a genuine mismatch if the Stop disposition needs it.
+    if (!state?.reservedRoot || !sameRun(state.reservedRoot, identity)) return;
+    if (state.steeringDiscardPreparedFor) {
+      if (!sameRun(state.steeringDiscardPreparedFor, identity)) {
+        throw new RuntimeMessageAuthorityInvariantError(
+          'Steering discard preparation belongs to another root Turn',
+        );
+      }
+      return;
+    }
+    await this.#receipts.settlePendingSteering(

Review Comment:
   Addressed in 1343cee25. The immutable terminal Stop fact is now the cut: a crash before that fact leaves the admission unresolved and recoverable, while `prepareTerminalTransition` commits durable retraction settlements for unconsumed admissions only after the exact Run has explicit Stop proof. This distinguishes an unconfirmed Stop attempt from a confirmed Stop without deleting the restart-delivery record in the pre-fence window.



-- 
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-host): unify durable message lifecycle [maka]

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


##########
packages/storage/src/message-receipt-store.ts:
##########
@@ -58,6 +84,18 @@ export interface MessageReceiptStore {
     operationId: string,
     receipt: MessageOperationReceipt,
   ): Promise<MessageOperationReceipt>;
+  readMessageAdmission(
+    sessionId: string,
+    messageId: string,
+  ): Promise<PendingMessageAdmission | undefined>;
+  readMessageSettlement(
+    sessionId: string,
+    messageId: string,
+  ): Promise<MessageAdmissionSettlement | undefined>;
+  listPendingMessages(): Promise<readonly PendingMessageAdmission[]>;

Review Comment:
   [P1] 已经生效的 queued message 编辑,在 Host 重启后会退回成编辑前的原始指令。
   
   这个 store 的接口里有 `readMessageAdmission`、`listPendingMessages`、`commitMessageOrder`、`commitMessageRetractions`、`garbageCollectMessageAdmissions`,**唯独没有任何一个方法可以更新一条 pending admission 的 content / modelContent / digest**。
   
   而 `packages/runtime-host/src/server/message-coordinator.ts:1405-1407` 的编辑路径是:
   
   ```
   queued.entry.content = content;
   queued.entry.modelContent = modelContent;
   this.#mutated(state);
   ```
   
   纯内存改写,随后 `#commitReceipt('update_entry', ...)` 写的是一条 Host-epoch receipt,不改 admission 本身。启动恢复走的是 `message-coordinator.ts:423` 的 `listPendingMessages()`,读到的仍然是入队时落盘的**原始内容**。
   
   复现结果:live projection 显示编辑后的文本,SIGKILL 之后从 `core_message_admissions` 恢复出来的 successor source 是编辑前的原文。
   
   后果:用户已经确认改掉的旧指令,会在一次普通的崩溃恢复之后被真正执行,可能带来副作用。这不是显示问题。
   
   为什么现有守卫拦不住:revision / identity / capacity / snapshot 这几道检查保护的都是 live mutation。
   
   修复方向:在同一个 durable 事务里更新这条 pending admission 的 content / modelContent / digest,并对 identity、placement、settlement 加 fence;或者改成写入新 identity 并 durable retract 旧 identity。



##########
packages/runtime/src/runtime-kernel.ts:
##########
@@ -2393,175 +2278,25 @@ export class RuntimeKernel implements RuntimeKernelLike {
     );
   }
 
-  // --------------------------------------------------------------------------
-  // Steering / followup queues (authoritative source of truth)
-  // --------------------------------------------------------------------------
-
-  steer(sessionId: string, text: string): QueueEnqueueOutcome {
-    this.assertEmbeddedMessageQueue('steer');
-    // Steering's delivery contract is anchored to the runtime event ledger
-    // (fail-closed persist + durable-consume ack). Without a RuntimeEventStore
-    // that anchor does not exist — same condition as requireTerminalWrite —
-    // so fall back to a fresh turn, whose user message the SessionStore
-    // persists with the ordinary turn-open guarantee.
-    if (!this.deps.runtimeEventStore) return { kind: 'fallback' };
-    // Double responsibility (codex): with no live steering owner to inject
-    // into — the turn just ended, begin() failed, or only child/compact runs
-    // are active (they never consume this queue) — tell the caller to open a
-    // fresh turn instead so the message is never dropped.
-    const state = this.liveSteeringState(sessionId);
-    if (!state) return { kind: 'fallback' };
-    const messageId = this.deps.newId();
-    state.steering.push({ id: messageId, messageId, content: { text } });
-    this.emitQueueUpdate(sessionId, state);
-    return { kind: 'queued' };
-  }
-
-  queueMessage(sessionId: string, text: string): QueueEnqueueOutcome {
-    this.assertEmbeddedMessageQueue('queueMessage');
-    const state = this.liveSteeringState(sessionId);
-    if (!state) return { kind: 'fallback' };
-    const messageId = this.deps.newId();
-    state.followup.push({ id: messageId, messageId, content: { text } });
-    this.emitQueueUpdate(sessionId, state);
-    return { kind: 'queued' };
-  }
-
-  drainFollowup(sessionId: string): string | null {
-    this.assertEmbeddedMessageQueue('drainFollowup');
-    const state = this.steeringBySession.get(sessionId);
-    if (!state || state.followup.length === 0) return null;
-    const drained = state.followup.splice(0);
-    this.emitQueueUpdate(sessionId, state);
-    return drained.map((message) => message.content.text).join('\n\n');
-  }
-
-  retractQueue(sessionId: string): string {
-    this.assertEmbeddedMessageQueue('retractQueue');
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return '';
-    // Retract reclaims QUEUED messages only. pull() is the single atomic
-    // commit point of delivery: an in-flight lease is already committed to
-    // the running turn — its durable append may land at any moment, so
-    // handing its text back to the user here would refill AND execute the
-    // same directive. An in-flight lease settles only by the persistence
-    // fact (ack when the ledger owns it, nack back to a queue otherwise).
-    const all = [
-      ...state.steering.map((message) => message.content.text),
-      ...state.followup.map((message) => message.content.text),
-    ];
-    state.steering = [];
-    state.followup = [];
-    this.emitQueueUpdate(sessionId, state);
-    return all.join('\n\n');
-  }
-
-  private ensureSteering(sessionId: string): SessionSteeringState {
-    const existing = this.steeringBySession.get(sessionId);
-    if (existing) return existing;
-    const created: SessionSteeringState = { steering: [], inFlight: [], followup: [] };
-    this.steeringBySession.set(sessionId, created);
-    return created;
-  }
-
-  private assertEmbeddedMessageQueue(operation: string): void {
-    if (this.deps.messageAuthority) {
-      throw new RuntimeMessageAuthorityInvariantError(
-        `Hosted Runtime cannot ${operation}; the Runtime Host owns message admission and queues`,
-      );
-    }
-  }
-
-  /**
-   * The session's steering state only while a steering-capable top-level run
-   * owns it (sink registered after begin() succeeded and not yet released).
-   * Child agent and compact runs never establish ownership, so their activity
-   * alone yields undefined — enqueue must fall back rather than strand text.
-   */
-  private liveSteeringState(sessionId: string): SessionSteeringState | undefined {
-    const state = this.steeringBySession.get(sessionId);
-    return state?.sink ? state : undefined;
-  }
-
-  private emitQueueUpdate(sessionId: string, state: SessionSteeringState): void {
-    state.sink?.({
-      type: 'queue_update',
-      id: this.deps.newId(),
-      turnId: state.activeTurnId ?? '',
-      ts: this.deps.now(),
-      steering: [
-        ...state.inFlight.map((message) => message.content.text),
-        ...state.steering.map((message) => message.content.text),
-      ],
-      followup: state.followup.map((message) => message.content.text),
-      steeringEntries: [
-        ...state.inFlight.map((message) => ({
-          entryId: message.id,
-          messageId: message.messageId,
-          content: message.content,
-          placement: 'current_turn' as const,
-          state: 'in_flight' as const,
-        })),
-        ...state.steering.map((message) => ({
-          entryId: message.id,
-          messageId: message.messageId,
-          content: message.content,
-          placement: 'current_turn' as const,
-          state: 'queued' as const,
-        })),
-      ],
-      followupEntries: state.followup.map((message) => ({
-        entryId: message.id,
-        messageId: message.messageId,
-        content: message.content,
-        placement: 'next_turn' as const,
-        state: 'queued' as const,
-      })),
-    });
-  }
-
-  private clearSteering(sessionId: string): void {
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return;
-    // Same commit-point rule as retractQueue: only QUEUED messages are
-    // clearable. An in-flight lease is already committed to the running
-    // turn's delivery and settles only by the persistence fact.
-    if (state.steering.length === 0 && state.followup.length === 0) return;
-    state.steering = [];
-    state.followup = [];
-    this.emitQueueUpdate(sessionId, state);
-  }
-
-  private releaseSteeringTurn(sessionId: string, turnId: string): void {
-    const state = this.steeringBySession.get(sessionId);
-    if (!state) return;
-    // A release folds only the leases THIS turn issued; an overlapping turn's
-    // in-flight lease stays for its issuer to settle (acked = delivered, so
-    // folding it into followup would redeliver an already-executed message).
-    const own = state.inFlight.filter((message) => message.issuingTurnId === turnId);
-    if (state.activeTurnId !== turnId) {
-      // Not (or no longer) the owner. The issuer's backend settles every
-      // lease before its turn ends, so `own` is normally empty; this is a
-      // backstop that keeps a never-settled lease from stranding invisibly.
-      if (own.length === 0) return;
-      state.inFlight = state.inFlight.filter((message) => message.issuingTurnId !== turnId);
-      state.followup = [...own, ...state.followup];
-      this.emitQueueUpdate(sessionId, state);
-      return;
-    }
-    // Stranded steering (arrived after the final step boundary, so no step is
-    // left to consume it) becomes the head of the followup queue instead of
-    // vanishing — the next turn opens with it first (grok-build safety). The
-    // migration is a queue change, so emit the final snapshot BEFORE the sink
-    // is cleared; otherwise observers stay on the stale pre-fold snapshot.
-    if (state.steering.length > 0 || own.length > 0) {
-      state.followup = [...own, ...state.steering, ...state.followup];
-      state.inFlight = state.inFlight.filter((message) => message.issuingTurnId !== turnId);
-      state.steering = [];
-      this.emitQueueUpdate(sessionId, state);
+  async materializeRootSourceMessages(input: {
+    sessionId: string;
+    turnId: string;
+    messages: readonly { messageId: string; content: MessageContent }[];
+  }): Promise<void> {
+    const existingIds = new Set(
+      (await this.deps.store.readMessages(input.sessionId)).map((message) => message.id),
+    );
+    for (const message of input.messages) {
+      if (existingIds.has(message.messageId)) continue;

Review Comment:
   [P1] 折叠到 successor 的 steering 没有重新绑定,之后每次 Host 启动都会失败。
   
   `materializeRootSourceMessages` 的去重是**整个 Session 范围**的:`readMessages(input.sessionId)` 取出所有已存在的 message id,命中就 `continue`。它只是跳过写入,**不会把这条 row 的 `turnId` 改绑到 successor**。
   
   触发路径:当前 root 接受了 steering,canonical UserMessage 已经写在 predecessor turn 下;backend 还没 pull 这条 steering,root 就进入终态;steering 被折叠进 successor;successor 以 `recordInitialUserMessage:false` 启动,而这里的全局去重让 source row 始终留在 predecessor 名下。
   
   后果:successor 当次能跑完,但下一次 Host 启动时,恢复流程发现 Run 已存在、而 source row 不在 successor 下,抛 `Admitted queued Turn <id> has incomplete source materialization`,readiness 失败——**整个 workspace 的 Host 起不来**。混合 steering + followup 的情况会在 source index 0 上以同样方式失败。
   
   为什么现有守卫拦不住:atomic admission 绑定的是 predecessor;全局去重是阻止写入而不是完成改绑;partial-prefix recovery 只在 Run 创建之前才允许介入。
   
   修复方向:保持单一 canonical identity 不变,但让 successor admission 能够原子地改绑/移动这条 row;或者让 materialization 与 recovery 显式接受并校验来自 predecessor 的 steering provenance。



-- 
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-host): unify durable message lifecycle [maka]

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

   Note on freshness: my earlier review is bound to `07a3adb9c`, which this branch no longer contains. Please do not read it as a statement about the current code.
   
   The branch was rewritten rather than extended — between `07a3adb9c` and the current `eecd4d93d` there is a new commit chain, and the two commits I examined now correspond to different objects. The change is also considerably larger than what I looked at: 82 files and `+3989/-3158`, against 37 files previously.
   
   I am not restating a verdict here. A fresh review is underway at `eecd4d93d`, and I will publish conclusions bound to whatever head is current when they are ready.
   
   One environment note that affects how CI is read right now, unrelated to this PR: `main` is failing its `Check ASF source headers` step because five `packages/runtime/plugin-*` files added by #3250 are missing the license header. Any ASF header failure seen while validating against `main` comes from there, not from this branch.
   
   <details><summary>简体中文</summary>
   
   关于时效性的说明:我先前那条 review 绑定在 `07a3adb9c` 上,而这个分支已经不包含该提交。请不要把它当作对当前代码的判断。
   
   这个分支是被重写而不是被追加的——`07a3adb9c` 到当前 `eecd4d93d` 之间是一条新的提交链,我当时看的那两个提交现在对应的是不同的对象。改动规模也比我看过的大得多:82 个文件、`+3989/-3158`,而此前是 37 个文件。
   
   我在这里不重述任何结论。针对 `eecd4d93d` 的新一轮复审正在进行,结论会绑定到届时的当前 head 再发布。
   
   另有一条与本 PR 无关、但会影响当下 CI 判读的环境事实:`main` 的 `Check ASF source headers` 这一步正在失败,原因是 #3250 新增的五个 `packages/runtime/plugin-*` 文件缺少版权头。因此在对 `main` 做验证时看到的 ASF 头失败来自那里,不是来自这个分支。
   
   </details>
   


-- 
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