Skip to content

fix(nodes): wait for pairing publication before duplex I/O - #161209

Closed
gisk0 wants to merge 5 commits into
openclaw:mainfrom
gisk0:fix/preserve-node-pairing-during-metadata-updates
Closed

gisk0 wants to merge 5 commits into
openclaw:mainfrom
gisk0:fix/preserve-node-pairing-during-metadata-updates

Conversation

@gisk0

@gisk0 gisk0 commented Sep 29, 2026 •

Copy link
Copy Markdown

tl;dr

Routine device updates can interrupt active remote coding streams. Queue duplex traffic behind pairing publication, refresh authority, then perform the final synchronous effect before releasing the local owner.

Related: #148693. Complements #148770, which retires genuinely stale connections.

What Problem This Solves

Presence and host-statistics writes temporarily fence the node binding. Input or progress overlapping that fence can fail a valid coding session. An earlier PR revision bypassed that fence for metadata, which allowed stale authority after an external SQLite deletion. This revision retains the original strict fence and waits for fresh authority instead.

User Impact

Active coding streams wait for routine updates within existing invocation deadlines, then continue if their exact pairing and invocation remain valid. Revocation, rotation, deletion, cancellation, replacement connections, and withdrawn caller authority prevent delivery. No configuration, protocol, or database migration is needed.

Why This Change Was Made

Duplex input and incoming progress/results wait for the pairing owner, read current authority, recheck the exact pending invocation/connection/generation and caller policy, then perform the synchronous send or settlement while holding that owner. Existing framing preserves message order. The publication owner itself is unchanged from the base.

The local lock serializes local writers. Foreign commits preceding the fresh worker read are observed; this does not exclude foreign commits after that read. Per-fragment reads add work; aggregate throughput is unbenchmarked. Exact-head security-owner acceptance of this boundary remains required.

Evidence

Head d69797077ef8500efec17b8f4f23e5a02a5bf26a; local validation base 52618fc09b.

  • Applied the repository test-audit workflow: removed the obsolete seven-operation cross-product and duplicated fence/read compositions; shared real fixture setup; retained failure/recovery. Publication cases reduced from 33 to 19; total net growth dropped from 682 to 473 lines (production 133→127, tests 549→346). Independent inbound cases prevent input rejection from masking missing progress/result guards. The plugin test now revokes caller authority while a send waits.
  • Validation: 174/174 focused tests across five files passed (88.1s wrapper), followed by 19/19 publication cases on the final formatted source (34.0s wrapper). Targeted formatting and typed lint passed; core types (110.5s) and selected gateway-server/infra test-type graphs (545.0s including setup) passed. Tests ran serially with one worker in an isolated checkout; cold worker preparation cost 459.0s for the final run.
  • Three disposable fault controls each failed for the intended reason: replacing only the asynchronous input guard with the real synchronous send caused failed to send node invoke input during the metadata fence; replacing only the progress or result guard with its real synchronous method independently produced expected true to be false after an external pairing deletion. These are guard-bypass controls, not pristine-base executions. No production source was altered for the controls; the scratch file was excluded from the published patch.
  • Fresh repository Codex AutoReview reports no P0–P2 findings. The final formatter change was whitespace-only relative to the reviewed candidate.
  • Earlier six-case real Gateway/WebSocket proof ran at f9027947; the guarded transport implementation is unchanged in this simplification. The new isolated inbound tests establish each guard independently.
  • Prior-head CI attribution records failures outside the pairing path and unresolved runtime causes. New-head CI remains a separate gate. An earlier local combined portal batch timed out; the exact isolated test later passed under its unchanged timeout, without establishing the original timing cause.

Paired vendor security scans were waived by the requester; independent review and focused tests were used. Full local build/suite, aggregate throughput benchmark, and production deployment of this upstream revision were not run.

@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Maintainer security review required

This external contributor PR changes sensitive security components. A maintainer must review these changes before merging.

Current SHA: d69797077ef8500efec17b8f4f23e5a02a5bf26a

These sensitive security changes were made:

  • src/infra/device-pairing-node-state.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

After reviewing the changes, post a new PR comment containing only approval commands, each on its own line:

/allow-security-sensitive-change

A later push requires a fresh approval comment.

@gisk0

gisk0 commented Sep 29, 2026

Copy link
Copy Markdown
Author

Requesting maintainer review of the pairing changes at f6055cebe7e2da75bd4fd664203aefa22734317b for the security-sensitive approval gate. The PR description includes the failing-before/passing-after evidence and the preserved revocation/publication boundaries.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 29, 2026
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 29, 2026, 1:46 PM ET / 17:46 UTC (Revision 5).

ClawSweeper review

What this changes

The branch makes remote node input, progress, and results wait for pairing publication and recheck the connected node's authority before delivery or settlement.

Merge readiness

⛔ Blocked before merge - 4 items remain

The current head appears to repair the pairing-publication interruption and addresses the earlier cached-authority finding. Real Gateway and WebSocket evidence supports the changed path. The disclosed cross-process authority boundary still needs exact-head security-owner acceptance before merge.

Priority: P1
Reviewed head: d69797077ef8500efec17b8f4f23e5a02a5bf26a
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Real transport proof and focused regressions support the repair, while the security-sensitive foreign-commit boundary awaits owner acceptance.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The earlier-head fixture used a real Gateway kernel and authenticated node WebSocket to exercise metadata overlap plus local and observed external authority changes, recording one valid input after publication and no queued input for revoked or rotated pairings. The production guards are unchanged in this test-focused head. The proof does not claim exclusion of a foreign commit after the final fresh read. No stored-data contract changes.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The earlier-head fixture used a real Gateway kernel and authenticated node WebSocket to exercise metadata overlap plus local and observed external authority changes, recording one valid input after publication and no queued input for revoked or rotated pairings. The production guards are unchanged in this test-focused head. The proof does not claim exclusion of a foreign commit after the final fresh read. No stored-data contract changes.
Evidence reviewed 7 items Final-effect guards: The introduced guard refreshes the pairing lease and rechecks the pending invocation before the synchronous input send; inbound progress and results use the same guarded path.
Pairing owner boundary: The new helper waits for the local pairing lock, performs a worker-backed lookup, then runs the synchronous effect against the published binding before releasing that local lock.
Real transport proof: The contributor's earlier-head six-case fixture reports a real Gateway and authenticated node WebSocket: valid metadata overlap delivers one input, while local revocation or rotation and observed external deletion, revocation, or rotation produce no queued input. The production guards are unchanged between that proven head and this test-focused head.
Findings None None.
Security Needs attention Settle the foreign-commit authority boundary: The fresh read and local lock reject previously observed revocation, but a foreign SQLite commit after that read can precede the socket effect; the security owner must accept or strengthen this contract.

How this fits together

