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

(maka) 03/03: fix(runtime-host): fence stale update reconciliation

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

M4n5ter pushed a commit to branch feat/runtime-host-update-reconciliation
in repository https://gitbox.apache.org/repos/asf/maka.git

commit 49f8dc6b7f24eed75389acb56d5cddcf1256646b
Author: Wang <m4...@gmail.com>
AuthorDate: Tue Aug 25 09:06:00 2026 +0800

    fix(runtime-host): fence stale update reconciliation
    
    Revalidate the selected managed-update policy inside the deployment lock before reading or mutating service state. This lets a newer manual or fixed policy revoke an in-flight unattended reconciliation without introducing another lock or scheduler state machine.
    
    Generated-by: Codex
---
 .../__tests__/runtime-host-selected-update.test.ts | 36 +++++++++++++++
 .../runtime-host-update-reconciliation.test.ts     | 48 +++++++++++++++++++-
 packages/cli/src/runtime-host-update-command.ts    | 29 +++++++++++-
 .../cli/src/runtime-host-update-reconciliation.ts  | 53 ++++++++++++++++++++--
 4 files changed, 158 insertions(+), 8 deletions(-)

diff --git a/packages/cli/src/__tests__/runtime-host-selected-update.test.ts b/packages/cli/src/__tests__/runtime-host-selected-update.test.ts
index 0c9002a9d..b758b83a5 100644
--- a/packages/cli/src/__tests__/runtime-host-selected-update.test.ts
+++ b/packages/cli/src/__tests__/runtime-host-selected-update.test.ts
@@ -21,6 +21,7 @@ import assert from 'node:assert/strict';
 import { describe, it } from 'node:test';
 import { decodeRuntimeHostServiceManagementFrame } from '@maka/runtime-host/operator';
 import {
+  runManagedRuntimeHostUpdateCli,
   runManagedRuntimeHostSelectedUpdateCli,
   type RuntimeHostSelectedUpdateCliOptions,
   type RuntimeHostUpdateCliOptions,
@@ -45,6 +46,41 @@ const OPTIONS: RuntimeHostSelectedUpdateCliOptions = {
 };
 
 describe('managed Runtime Host selected update', () => {
+  it('revalidates selection inside the deployment lock before reading service state', async () => {
+    let lockHeld = false;
+    let output = '';
+    assert.equal(
+      await runManagedRuntimeHostUpdateCli(
+        {
+          ...OPTIONS,
+          sourcePackageRoot: '/verified/package',
+          version: '2.0.0',
+        },
+        {
+          withDeploymentLock: async (_root, operation) => {
+            lockHeld = true;
+            try {
+              return await operation();
+            } finally {
+              lockHeld = false;
+            }
+          },
+          revalidateSelection: async () => {
+            assert.equal(lockHeld, true);
+            return { code: 'update_policy_changed', message: 'The policy changed' };
+          },
+          manage: async () => assert.fail('service state must not be read'),
+          writeOutput: (value) => {
+            output += value;
+          },
+        },
+      ),
+      1,
+    );
+    const frame = decodeRuntimeHostServiceManagementFrame(output.trim());
+    assert.equal(frame?.kind === 'error' ? frame.error.code : undefined, 'update_policy_changed');
+  });
+
   it('parses an optional target without changing the exact-package command', () => {
     assert.deepEqual(
       parseRuntimeHostCommand([
diff --git a/packages/cli/src/__tests__/runtime-host-update-reconciliation.test.ts b/packages/cli/src/__tests__/runtime-host-update-reconciliation.test.ts
index f90fa0574..b51179170 100644
--- a/packages/cli/src/__tests__/runtime-host-update-reconciliation.test.ts
+++ b/packages/cli/src/__tests__/runtime-host-update-reconciliation.test.ts
@@ -207,7 +207,8 @@ describe('managed Runtime Host update reconciliation', () => {
             service: SERVICE,
           };
         },
-        applySelection: async (_options, _selection, _overrides, emit) => {
+        applySelection: async (_options, _selection, overrides, emit) => {
+          assert.equal(await overrides?.revalidateSelection?.(), undefined);
           applied = true;
           emit?.({
             schemaVersion: 1,
@@ -247,6 +248,51 @@ describe('managed Runtime Host update reconciliation', () => {
     );
   });
 
+  it('revokes a stale reconcile when automatic policy changes to manual', async (t) => {
+    const clientDataRoot = await mkdtemp(join(tmpdir(), 'maka-update-policy-race-'));
+    t.after(() => rm(clientDataRoot, { recursive: true, force: true }));
+    await writeRuntimeHostManagedUpdatePolicy(clientDataRoot, {
+      schemaVersion: 1,
+      policy: { kind: 'channel', channel: 'latest' },
+      target: TARGET,
+    });
+    let output = '';
+    assert.equal(
+      await runManagedRuntimeHostUpdateReconcileCli(
+        { json: true, framed: false, clientDataRoot, defaultRootPath: '/workspace' },
+        {
+          resolveSelection: async (options) => {
+            await writeRuntimeHostManagedUpdatePolicy(clientDataRoot, null);
+            return {
+              selector: options.selector,
+              candidate: { version: '2.0.0', integrity: INTEGRITY, compatibility: 1 },
+              outcome: { kind: 'unattended_update', compatibility: 1 },
+              currentCliPath: '/managed/current/cli.js',
+              service: SERVICE,
+            };
+          },
+          applySelection: async (_options, _selection, overrides, emit) => {
+            const rejection = await overrides?.revalidateSelection?.();
+            assert.equal(rejection?.code, 'update_policy_changed');
+            emit?.({
+              schemaVersion: 1,
+              kind: 'error',
+              action: 'update',
+              error: rejection ?? assert.fail('policy revalidation is required'),
+            });
+            return 1;
+          },
+          writeOutput: (value) => {
+            output += value;
+          },
+        },
+      ),
+      1,
+    );
+    assert.equal(JSON.parse(output).error.code, 'update_policy_changed');
+    assert.equal(await readRuntimeHostManagedUpdatePolicy(clientDataRoot), null);
+  });
+
   it('fails closed on corrupt policy and returns manual-action candidates without mutation', async (t) => {
     const clientDataRoot = await mkdtemp(join(tmpdir(), 'maka-update-reconcile-'));
     t.after(() => rm(clientDataRoot, { recursive: true, force: true }));
diff --git a/packages/cli/src/runtime-host-update-command.ts b/packages/cli/src/runtime-host-update-command.ts
index fab650d98..ac8354a5a 100644
--- a/packages/cli/src/runtime-host-update-command.ts
+++ b/packages/cli/src/runtime-host-update-command.ts
@@ -94,6 +94,7 @@ export interface RuntimeHostSelectedUpdateCliOptions
 }
 
 interface RuntimeHostUpdateCliDeps {
+  readonly revalidateSelection: () => Promise<RuntimeHostUpdateSelectionRejection | undefined>;
   readonly manage: typeof manageRuntimeHostService;
   readonly replace: typeof replaceRuntimeHostManagedService;
   readonly openDeployment: typeof openRuntimeHostManagedPackageDeployment;
@@ -113,6 +114,7 @@ interface RuntimeHostUpdateCliDeps {
 }
 
 interface RuntimeHostResolvedUpdateCliDeps {
+  readonly revalidateSelection: () => Promise<RuntimeHostUpdateSelectionRejection | undefined>;
   readonly withPackage: typeof withRuntimeHostRegistryUpdatePackage;
   readonly update: typeof runManagedRuntimeHostUpdateCli;
   readonly writeOutput: (value: string) => unknown;
@@ -135,12 +137,28 @@ interface RuntimeHostOperatorInvocation {
   readonly capabilityRequest?: RuntimeHostOperatorCapability;
 }
 
+interface RuntimeHostUpdateSelectionRejection {
+  readonly code: string;
+  readonly message: string;
+}
+
+class RuntimeHostUpdateSelectionError extends Error {
+  constructor(
+    readonly code: string,
+    message: string,
+  ) {
+    super(message);
+    this.name = 'RuntimeHostUpdateSelectionError';
+  }
+}
+
 export async function runManagedRuntimeHostUpdateCli(
   options: RuntimeHostUpdateCliOptions,
   overrides: Partial<RuntimeHostUpdateCliDeps> = {},
   frameSink?: RuntimeHostUpdateFrameSink,
 ): Promise<number> {
   const deps: RuntimeHostUpdateCliDeps = {
+    revalidateSelection: async () => undefined,
     manage: manageRuntimeHostService,
     replace: replaceRuntimeHostManagedService,
     openDeployment: openRuntimeHostManagedPackageDeployment,
@@ -164,6 +182,10 @@ export async function runManagedRuntimeHostUpdateCli(
   try {
     return await deps.withDeploymentLock(options.clientDataRoot, async () => {
       try {
+        const rejection = await deps.revalidateSelection();
+        if (rejection) {
+          throw new RuntimeHostUpdateSelectionError(rejection.code, rejection.message);
+        }
         const serviceId = resolveRuntimeHostManagedServiceId(options.clientDataRoot);
         if (serviceId !== options.expectedTarget.serviceId) {
           throw new RuntimeHostServiceManagerError(
@@ -461,7 +483,8 @@ export async function runManagedRuntimeHostUpdateCli(
       : error;
     const code =
       reportedError instanceof RuntimeHostServiceManagerError ||
-      reportedError instanceof RuntimeHostManagedDeploymentError
+      reportedError instanceof RuntimeHostManagedDeploymentError ||
+      reportedError instanceof RuntimeHostUpdateSelectionError
         ? reportedError.code
         : 'internal_service_error';
     const message = reportedError instanceof Error ? reportedError.message : String(reportedError);
@@ -487,6 +510,7 @@ export async function runManagedRuntimeHostSelectedUpdateCli(
   frameSink?: RuntimeHostUpdateFrameSink,
 ): Promise<number> {
   const deps: RuntimeHostSelectedUpdateCliDeps = {
+    revalidateSelection: async () => undefined,
     resolveSelection: resolveManagedRuntimeHostUpdateSelection,
     withPackage: withRuntimeHostRegistryUpdatePackage,
     update: runManagedRuntimeHostUpdateCli,
@@ -537,6 +561,7 @@ export async function runManagedRuntimeHostResolvedUpdateCli(
   frameSink?: RuntimeHostUpdateFrameSink,
 ): Promise<number> {
   const deps: RuntimeHostResolvedUpdateCliDeps = {
+    revalidateSelection: async () => undefined,
     withPackage: withRuntimeHostRegistryUpdatePackage,
     update: runManagedRuntimeHostUpdateCli,
     writeOutput: (value) => process.stdout.write(value),
@@ -578,7 +603,7 @@ export async function runManagedRuntimeHostResolvedUpdateCli(
             },
           },
         },
-        {},
+        { revalidateSelection: deps.revalidateSelection },
         emit,
       );
     };
diff --git a/packages/cli/src/runtime-host-update-reconciliation.ts b/packages/cli/src/runtime-host-update-reconciliation.ts
index 0c7fa7dd2..eaa063288 100644
--- a/packages/cli/src/runtime-host-update-reconciliation.ts
+++ b/packages/cli/src/runtime-host-update-reconciliation.ts
@@ -205,11 +205,33 @@ export async function runManagedRuntimeHostUpdateReconcileCli(
       selector: selection.selector,
       expectedTarget: record.target,
     };
-    const exitCode = await deps.applySelection(selectedOptions, selection, {}, (frame) => {
-      const mapped = reconcileFrame(frame, updatePolicy);
-      writeFrame(mapped, options, deps);
-      if (mapped.kind !== 'progress') terminal = mapped;
-    });
+    const exitCode = await deps.applySelection(
+      selectedOptions,
+      selection,
+      {
+        revalidateSelection: async () => {
+          let current: RuntimeHostManagedUpdatePolicyRecord | null;
+          try {
+            current = await deps.readPolicy(options.clientDataRoot);
+          } catch (error) {
+            return boundedError(error, 'Unable to revalidate the managed update policy');
+          }
+          if (!sameUpdatePolicyRecord(current, record)) {
+            return {
+              code: 'update_policy_changed',
+              message:
+                'The managed Runtime Host update policy changed while its candidate was prepared; reconciliation made no changes',
+            };
+          }
+          return undefined;
+        },
+      },
+      (frame) => {
+        const mapped = reconcileFrame(frame, updatePolicy);
+        writeFrame(mapped, options, deps);
+        if (mapped.kind !== 'progress') terminal = mapped;
+      },
+    );
     if (!terminal) {
       throw new Error('The managed Runtime Host update did not return a terminal result');
     }
@@ -262,6 +284,27 @@ function policySelector(
     : { kind: 'channel', channel: policy.channel };
 }
 
+function sameUpdatePolicyRecord(
+  left: RuntimeHostManagedUpdatePolicyRecord | null,
+  right: RuntimeHostManagedUpdatePolicyRecord | null,
+): boolean {
+  if (!left || !right) return left === right;
+  if (
+    left.schemaVersion !== right.schemaVersion ||
+    left.target.serviceId !== right.target.serviceId ||
+    left.target.rootPath !== right.target.rootPath ||
+    left.target.rootId !== right.target.rootId ||
+    left.policy.kind !== right.policy.kind
+  ) {
+    return false;
+  }
+  return left.policy.kind === 'fixed' && right.policy.kind === 'fixed'
+    ? left.policy.version === right.policy.version
+    : left.policy.kind === 'channel' &&
+        right.policy.kind === 'channel' &&
+        left.policy.channel === right.policy.channel;
+}
+
 function reconcileFrame(
   frame: RuntimeHostUpdateFrame,
   updatePolicy: ReturnType<typeof policyResult>,


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