The Gateway pairs remote nodes and sends invocation traffic over their WebSocket connections. Pairing records feed the node registry, which decides whether input can be sent and whether progress or results can reach the caller.

flowchart LR
  A[Pairing records] --> B[Pairing publication]
  C[Node WebSocket] --> D[Node registry]
  B --> D
  D --> E{Current pairing and invocation?}
  E -->|Yes| F[Send or accept stream traffic]
  E -->|No| G[Reject delivery]
Loading

Decision needed

Question Recommendation
Is a fresh worker read under the local pairing lock sufficient authority for node duplex I/O when a foreign SQLite commit can occur immediately afterward? Accept the observation contract: Approve this exact head with the documented foreign-commit window and retain the current worker-read contract.

Why: The patch and real transport proof cover revocation observed before the read, while the PR explicitly leaves the post-read foreign-commit window as a trust-model choice.

Before merge

  • Resolve security concern: Settle the foreign-commit authority boundary - The fresh read and local lock reject previously observed revocation, but a foreign SQLite commit after that read can precede the socket effect; the security owner must accept or strengthen this contract.
  • Resolve merge risk (P1) - The local lock protects local pairing writers, but a separate SQLite writer can change pairing after the fresh worker read and before the socket effect. The security owner must accept this exact-head observation boundary or require a stronger final-I/O contract.
  • Complete next step (P2) - Obtain exact-head security-owner acceptance of the documented foreign-commit observation boundary, or revise the final-I/O contract as the owner directs.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [medium] Settle the foreign-commit authority boundary — src/infra/device-pairing-node-state.ts:53
Agent review details

Security

Needs attention: The diff adds no observed credential or supply-chain change, but exact-head approval is required for its disclosed pairing-authority observation boundary.

PR surface

Source +127, Tests +346. Total +473 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 7 147 20 +127
Tests 5 371 25 +346
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 518 45 +473

Review metrics

Metric Value Why it matters
Test cost 19 publication cases; 34.0s local wrapper time The contributor measured the focused suite after simplifying its coverage; current-head CI cost was not yet available in the supplied context.

Merge-risk options

Maintainer options:

  1. Accept the documented boundary (recommended)
    An authorized security owner can approve this exact head with the known post-read foreign-commit window.
  2. Pause for a stronger guard
    Keep this branch open while the owner defines and proves stronger cross-process protection at final I/O.

Technical review

Best possible solution:

Keep the guarded duplex path and have the security owner settle the documented foreign-commit observation boundary before the native merge gate proceeds.

Do we have a high-confidence way to reproduce the issue?

Yes. The pairing-publication overlap has a clear source path and an isolated real Gateway/WebSocket fixture; the disposable fault controls failed at the intended guards, though a pristine-base runtime failure was not run.

Is this the best way to solve the issue?

Yes, subject to security-owner acceptance. The change uses the existing pairing publication owner and rechecks authority at the final effect; stronger cross-process exclusion would require an explicit contract decision.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 7098bf6cddd8.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Routine pairing updates can interrupt an active remote node coding stream, while the repair remains blocked on an authority decision.
  • merge-risk: 🚨 security-boundary: The introduced final-effect path relies on a local lock and fresh worker read that cannot exclude a later foreign pairing commit.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The earlier-head fixture used a real Gateway kernel and authenticated node WebSocket to exercise metadata overlap plus local and observed external authority changes, recording one valid input after publication and no queued input for revoked or rotated pairings. The production guards are unchanged in this test-focused head. The proof does not claim exclusion of a foreign commit after the final fresh read. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The earlier-head fixture used a real Gateway kernel and authenticated node WebSocket to exercise metadata overlap plus local and observed external authority changes, recording one valid input after publication and no queued input for revoked or rotated pairings. The production guards are unchanged in this test-focused head. The proof does not claim exclusion of a foreign commit after the final fresh read. No stored-data contract changes.

Evidence

Security concerns:

  • [medium] Settle the foreign-commit authority boundary — src/infra/device-pairing-node-state.ts:53
    The fresh read and local lock reject previously observed revocation, but a foreign SQLite commit after that read can precede the socket effect; the security owner must accept or strengthen this contract.
    Confidence: 0.92

What I checked:

  • Final-effect guards: The introduced guard refreshes the pairing lease and rechecks the pending invocation before the synchronous input send; inbound progress and results use the same guarded path. (src/gateway/node-registry.ts:1181, d69797077ef8)
  • Pairing owner boundary: The new helper waits for the local pairing lock, performs a worker-backed lookup, then runs the synchronous effect against the published binding before releasing that local lock. (src/infra/device-pairing-node-state.ts:48, d69797077ef8)
  • Real transport proof: The contributor's earlier-head six-case fixture reports a real Gateway and authenticated node WebSocket: valid metadata overlap delivers one input, while local revocation or rotation and observed external deletion, revocation, or rotation produce no queued input. The production guards are unchanged between that proven head and this test-focused head. (f9027947f5b7)
  • Existing worker observation contract: The storage contract describes foreign-commit detection by read workers and binding publication by commit receipts; it does not establish atomic exclusion of a foreign commit after a fresh read. Public docs: docs/reference/database-schemas/storage-changes.md. (docs/reference/database-schemas/storage-changes.md:1889, d69797077ef8)
  • Current-main necessity: The fetched main revision lacks the new guarded input, progress, and pairing-lease methods, so the central repair is not already implemented there. The listed latest release predates this PR. (src/gateway/node-registry.ts, 7098bf6cddd8)
  • Area history: Current-main history identifies prior node registry, pairing-worker, and shared runtime contributors; the PR author is not included solely for proposing this branch. (src/gateway/node-registry.ts, 7098bf6cddd8)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Gio Della-Libera: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain exact-head security-owner approval for the disclosed foreign-commit observation boundary.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-29T13:44:22.101Z sha f6055ce :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-29T14:12:35.132Z sha f6055ce :: blocked before merge. :: [P1] Reject externally revoked pairing before invocation I/O
  • reviewed 2026-09-29T14:34:35.307Z sha f6055ce :: blocked before merge. :: [P1] Reject externally revoked pairing before invocation I/O
  • reviewed 2026-09-29T15:57:16.865Z sha f902794 :: blocked before merge. :: none

@gisk0

gisk0 commented Sep 29, 2026 •

Copy link
Copy Markdown
Author

Won't fix: the four inherited fixture/routing mismatches below are outside this pairing patch. The other two runtime failure groups remain unresolved and still block readiness; no waiver or unrelated-cause claim is made.

CI triage for f6055cebe7e2da75bd4fd664203aefa22734317b (run 36576072704): six shards failed. All failures below were inspected in the existing job logs; no workflow or job was rerun.

Four shards have concrete source-level evidence of inherited fixture/routing drift from upstream #161124, already present in pinned base 52618fc09b8affbc8b1d7a478c1e573d72132757. These are source comparisons, not executed standalone base reproductions:

  • 32: 4 failures in github-shared-publication-events.test.ts. The fixture now creates repository workspaces through the host SQLite broker, but the file remains in the thread-based Gateway core project. openSharedStateSqliteWorkerStore explicitly rejects !isMainThread. Its sibling read test is registered with the forked database-worker project; this events file is missing there.
  • 24-3: 8 failures in server.sessions.list-changed.test.ts. Upstream broadcasts now include prepareSessionProjection; the shared assertion still expects the prior exact options object.
  • 43: 3 failures in server-restart-sentinel.test.ts. Same upstream broadcast change: production supplies a fourth projection-options argument while the assertion expects three arguments.
  • 8: 1 failure in github-publication-personal-pending.test.ts. Upstream personalPending now rereads the receipt after preparing its owner. The fixture deliberately completes it as failed, then still expects the held older needs_confirmation snapshot. The fresh failed result matches that new code path.

Two failures remain unresolved; their attribution is not established:

  • 38-1: 2 chat.reset-visible-yield.test.ts cases time out awaiting the requester yield event. Both are preceded by Queued subagent registry persistence failed: This turn has ended; ask again in a new turn. A bounded local reproduction also emitted this closed-turn error, but the underlying lifetime/order cause remains unproven (details below).
  • 15-1: 1 server.private-completion.test.ts case fails during chat.abort: descendant cancellation reports unavailable session delivery generation. The origin of that missing generation is unproven.

No failing owner/test/config file above changes in this PR. This fact alone does not establish that the two unresolved runtime failures are unrelated.

Exact-base source anchors:

Additional bounded path inspection:

  • The failing private-completion cancellation uses mocked local agent commands and forced synthetic in-process operator clients for both parent and child (server.private-completion.test.ts:116-124,603-629). Its abort goes through the internal recovery dispatcher (server-instance-runtime.ts:161-170), which constructs an operator client without a device/pairing identity (server-plugin-runtime-client.ts:66-79). The test never opens the harness WebSocket client or creates a paired node. This failing cancellation path does not exercise the changed pairing mutation/publication branches; the missing delivery-generation cause itself remains unexplained.
  • The yield fixture likewise uses a local mock HTTP model and allows only spawn/yield plus optional GitHub tools; it creates no node or remote execution placement (chat.reset-visible-yield.test.ts:536-566). However, its normal operator WebSocket helper creates a signed device identity (test-helpers.e2e.ts:86-102). Operator connection/reconnection can perform pairing metadata updates, so an absolute claim that this test cannot execute any changed mutation branch would be unjustified. Attribution remains unresolved.

Bounded local yield follow-up (no GitHub job/workflow rerun):

  • Exact target: node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-methods-isolated.config.ts src/gateway/server-methods/chat.reset-visible-yield.test.ts --maxWorkers=1. That file declares only the two failed reset/complete cases. Same CI project and forks pool, original test timeouts unchanged.
  • Final candidate: 2/2 failed, exit 1, 167.239s wall / 158.94s Vitest. The reset case emitted the same Queued subagent registry persistence failed: This turn has ended; ask again in a new turn. error seen in CI, then reached the full 90s test timeout. The complete case subsequently failed because Gateway plugin metadata was still shutting down. Teardown also reported a SQLite file identity change. Thus the closed-turn error was reproduced, but the exact pair of CI yield-event timeouts and their causal attribution remain unresolved.
  • Pinned-base comparison: tests did not run. The unchanged repository runner's 120s no-output watchdog terminated cold worker compilation, exit 143 after 151.781s. This gives no behavioral base verdict; no retry or timeout relaxation followed.
  • Environment limits: local Node 26.8.2 on NixOS versus CI Node 24.21.0; one selected file/worker under MemoryHigh 6 GiB, MemoryMax 8 GiB and CPUQuota 200%, rather than the whole CI shard. This is not an environment-identical reproduction or proof of an unrelated/flaky failure.
  • The comparison touched only the three patch files in the isolated validation checkout. All were restored and their final candidate SHA-256 hashes verified; production and the published worktree were untouched. Both test units were observed settled (failed, not running). The base unit's final successful status check showed MainPID=0, ControlPID=0 and no tasks. A later redundant combined read failed in node discovery before remote execution; no transport repair was attempted.

@gisk0

gisk0 commented Sep 29, 2026

Copy link
Copy Markdown
Author

Response to ClawSweeper review: the real-transport evidence is below. The request for an unconditional external-revocation guarantee is not satisfied; the negative control demonstrates the observation window. That authority-contract decision and exact-head maintainer approval remain open.

Additional real Gateway/WebSocket evidence for f6055cebe7e2da75bd4fd664203aefa22734317b:

I ran the attached scratch fixture against the final patch's source contents in an isolated checkout. All three changed source files matched the published head by SHA-256. This fixture was not added to the PR. It starts an actual Gateway kernel/listener and authenticated node WebSocket client using the repository's existing test hooks and temporary synthetic state. It does not use a production Gateway, real coding workload, or production pairing database.

PASS real WebSocket pairing publication boundary: metadata             34731 ms
PASS real WebSocket pairing publication boundary: revoke                5723 ms
PASS real WebSocket pairing publication boundary: rotate                5434 ms
PASS real WebSocket pairing publication boundary: observed-external     5649 ms
PASS real WebSocket pairing publication boundary: unobserved-external   6102 ms
Test Files  1 passed (1)
Tests       5 passed (5)
Duration    354.54s
Exit        0

The first run compiled the cold Gateway worker bundle in 247.236 seconds; total runner wall time was 361 seconds. The service exited and fixture cleanup retired the Gateway and SQLite owners. The last observed peak memory was approximately 5.08 GB.

For reproduction, save the attached fixture as src/gateway/server.pairing-publication-live-proof.test.ts in an isolated checkout of this head with its frozen dependencies, then run:

node scripts/run-vitest.mjs run \
  --config test/vitest/vitest.gateway-server.config.ts \
  src/gateway/server.pairing-publication-live-proof.test.ts \
  --maxWorkers=1

Environment: Linux, Node 26.8.2, pnpm 12.5.1, Vitest 5.0.1. The Gateway project uses the fork pool; this file ran in gateway-server (gateway-server-parallel) with one worker. The transient test service had MemoryHigh=6G, MemoryMax=8G, CPUQuota=200%, RuntimeMaxSec=1800, and KillMode=control-group.

Fixture SHA-256: b182a53b72d61b88d225916b86ee01e6b742d778e30a840ab79a6caf259f9dcf.

The metadata case wraps and delegates the real binding resolver, then pauses its return after its actual worker lookup. It queues the real metadata mutation behind a second deterministic barrier. While that write remains queued, sendInvokeInput delivers an actual node.invoke.input event to the node WebSocket, and releasing the first barrier lets real inbound node.invoke.progress pass the final pairing gate and reach the invocation's progress callback. The write is released afterward; the invocation completes successfully. The initial invocation is created through the real kernel's NodeRegistry, rather than an operator RPC.

The revoke and rotate cases queue their actual mutation adapters and verify that input is denied before the server socket's send method receives any node.invoke.input frame. After the mutation commits, inbound progress is rejected. The observed-external case deletes the pairing through a separate SQLite connection, refreshes it through the real worker lookup, then queues metadata; the subsequent metadata interval does not restore that revoked authority, and both boundaries deny use.

Explicit freshness limitation: the negative-control case also passes by demonstrating the weaker behavior: an external SQLite deletion made while metadata is queued, before a worker read or receipt observes it, still permits an input frame using the cached committed binding. After the metadata receipt and fresh lookup observe the deletion, subsequent input and progress are denied. This patch therefore does not establish instantaneous cross-process revocation at every synchronous effect. It preserves local authority-mutation fences and already-observed revocation. Whether external commits must invalidate synchronous leases immediately is a separate authority-contract decision; these results should not be read as proving that stronger guarantee.

The existing worker/publication contract describes detection through worker reads and commit receipts. These results support retaining that contract; they do not substitute for a maintainer decision about this relaxation.

Reproducible scratch integration fixture
// Scratch integration evidence for PR #161209; not part of the published patch.
import { DatabaseSync } from "node:sqlite";
import { expect, test, vi } from "vitest";
import { runQaGatewayFixture } from "../../test/helpers/qa-gateway-cleanup.js";
import { writeConfigFile } from "../config/config.js";
import { approveNodePairing, requestNodePairing } from "../infra/device-pairing-node.js";
import * as nodeState from "../infra/device-pairing-node-state.js";
import { revokeDeviceToken, rotateDeviceToken } from "../infra/device-pairing-tokens.js";
import { getPairedDevice, updatePairedDeviceMetadata } from "../infra/device-pairing.js";
import { withTimeout } from "../infra/fs-safe.js";
import { createDeferredCore } from "../shared/deferred.js";
import * as stateWorker from "../state/openclaw-state-worker-store.js";
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
import { withEnvAsync } from "../test-utils/env.js";
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
import { pairDeviceIdentity } from "./device-authz.test-helpers.js";
import { createGatewayKernel } from "./server-kernel.js";
import { connectGatewayClient } from "./test-helpers.e2e.js";
import { installGatewayTestHooks, startServer } from "./test-helpers.js";

installGatewayTestHooks({ scope: "suite" });

test.each(["metadata", "revoke", "rotate", "observed-external", "unobserved-external"] as const)(
  "real WebSocket pairing publication boundary: %s",
  async (mode) => {
    if (!process.env.OPENCLAW_STATE_DIR) throw new Error("isolated state required");
    const paired = await pairDeviceIdentity({
      name: `pairing-proof-${mode}`,
      role: "node",
      scopes: [],
      clientId: GATEWAY_CLIENT_NAMES.NODE_HOST,
      clientMode: GATEWAY_CLIENT_MODES.NODE,
    });
    const nodeId = paired.identity.deviceId;
    const pairing = await requestNodePairing({
      nodeId,
      platform: "linux",
      deviceFamily: "Linux",
      commands: ["camera.list"],
    });
    await approveNodePairing(pairing.request.requestId, {
      callerScopes: ["operator.pairing", "operator.write"],
    });
    await writeConfigFile({ gateway: { nodes: { commands: { allow: ["camera.list"] } } } });

    let kernel: Awaited<ReturnType<typeof createGatewayKernel>> | undefined;
    const createKernel = createGatewayKernel;
    const factory = vi.spyOn(await import("./server-kernel.js"), "createGatewayKernel")
      .mockImplementation(async (...args) => {
        kernel = await createKernel(...args);
        return kernel;
      });
    const realResolve = nodeState.resolveCurrentPairedDeviceNodeBinding;
    const readReady = createDeferredCore();
    const releaseRead = createDeferredCore();
    let holdNextRead = false;
    const resolver = vi.spyOn(nodeState, "resolveCurrentPairedDeviceNodeBinding")
      .mockImplementation(async (id) => {
        const binding = await realResolve(id);
        if (holdNextRead && id === nodeId) {
          holdNextRead = false;
          readReady.resolve();
          await releaseRead.promise;
        }
        return binding;
      });
    let started: Awaited<ReturnType<typeof startServer>>;
    try {
      started = await withEnvAsync({ OPENCLAW_TEST_MINIMAL_GATEWAY: undefined }, () => startServer("secret"));
    } catch (error) {
      factory.mockRestore();
      resolver.mockRestore();
      throw error;
    }
    const { port, server } = started;
    let node: Awaited<ReturnType<typeof connectGatewayClient>> | undefined;
    let invocation: ReturnType<NonNullable<typeof kernel>["nodeRegistry"]["invoke"]> | undefined;
    let progress: Promise<unknown> | undefined;
    let mutation: Promise<unknown> | undefined;
    let writer: ReturnType<typeof vi.spyOn> | undefined;
    let transport: ReturnType<typeof vi.spyOn> | undefined;
    const releaseMutation = createDeferredCore();
    const queued = createDeferredCore();
    const dispatched = createDeferredCore<{ id: string; nodeId: string }>();
    const inputReceived = createDeferredCore<unknown>();
    const chunks: string[] = [];
    const unblock = () => { releaseRead.resolve(); releaseMutation.resolve(); };
    await runQaGatewayFixture(async () => {
      await server.startupSettled;
      if (!kernel) throw new Error("real Gateway kernel missing");
      node = await connectGatewayClient({
        url: `ws://127.0.0.1:${port}`,
        token: "secret",
        role: "node",
        clientName: GATEWAY_CLIENT_NAMES.NODE_HOST,
        mode: GATEWAY_CLIENT_MODES.NODE,
        platform: "linux",
        deviceFamily: "Linux",
        scopes: [],
        commands: ["camera.list"],
        deviceIdentity: paired.identity,
        onEvent: (event) => {
          if (event.event === "node.invoke.request") dispatched.resolve(event.payload as { id: string; nodeId: string });
          if (event.event === "node.invoke.input") inputReceived.resolve(event.payload);
        },
      });
      invocation = kernel.nodeRegistry.invoke({
        nodeId, command: "camera.list", timeoutMs: 30_000, idleTimeoutMs: 20_000,
        onProgress: (chunk) => chunks.push(chunk),
      });
      const frame = await withTimeout(dispatched.promise, 10_000, "real invoke request");
      const session = kernel.nodeRegistry.get(nodeId);
      if (!session) throw new Error("registered real socket missing");
      transport = vi.spyOn(session.client.socket, "send");
      if (mode === "metadata") {
        holdNextRead = true;
        progress = node.request("node.invoke.progress", { invokeId: frame.id, nodeId, seq: 0, chunk: "working" });
        void progress.catch(() => undefined);
        await withTimeout(readReady.promise, 10_000, "real progress pairing read");
      }
      const deleteExternally = () => {
        const external = new DatabaseSync(resolveOpenClawStateSqlitePath());
        try { external.prepare("DELETE FROM device_pairing_paired WHERE device_id = ?").run(nodeId); }
        finally { external.close(); }
      };
      if (mode === "observed-external") {
        deleteExternally();
        expect(await getPairedDevice(nodeId)).toBeNull();
      }
      {
        const realWrite = stateWorker.runOpenClawStateWorkerOperation;
        writer = vi.spyOn(stateWorker, "runOpenClawStateWorkerOperation")
          .mockImplementationOnce(async (...args) => {
            queued.resolve();
            await releaseMutation.promise;
            return realWrite(...args);
          });
        mutation = mode === "metadata" || mode === "observed-external" || mode === "unobserved-external"
          ? updatePairedDeviceMetadata(nodeId, { displayName: "telemetry" })
          : mode === "revoke"
            ? revokeDeviceToken({ deviceId: nodeId, role: "node" })
            : rotateDeviceToken({ deviceId: nodeId, role: "node", scopes: [] });
        void mutation.catch(() => undefined);
        await withTimeout(Promise.race([queued.promise, mutation]), 10_000, "queued pairing mutation");
      }
      if (mode === "unobserved-external") {
        deleteExternally();
        // Explicit negative control: cross-process edits are not instant publication invalidations.
        expect(() => kernel!.nodeRegistry.sendInvokeInput(frame.id, { command: "before-observation" })).not.toThrow();
        await withTimeout(inputReceived.promise, 10_000, "unobserved external edit still permits cached input");
        releaseMutation.resolve();
        await expect(mutation).resolves.toBe(false);
        expect(await getPairedDevice(nodeId)).toBeNull();
        transport.mockClear();
      }
      if (mode === "metadata") {
        expect(() => kernel!.nodeRegistry.sendInvokeInput(frame.id, { command: "continue" })).not.toThrow();
        await withTimeout(inputReceived.promise, 10_000, "real input socket delivery");
        releaseRead.resolve();
        await expect(progress).resolves.toMatchObject({ ok: true });
        expect(chunks).toEqual(["working"]);
        releaseMutation.resolve();
        await expect(mutation).resolves.toBe(true);
        await node.request("node.invoke.result", { id: frame.id, nodeId, ok: true, payload: { proof: true } });
        await expect(invocation).resolves.toMatchObject({ ok: true });
      } else {
        expect(() => kernel!.nodeRegistry.sendInvokeInput(frame.id, { command: "must-not-send" })).toThrow();
        expect(transport.mock.calls.filter(([payload]) => typeof payload === "string" && payload.includes('"event":"node.invoke.input"'))).toHaveLength(0);
        releaseMutation.resolve();
        if (mode === "observed-external" || mode === "unobserved-external") await expect(mutation).resolves.toBe(false);
        else await expect(mutation).resolves.toMatchObject({ ok: true });
        await expect(node.request("node.invoke.progress", { invokeId: frame.id, nodeId, seq: 0, chunk: "revoked" })).rejects.toThrow();
        expect(chunks).toEqual([]);
      }
    },
    unblock,
    async () => { await Promise.allSettled([mutation, progress]); writer?.mockRestore(); transport?.mockRestore(); },
    async () => { await node?.stopAndWait(); },
    async () => { await server.close({ reason: "pairing proof complete" }); },
    async () => { await Promise.allSettled([invocation]); },
    () => { resolver.mockRestore(); factory.mockRestore(); });
  },
  120_000,
);

@gisk0

gisk0 commented Sep 29, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 29, 2026
@gisk0

gisk0 commented Sep 29, 2026

Copy link
Copy Markdown
Author

Response to ClawSweeper revision 2 at f6055cebe7e2da75bd4fd664203aefa22734317b: the P1 behavior is confirmed by the negative control, not disputed or fixed. This metadata interval becomes usable under the patch, and an unobserved external deletion can therefore precede a cached send. The PR description now labels that explicitly as an open P1.

Disposition: escalated for an explicit security-owner contract decision. The documented worker-observation contract explains the implementation choice, but it is not a substitute for acceptance of this changed interval. This PR remains blocked unless the owner accepts that boundary at this exact head or requests a final-I/O repair. No approval or waiver is assumed. The existing exact-head approval request remains outstanding.

The transport-proof request is satisfied according to revision 2. Its remaining security, merge-risk, patch-quality, and next-step bullets all refer to the same unresolved external-revocation finding and owner approval; none is being marked resolved. CI is separately red, with the diagnosis linked in the description.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: L and removed size: M labels Sep 29, 2026
@gisk0

gisk0 commented Sep 29, 2026

Copy link
Copy Markdown
Author

Response to ClawSweeper revision 3: fixed in f9027947f5b769b3bccdbd64ba08cf0cc6a53a61.

Removed the metadata preservesBindings exception entirely. Every pairing mutation fences publication again. Coding duplex input and incoming progress/results now wait for the pairing owner, refresh the exact binding, and perform their synchronous effect under that owner after rechecking the pending invocation, connection, generation, cancellation, policy, and caller authority. Both inbound siblings and the plugin/Claude duplex send paths use the guard.

The prior negative-control behavior is superseded: an isolated real Gateway plus authenticated node WebSocket now sends zero queued input and accepts no queued progress/result after external deletion, revocation, or rotation. Valid metadata overlap waits and then delivers exactly one input. Local revoke/rotate also deny. All six cases passed. This proves commits preceding the fresh read are observed; it does not claim atomic exclusion of foreign SQLite commits after that read.

The PR body is being updated to describe the final implementation and current evidence. Exact-head maintainer security approval remains a separate required gate; no approval is claimed.

Independent review disposition: the cached-authority P1 is removed. One AutoReview P2 asked to defer idle expiry while progress awaits authority. We retained the existing deadlines: base already waits during an active pairing mutation at router admission, and unverified/duplicate progress must not extend invocation lifetime. The added post-router final check deliberately closes that authority gap. Metadata waiting is bounded by existing invocation deadlines, as the PR description now states.

Validation of this candidate: 466 unique tracked tests passed across 13 files, plus the six isolated Gateway/WebSocket cases. Format, typed lint, core types, three relevant test-type graphs, and commit-hook secret scan passed. The exact committed portal test passed in 18.942s under its unchanged 30s timeout. An earlier combined batch timed out on that test; its timing/order cause remains unproven. These isolated passes do not erase that failure. Full local build/suite, aggregate throughput benchmark, and a deployed Codex workload were not run.

Reproducible transport fixture

Run the fixture below as src/gateway/server.pairing-publication-live-proof.test.ts at this head using:

node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-server.config.ts src/gateway/server.pairing-publication-live-proof.test.ts --maxWorkers=1

The executed fixture SHA256 was 4a46876c21ae8df3be8f70d4621710f0c2b7ceb45208e9c9e8fd615d1d83cbb1. The published copy below adds only an erased unknown[] annotation to a spy-call filter (SHA256 f271a0c65f78e54230896a2dc4f1b7f5f0365d3769863e900a44f9188356a15d); that annotation-only copy was not rerun. The original six runtime cases passed in 214.72s including cold worker preparation. The scratch fixture is evidence, outside the tracked patch.

Six-case real Gateway/WebSocket fixture
// Scratch integration evidence for PR #161209; not part of the published patch.
import { DatabaseSync } from "node:sqlite";
import { expect, test, vi } from "vitest";
import { runQaGatewayFixture } from "../../test/helpers/qa-gateway-cleanup.js";
import { writeConfigFile } from "../config/config.js";
import * as nodeState from "../infra/device-pairing-node-state.js";
import { approveNodePairing, requestNodePairing } from "../infra/device-pairing-node.js";
import { revokeDeviceToken, rotateDeviceToken } from "../infra/device-pairing-tokens.js";
import { updatePairedDeviceMetadata } from "../infra/device-pairing.js";
import { withTimeout } from "../infra/fs-safe.js";
import { createDeferredCore } from "../shared/deferred.js";
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
import * as stateWorker from "../state/openclaw-state-worker-store.js";
import { withEnvAsync } from "../test-utils/env.js";
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
import { pairDeviceIdentity } from "./device-authz.test-helpers.js";
import { createGatewayKernel } from "./server-kernel.js";
import { connectGatewayClient } from "./test-helpers.e2e.js";
import { installGatewayTestHooks, startServer } from "./test-helpers.js";

installGatewayTestHooks({ scope: "suite" });

const modes = [
  "metadata",
  "revoke",
  "rotate",
  "external-delete",
  "external-revoke",
  "external-rotate",
] as const;

test.each(modes)(
  "real WebSocket fresh pairing effect boundary: %s",
  async (mode) => {
    if (!process.env.OPENCLAW_STATE_DIR) throw new Error("isolated state required");
    const paired = await pairDeviceIdentity({
      name: `pairing-proof-${mode}`,
      role: "node",
      scopes: [],
      clientId: GATEWAY_CLIENT_NAMES.NODE_HOST,
      clientMode: GATEWAY_CLIENT_MODES.NODE,
    });
    const nodeId = paired.identity.deviceId;
    const pairing = await requestNodePairing({
      nodeId,
      platform: "linux",
      deviceFamily: "Linux",
      commands: ["camera.list"],
    });
    await approveNodePairing(pairing.request.requestId, {
      callerScopes: ["operator.pairing", "operator.write"],
    });
    await writeConfigFile({ gateway: { nodes: { commands: { allow: ["camera.list"] } } } });

    let kernel: Awaited<ReturnType<typeof createGatewayKernel>> | undefined;
    const realCreateKernel = createGatewayKernel;
    const factory = vi
      .spyOn(await import("./server-kernel.js"), "createGatewayKernel")
      .mockImplementation(async (...args) => {
        kernel = await realCreateKernel(...args);
        return kernel;
      });
    const realOwner = nodeState.withCurrentPairedDeviceNodeBinding;
    const queuedReads = createDeferredCore();
    let observeOwner = false;
    let ownerCalls = 0;
    let ownerEffects = 0;
    const requiredOwnerCalls = mode === "metadata" ? 2 : 3;
    // Observe the production owner entry and effect; never replace its read, binding, or lock.
    const owner = vi
      .spyOn(nodeState, "withCurrentPairedDeviceNodeBinding")
      .mockImplementation(function <T>(
        id: string,
        effect: (binding: nodeState.PairedDeviceNodeBinding | undefined) => T,
        baseDir?: string,
      ): Promise<T> {
        const observed = observeOwner && id === nodeId;
        if (observed && ++ownerCalls >= requiredOwnerCalls) queuedReads.resolve();
        return realOwner(
          id,
          (binding) => {
            if (observed) ownerEffects++;
            return effect(binding);
          },
          baseDir,
        );
      });
    let started: Awaited<ReturnType<typeof startServer>>;
    try {
      started = await withEnvAsync({ OPENCLAW_TEST_MINIMAL_GATEWAY: undefined }, () =>
        startServer("secret"),
      );
    } catch (error) {
      factory.mockRestore();
      owner.mockRestore();
      throw error;
    }
    const { port, server } = started;
    let node: Awaited<ReturnType<typeof connectGatewayClient>> | undefined;
    let invocation: ReturnType<NonNullable<typeof kernel>["nodeRegistry"]["invoke"]> | undefined;
    let input: Promise<void> | undefined;
    let progress: Promise<unknown> | undefined;
    let result: Promise<unknown> | undefined;
    let mutation: Promise<unknown> | undefined;
    let writer: ReturnType<typeof vi.spyOn> | undefined;
    let transport: ReturnType<typeof vi.spyOn> | undefined;
    const releaseMutation = createDeferredCore();
    const queuedMutation = createDeferredCore();
    const dispatched = createDeferredCore<{ id: string; nodeId: string }>();
    const inputReceived = createDeferredCore<unknown>();
    const inputFrames: unknown[] = [];
    const chunks: string[] = [];
    const inputSends = () =>
      transport?.mock.calls.filter(
        ([payload]: unknown[]) =>
          typeof payload === "string" && payload.includes('"event":"node.invoke.input"'),
      ) ?? [];

    await runQaGatewayFixture(
      async () => {
        await server.startupSettled;
        if (!kernel) throw new Error("real Gateway kernel missing");
        node = await connectGatewayClient({
          url: `ws://127.0.0.1:${port}`,
          token: "secret",
          role: "node",
          clientName: GATEWAY_CLIENT_NAMES.NODE_HOST,
          mode: GATEWAY_CLIENT_MODES.NODE,
          platform: "linux",
          deviceFamily: "Linux",
          scopes: [],
          commands: ["camera.list"],
          deviceIdentity: paired.identity,
          onEvent: (event) => {
            if (event.event === "node.invoke.request")
              dispatched.resolve(event.payload as { id: string; nodeId: string });
            if (event.event === "node.invoke.input") {
              inputFrames.push(event.payload);
              inputReceived.resolve(event.payload);
            }
          },
        });
        invocation = kernel.nodeRegistry.invoke({
          nodeId,
          command: "camera.list",
          timeoutMs: 30_000,
          idleTimeoutMs: 20_000,
          onProgress: (chunk) => chunks.push(chunk),
        });
        void invocation.catch(() => undefined);
        const frame = await withTimeout(dispatched.promise, 10_000, "real invoke request");
        const session = kernel.nodeRegistry.get(nodeId);
        if (!session) throw new Error("registered real socket missing");
        transport = vi.spyOn(session.client.socket, "send");
        const realWrite = stateWorker.runOpenClawStateWorkerOperation;
        writer = vi
          .spyOn(stateWorker, "runOpenClawStateWorkerOperation")
          .mockImplementationOnce(async (...args) => {
            queuedMutation.resolve();
            await releaseMutation.promise;
            return realWrite(...args);
          });
        mutation =
          mode === "revoke"
            ? revokeDeviceToken({ deviceId: nodeId, role: "node" })
            : mode === "rotate"
              ? rotateDeviceToken({ deviceId: nodeId, role: "node", scopes: [] })
              : updatePairedDeviceMetadata(nodeId, { displayName: "telemetry" });
        void mutation.catch(() => undefined);
        await withTimeout(
          Promise.race([queuedMutation.promise, mutation]),
          10_000,
          "queued pairing mutation",
        );

        observeOwner = true;
        input = kernel.nodeRegistry.sendInvokeInputWhenCurrent(frame.id, { command: "continue" });
        void input.catch(() => undefined);
        progress = node.request("node.invoke.progress", {
          invokeId: frame.id,
          nodeId,
          seq: 0,
          chunk: "working",
        });
        void progress.catch(() => undefined);
        if (mode !== "metadata") {
          result = node.request("node.invoke.result", {
            id: frame.id,
            nodeId,
            ok: true,
            payload: { mustNotEscape: true },
          });
          void result.catch(() => undefined);
        }
        await withTimeout(
          queuedReads.promise,
          10_000,
          "input and inbound RPCs waiting on real owner",
        );
        expect(ownerEffects).toBe(0);
        expect(inputSends()).toHaveLength(0);
        expect(inputFrames).toHaveLength(0);
        expect(chunks).toEqual([]);

        if (mode.startsWith("external-")) {
          const external = new DatabaseSync(resolveOpenClawStateSqlitePath());
          try {
            if (mode === "external-delete") {
              external.prepare("DELETE FROM device_pairing_paired WHERE device_id = ?").run(nodeId);
            } else if (mode === "external-revoke") {
              external
                .prepare(
                  "UPDATE device_pairing_paired SET tokens_json = json_set(tokens_json, '$.node.revokedAtMs', 100) WHERE device_id = ?",
                )
                .run(nodeId);
            } else {
              external
                .prepare(
                  "UPDATE device_pairing_paired SET tokens_json = json_set(tokens_json, '$.node.token', 'scratch-external-replacement', '$.node.rotatedAtMs', 100) WHERE device_id = ?",
                )
                .run(nodeId);
            }
          } finally {
            external.close();
          }
        }

        releaseMutation.resolve();
        await mutation;
        if (mode === "metadata") {
          await expect(input).resolves.toBeUndefined();
          await withTimeout(
            inputReceived.promise,
            10_000,
            "exactly one real input delivery after metadata",
          );
          await expect(progress).resolves.toMatchObject({ ok: true, ignored: false });
          expect(inputSends()).toHaveLength(1);
          expect(inputFrames).toHaveLength(1);
          expect(chunks).toEqual(["working"]);
          result = node.request("node.invoke.result", {
            id: frame.id,
            nodeId,
            ok: true,
            payload: { proof: true },
          });
          await expect(result).resolves.toMatchObject({ ok: true });
          await expect(invocation).resolves.toMatchObject({ ok: true });
        } else {
          await expect(input).rejects.toThrow();
          const replies = await Promise.allSettled([progress, result]);
          for (const reply of replies) {
            // Router denial may reject/close the connection; late handlers may safely ignore.
            if (reply.status === "fulfilled") expect(reply.value).toMatchObject({ ignored: true });
          }
          expect(inputSends()).toHaveLength(0);
          expect(inputFrames).toHaveLength(0);
          expect(chunks).toEqual([]);
          await expect(invocation).resolves.toMatchObject({ ok: false });
        }
        expect(ownerEffects).toBeGreaterThan(0);
      },
      () => {
        releaseMutation.resolve();
      },
      async () => {
        await Promise.allSettled([mutation, input, progress, result]);
        writer?.mockRestore();
        transport?.mockRestore();
      },
      async () => {
        await node?.stopAndWait();
      },
      async () => {
        await server.close({ reason: "pairing proof complete" });
      },
      async () => {
        await Promise.allSettled([invocation]);
      },
      () => {
        owner.mockRestore();
        factory.mockRestore();
      },
    );
  },
  120_000,
);

@gisk0 gisk0 changed the title fix(nodes): prevent disconnects during routine device updates fix(nodes): wait for pairing publication before duplex I/O Sep 29, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 29, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 29, 2026
@gisk0

gisk0 commented Sep 29, 2026 •

Copy link
Copy Markdown
Author

Recorded follow-through for f9027947f5b769b3bccdbd64ba08cf0cc6a53a61:

ClawSweeper revision 4 confirms the prior cached-authority finding is addressed, accepts the real transport proof, and marks this ready for maintainer look. Its remaining decision is exact-head security-owner acceptance of the disclosed fresh-read/local-lock observation boundary. That approval is not claimed here.

CI is testing merge 68fdba56f312d76206be9a8e675fc3de6de4f28e against newer upstream bcc6b571c4489bfd8e5557d2b0900fb64e1e8936. Failures observed so far:

Job Failure and attribution
UI E2E 6/9 Emoji identity-editor save times out waiting for agents.update. The test installs its own browser MockGateway and this job skips real Gateway tests; it does not exercise the changed node pairing path. Exact UI timing cause unproven.
Node shard 28 Doctor snapshot cleanup fails, followed by admission/lifecycle failures (110 failed cases). The first case has migrateState:false and fails through generic update-run history reading, before pairing mutations or node traffic. Its cleanup owner changed upstream after the local validation base; it is unchanged by this PR. The generic error hides the underlying cleanup cause.
Node shard 13 Startup tests reach a worker-free fixture mock during generic state reads (17 failures). The exact upstream base shares a non-isolated fork and runs the worker-free fixture first; later direct database assertions reach its throwing Worker mock. Strong source/order evidence of inherited fixture contamination; no clean-base runtime reproduction.
Node shard 42 SDK session disk-budget drainage leaves one observed native worker alive. The fixture exercises session-store mutations and disk-budget worker retirement, outside the changed node stream paths. Exact retirement cause unproven.
Node shard 11 A direct SQLite staging diagnostic expects a staging-root error but receives a combined allocation/cleanup error. It fails before the worker-startup half and invokes no Gateway/pairing path; precise cleanup cause unproven.
Node shard 4 Update-status fixture reports this.process.unref is not a function instead of lastRun. The mocked process path is unchanged by this PR; the exact object/mocking cause remains unproven.
Node shard 12 102 live-model-switch cases encounter a missing async metadata export: the exact upstream base mock supplies only the synchronous export while its consumer calls the async one. A separate direct snapshot cleanup assertion returns false; that underlying cleanup cause remains unproven.

The exact base-to-CI-merge comparison contains only this PR's 13 effective pairing/Gateway files. These are source/path attributions, not standalone base-runtime reproductions. No unrelated fixtures were changed and no CI jobs were manually rerun. At 16:14 UTC this CI run had 7 failed jobs and 3 still running; this is not a green-CI claim. The required approval gate remains blocked. A separately requested test-value/simplification audit is now underway; these observations remain bound to the published head above.

Final late result, 17:34 UTC: Node shard 41 also failed: server-reload-handlers.test.ts timed out at 120s in deferred restart SecretRef revalidation (held promotion false), with 1,750 other cases passing. The test and its reload handler are identical between the exact CI base and merge; the test controls fake timers, restart preparation and plugin leases. The timeout cause remains unproven, and no clean-base runtime reproduction is claimed. This brings that CI run to eight failed test jobs; it remains evidence for the older head only.

@gisk0

gisk0 commented Sep 29, 2026

Copy link
Copy Markdown
Author

Test-audit follow-up in d69797077ef8500efec17b8f4f23e5a02a5bf26a:

  • Reduced the PR from 13 to 12 files and net growth from 682 to 473 lines: production 133→127, tests 549→346.
  • Removed the obsolete seven-operation metadata matrix and duplicated fence/read compositions. The primary publication suite now has 19 cases rather than 33.
  • Corrected a coverage weakness: input rejection previously retired the invocation before the subsequent progress/result assertions. The replacement inbound cases keep cached authority current, externally delete the pairing, then exercise exactly one inbound guard. They cannot pass merely because another effect already removed the invocation.
  • Strengthened the existing plugin test to revoke delegated authority while a send waits, proving the actual final callback and failed delivery rather than only asserting callback shape.
  • Removed an unused factory override and reverted the publication owner to the original strict implementation; its extra finish-time block was redundant after the metadata exception was removed. Retained failed-write/recovery coverage because no other test independently protects that contract.

Validation: 174/174 focused tests across five files passed (88.1s wrapper), followed by 19/19 publication cases on the final formatted source (34.0s wrapper). Targeted formatting and typed lint passed; core types (110.5s) and selected gateway-server/infra test-type graphs (545.0s including setup) passed. Tests ran serially with one worker in an isolated checkout; cold worker preparation cost 459.0s for the final run.

Three disposable fault controls each failed for the intended reason: replacing only the asynchronous input guard with the real synchronous send caused failed to send node invoke input during the metadata fence; replacing only the progress or result guard with its real synchronous method independently produced expected true to be false after an external pairing deletion. These are guard-bypass controls, not pristine-base executions. No production source was altered for the controls; the scratch file was excluded from the published patch.

Fresh repository Codex AutoReview reports no P0–P2 findings. The final formatting-only indentation change has an empty whitespace-insensitive diff from that reviewed candidate. These checks do not claim paired vendor scans (requester waiver), a full build/suite, a throughput benchmark, or a production deployment.

The final authority semantics and disclosed foreign-commit observation limit are unchanged from the head ClawSweeper reviewed in revision 4. Exact-head maintainer security approval remains required; none is claimed.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 29, 2026
@gisk0

gisk0 commented Sep 29, 2026

Copy link
Copy Markdown
Author

Current-head CI follow-through for d69797077ef8500efec17b8f4f23e5a02a5bf26a.

ClawSweeper revision 5 reports no concrete contributor-facing blocker and sufficient real-behavior proof. Its remaining decision is exact-head security-owner acceptance of the disclosed foreign-commit observation boundary; no maintainer approval is claimed.

CI run 36606101603 checks merge 5c38192fcceb0cfce65142ab16f791f87dfc8f7d, created from this head and upstream 9b2da9290be3002f1a2dcae03c0bd139d8a1705a.

Job Evidence and disposition
Node shard 35 102 live-model-switch cases fail because the plugin-metadata-snapshot.js mock omits resolvePluginMetadataSnapshotAsync. The exact CI base mock supplies only the synchronous resolver, while its consumer calls the async resolver. Both files have identical blob IDs in the CI base and merge. Source-proven inherited mock mismatch; no standalone base runtime reproduction is claimed.
UI E2E 5/9 Loading-skeleton test fails its composer geometry assertion (bottomGap = -500, expected >=0); 390 other cases pass. The fixture installs a browser MockGateway, and the job sets OPENCLAW_UI_E2E_SKIP_REAL_GATEWAY=1. It does not exercise the changed backend node transport. Underlying layout/timing cause unproven.
Node shard 42 The physical session-disk-usage fixture leaves native worker [5] alive after SDK maintenance drainage. The exact base fixture performs session entry upsert/delete, disk-budget scans and worker retirement; it exercises no node invocation or pairing-write path. 1,159 sibling cases pass. The same diagnostic occurred on the prior head; the underlying retirement cause remains unproven.
Node shard 12 Direct SQLite snapshot staging diagnostic expects a staging-root error but receives SQLite snapshot allocation and cleanup failed. The assertion occurs before the fixture starts its read-only worker and invokes no Gateway or pairing traffic. Same diagnostic as the prior run; underlying cleanup cause unproven.
Node shard 15 Cron on-exit receipt rearm test expects lastRunStatus ok but receives error after simulated timeout. The fixture controls exit watchers, receipt ownership and a mocked command runner; no paired node transport is involved. Exact timing/status cause unproven.

No unrelated fixtures or UI were changed, and no CI job was manually rerun. At the end of the 20-minute watch (17:56 UTC), this run had 103 passed jobs, five failed jobs listed above, and nine still running. This is not a green-CI claim. Required code-owner/security approval is also absent; the PR remains blocked. The bounded watch has ended.

@steipete

Copy link
Copy Markdown
Contributor

Thanks @gisk0 — this PR found the real problem: routine device writes (presence, metadata, host stats) fenced every node's pairing binding while the write was in flight, so active node streams and requests failed even though nothing about their own pairing changed.

That fence is now handled at its owner instead of being worked around in node transport:

With both on main, queuing duplex I/O behind pairing publication is no longer needed, so I'm closing this as superseded. Your diagnosis is credited in #169575. Thank you for the careful work here, including keeping revocation strict when the first revision relaxed it.

@steipete steipete closed this Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-review-required security-sensitive-changed size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants