Skip to content

improve(setup): diagnose native Gateway handshake delays (Layer 2) - #1924

Merged
karkarl merged 5 commits into
mainfrom
karkarl-gateway-handshake-diagnostics
Nov 4, 2026
Merged

karkarl merged 5 commits into
mainfrom
karkarl-gateway-handshake-diagnostics

Conversation

@karkarl

@karkarl karkarl commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Layer 2 of the native Gateway recovery stack. Depends on #1917 (fix(connection): retry promptly while the Gateway is starting). Targets karkarl-startup-rejection-handling, not main. Comparison base: fea2adbba185db491d37a2b6192eecb941b96cc4.

Maintainer edits were requested at creation. GitHub reports the fork-collaboration flag as false for this user-authorized same-repository stack and rejects enabling it with HTTP 422: Fork collab can only be enabled on cross-repo pull requests. Branch edits therefore use existing repository permissions; no fork-collaboration permission is claimed.

What Problem This Solves

Native Gateway onboarding diagnostics cannot distinguish time spent opening a transport, verifying provenance, and waiting for the application handshake.

User Impact

User impact: support can inspect sanitized handshake phases in the existing native setup JSONL log. No UI, deadline, readiness policy, retry policy, credential ordering, pairing action, or network request changes.

Draft, not runtime-validated or ready to merge. SetupEngine has 15 existing cleanup-fixture failures caused by the host's script execution policy. Store ARM64/x64, current-head UI/MCP, real Gateway and WSL/MXC proof remain blocked by missing runtime authority. The original clean Store timing does not establish a single root cause.

Why This Change Was Made

OpenClawGatewayClient.HandshakeObserved reports transport/challenge, provenance authorization, connect admission/result, and disconnection/failure phases. It uses source transport generations, including rejected pre-auth sockets, plus monotonic total and previous-phase milliseconds. Reconnect authorization belongs to the preceding generation until the next socket exists. Startup classification and bounded retry hints reuse Layer 1.

The existing connection/session/host ownership chain forwards one subscription to SetupLogger as native.gateway.handshake, with a session-local connection_attempt counter disambiguating new clients. Stale, canceled and disposed work cannot emit. The native Shared client keeps NullLogger: no general protocol logger is forwarded. Only enum names, counters, durations and a bounded retry hint are projected. No nonce, token, identity, endpoint, configuration, raw response, exception text, operation name or user content is recorded.

The sink remains synchronous like existing setup logs; elapsed measurements can include prior logging overhead. This layer does not attribute the original timeout or change its deadline. It does not tail package output or recreate the activity UI owned by #1735 (feat(setup): stream live native Gateway activity log and typed failure diagnosis).

Evidence

Behavioral tests exercise real loopback sockets and actual JSONL output, not source regex proxies: ordered success phases, current/stale generation fences, delayed authorization success/exception, cancellation/disposal, typed auth/device-token/protocol/pairing/startup categories, three rejected sockets followed by an accepted fourth, pre-retry authorization, and absence of sensitive sentinels. The native test verifies its accepted stored credential remains intact.

Independent P0-P3 narrative source review found one P2: the general free-text redactor corrupted AuthorizationStarted and token-related enum names. An actual JSONL regression reproduced the failure (1 failed before the fix). A private typed wrapper now projects only allowlisted primitive fields; every phase/error enum round-trips, while generic token data remains redacted. A separate narrow independent follow-up found no remaining P0-P3 issues. Independent rubber-duck implementation/proof-plan review found no blockers; its synchronous-logging caveat is documented.

Reviews used the canonical Copilot-subagent fallback because Codex CLI was unavailable. Host: Copilot subagents; model identities unverified. These are narrative assessments, without helper-owned isolation, frozen-input checks or structured-result validation. They are not runtime proof.

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Required proof pools

  • windows-11-arm64: original symptom was native Store ARM64 onboarding; compilation alone cannot establish runtime timing or x64 parity. Runtime blocked.
  • windows-winui-interactive: current-head native setup diagnostic visibility and lifecycle. No new UI, but live app proof is blocked.
  • windows-wsl-gateway-e2e: shared operator transport/reconnect hooks require real Gateway-path regression confidence. Provisioning blocked.
  • windows-wsl-mxc: Gateway setup/connection-path regression gate, not a claim that execution or containment policy changed. Required native/WSL provisioning is blocked.

Validation

Committed head: e4ce43f01bd4759f8748e0b510dfe39e27941495. Native Windows ARM64, .NET SDK 10.0.403. Set OPENCLAW_REPO_ROOT to this worktree and OPENCLAW_TRAY_DATA_DIR to its isolated TestResults\isolated-profile; clear inherited OPENCLAW_RUN_* opt-ins and conflicting local-data overrides. No installed/shared app or Gateway was launched or reconfigured.

Product CI: running, not yet green. After native Companion stack registration, Build and Test run 40964791761, attempt 1, was verified as pull_request, in_progress, with no conclusion and exact head e4ce43f01bd4759f8748e0b510dfe39e27941495. Historically, before registration, product CI had not triggered for this feature-base PR and the only observed checks were successful dispatch checks (run 40961546378, run 40961397888). Those dispatch successes remain distinct from build/test validation. The completed results below are local full-head results only; the running CI is not a pass or runtime proof. No workflow dispatch, retarget, or CI configuration change was performed.

  • .\build.ps1: PASS, all five targets, Debug win-arm64.
  • dotnet build .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --verbosity quiet: PASS, 0 warnings/errors, genuine initial build/restore before --no-restore.
  • dotnet build .\tests\OpenClaw.Connection.Tests\OpenClaw.Connection.Tests.csproj --verbosity quiet: PASS, 0 warnings/errors, genuine initial build/restore before --no-restore.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore: PASS, 4,847 passed / 24 skipped / 0 failed (4,871 total).
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore: PASS, 4,754 passed / 0 skipped / 0 failed.
  • dotnet test .\tests\OpenClaw.Connection.Tests\OpenClaw.Connection.Tests.csproj --no-restore: PASS, 1,700 passed / 1 skipped / 0 failed (1,701 total).
  • dotnet test .\tests\OpenClaw.SetupEngine.Tests\OpenClaw.SetupEngine.Tests.csproj --no-restore: FAIL / host-policy blocker, 2,474 passed / 15 failed / 1 skipped (2,490 total).
  • .\scripts\validate-docs.ps1: PASS, 68 Markdown files; both proof-pool schema paths and flow regression passed.
  • git diff --check: PASS.

Pre-commit focused runs on the identical reviewed product/test content: Shared observation filter FullyQualifiedName~GatewayHandshakeObservationTests|FullyQualifiedName~HandshakeObservations|FullyQualifiedName~StartupUnavailable_Retries, 14 passed / 0 skipped; Setup filter FullyQualifiedName~SetupLoggerTests|FullyQualifiedName~NativeGatewaySetupConnectionTests, 63 passed / 0 skipped. Full committed-head suites above supersede these for closeout. No baseline copy of the new observation seam existed; the review-found redaction defect has its separate fail/pass negative control.

All 15 final-head SetupEngine failures are in unchanged GatewayPackageCleanupTests: 8 receipt-validation cases and 7 registration-binding cases. Each failed because its temporary guard-test.ps1 could not execute: running scripts is disabled on this system, UnauthorizedAccess. The first run reproduced the same 15 failures, and Layer 1 independently reported that blocker. This layer did not run a separate baseline checkout or change machine policy, cleanup behavior, tests, or skip gates. The suite remains non-green; no execution-policy bypass was used. Final-head TRX confirms actual execution and the observation/logger tests passed.

The first full run on 787c9d2f caught one task-owned ledger formatting error: its guard field listed two test references instead of one. The final commit changes only that documentation field, preserves the independently reviewed product/test content, and passed all 6 ArchitectureLedgerConsistencyTests before rerunning the full closeout above. The initial result (Shared 4,846 passed / 1 failed / 24 skipped) is retained, not relabeled as passing.

Real Behavior Proof

  • Environment tested: native Windows ARM64 managed tests with fresh loopback fixtures, isolated identities/settings, actual production client and local JSONL logger. Synthetic fixtures, not the installed Gateway, UI or provider runtime.
  • PR head or commit tested: e4ce43f01bd4759f8748e0b510dfe39e27941495.
  • Exact steps or command run: committed-head Shared and SetupEngine commands above execute HandshakeObservations_SuccessReportsOnlySafeOrderedPhaseTimings, StartupUnavailable_RetriesFreshAuthorizedSocketsWithoutAuthOrPairingFailure, StartupRejections_RetryWithinSetupLifetimeWithoutRetiringAcceptedCredential, and HandshakeObservation_EnumValuesSurviveJsonlRedactionWithoutWeakeningGenericRedaction.
  • Evidence after fix: all four named behavioral tests passed on the committed head. The full Shared suite passed 4,847 cases and the SetupEngine suite passed 2,474 cases, including the native observation and JSONL tests; its 15 unrelated cleanup-fixture failures remain explicitly reported above. TRX and command logs are retained under the local TestResults\layer2-head-e4ce43f0 run and session artifacts.
  • Observed result: fixture assertions directly inspect emitted observations and persisted native.gateway.handshake JSONL, including safe enum names and generations; no assertion here establishes installed Store readiness or identifies the original slow phase.
  • Screenshot or artifact links verified? (Yes/No/N/A) N/A. No screenshots or public runtime artifacts claimed. Exact invocation TRX and logs are retained locally.
  • Not verified or blocked: Store ARM64 and x64 native onboarding/timing, current-head app UI and MCP discovery/invocation, real Gateway mediation, WSL/MXC and signed-package/clean-machine proof. Runtime launch, installation/configuration, process stop/restart, WSL provisioning, machine-policy changes and workflow dispatch were not authorized. No proof borrowed from Layer 1 or another PR. Product CI run 40964791761 is running, not yet green; earlier dispatch successes are not build/test validation.

Security Impact

  • New permissions or capabilities? (Yes/No) No.
  • Secrets or tokens handling changed? (Yes/No) No credential handling changes. New diagnostics deliberately exclude secrets and raw protocol data.
  • New or changed network calls? (Yes/No) No.
  • Command or tool execution surface changed? (Yes/No) No.
  • Data access scope changed? (Yes/No) No.
  • If any answer is Yes, explain the risk and mitigation: N/A. The typed log projection is a narrow allowlist, not a general redaction bypass.

Compatibility and Migration

  • Backward compatible? (Yes/No) Yes.
  • Config or environment changes? (Yes/No) No.
  • Migration needed? (Yes/No) No.
  • If yes, list the exact upgrade steps: N/A. Layer 1 remains the dependency; later stack work owns deadline/admission recovery.

Review Conversations

  • I replied to or resolved every bot review conversation addressed by this PR.
  • I left unresolved only conversations that still need maintainer judgment.

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

🦞👀
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.

@clawsweeper

clawsweeper Bot commented Oct 29, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge.

What this changes

This PR records sanitized native Gateway handshake phases and durations in the existing setup log.

Example: Three startup rejections precede an accepted fourth connection.

  • Before: The setup log cannot separate those handshake attempts or their phases.
  • After: StartupUnavailable entries identify transport generations 1, 2 and 3, followed by ConnectAccepted for generation 4.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused diagnostics with meaningful transport and logger coverage and no actionable source finding; supplied evidence remains limited to in-process fixtures.
Proof confidence 🦐 gold shrimp (3/6) This collaborator-authored PR is outside the ordinary contributor-proof gate; its complete body reports current-head ARM64 production-client loopback tests and actual JSONL assertions, while explicitly leaving installed Gateway behavior unexercised.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Support cannot distinguish transport opening, provenance verification and application-handshake waits during native Gateway onboarding.
Reason: Collaborator-authored direction adds useful local diagnostics through existing owners without introducing settings or changing connection policy.

Merge readiness

✅ Ready for maintainer review

Keep open: this collaborator-authored draft adds useful handshake diagnostics absent from main, and source review found no definite introduced defect.

Priority: P2
Reviewed head: e4ce43f01bd4759f8748e0b510dfe39e27941495

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied current-head evidence covers managed loopback clients and JSONL assertions, while installed native Gateway setup and the declared runtime proof pools remain unverified.
Agent review details

How this fits together

The shared operator client observes transport and handshake activity; the existing native connection, session and host forward typed observations to SetupLogger for local JSONL output.

flowchart TD
A[Gateway WebSocket] --> B[Shared transport]
B --> C[Operator handshake observations]
C --> D[Native setup connection]
D --> E[Setup session and host]
E --> F[SetupLogger]
F --> G[Local JSONL log]
Loading

Technical review

Best possible solution:

Keep typed observations in the existing connection owners and forward only allowlisted diagnostic fields through the existing setup logger.

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

Current-main source confirms that native setup lacks this phase-observation stream; supplied tests exercise its proposed behavior, and this read-only review executed no target code.

Is this the best way to solve the issue?

The diagnostic gap is missing phase attribution; the invariant is that observation preserves authorization, credentials and connection policy. The diff uses existing owners, and its narrow typed logger projection avoids corrupting enum names without weakening general redaction.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Socket-generation authorization keeps the original intent (603886a: Reject stale replacement sockets and preserve credential handoff boundaries, as recorded in fix: harden gateway recovery credential handoffs #1076.)
  • Protocol compatibility failures keeps the original intent (428db77: Validate hello-ok before publishing readiness or persisting handshake tokens; added observations retain those decisions.)
  • Native connection and session ownership keeps the original intent (3eed1f1: Share native onboarding while retaining staged runtime ownership, exact verification and guarded credential handling.)
  • Structured log-data sanitization changes intended behavior with a stated reason (8c9acbc: Sanitize diagnostic data before output; this PR explains and tests a private primitive-only projection because free-text redaction corrupts safe enum names.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Scott Hanselman: Raw commit a51029e adds src/OpenClaw.Shared/OpenClawGatewayClient.cs:3261 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a51029ef6f77; files: src/OpenClaw.Shared/OpenClawGatewayClient.cs)
  • Pedro Larroy: Raw commit e5122db adds src/OpenClaw.SetupEngine/SetupLogger.cs:16 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e5122db3c943; files: src/OpenClaw.SetupEngine/SetupLogger.cs)

Review metrics

Metric Value Why it matters
Introduced change Production +189/-7; tests +315/-0; docs +32/-0 Growth covers typed timing, existing-owner forwarding and distinct transport, lifecycle and redaction contracts without adding another connection-policy owner.

Labels

Label changes:

  • add P2: This is a bounded setup-diagnostics improvement without a demonstrated urgent regression or a claim to repair the underlying startup delay.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a bounded setup-diagnostics improvement without a demonstrated urgent regression or a claim to repair the underlying startup delay.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Provide a current-head native setup transcript showing phase entries reaching the existing JSONL log, with private details redacted.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 29, 2026, 6:10 PM ET / 22:10 UTC.

@karkarl
karkarl added this pull request to stack #1928 October 29, 2026 22:18
@karkarl
karkarl force-pushed the karkarl-gateway-handshake-diagnostics branch from edecc1b to c34f520 Compare November 4, 2026 17:17
@karkarl
karkarl force-pushed the karkarl-gateway-handshake-diagnostics branch from c34f520 to 48b6200 Compare November 4, 2026 18:15
@karkarl
karkarl marked this pull request as ready for review November 4, 2026 20:58
Base automatically changed from karkarl-startup-rejection-handling to main November 4, 2026 21:50
karkarl and others added 5 commits November 4, 2026 13:50
Keep client attempt ordinals unique across replacement native setup sessions. Classify observed transport failures without scanning exception stack frames, leaving existing failure policy unchanged. Cover both regressions and document the page-owned file sink boundary.

Co-authored-by: Copilot App <[email protected]>
Use the setup host's current logger parameter and describe window-owned sink lifetime after the lower stack's main rebase. No UI, logging lifetime or handshake policy changes.

Co-authored-by: Copilot App <[email protected]>
Cover the upstream-added keepalive cancellation path with the same current-generation disconnect observation as adjacent transport loss paths. Extend the existing real-socket ping timeout test to protect generation and ordering without changing recovery or timing policy.

Co-authored-by: Copilot App <[email protected]>
@karkarl
karkarl force-pushed the karkarl-gateway-handshake-diagnostics branch from 48b6200 to 2d1ac2b Compare November 4, 2026 21:50
@karkarl
karkarl merged commit c43b7e9 into main Nov 4, 2026
44 of 46 checks passed
@karkarl
karkarl deleted the karkarl-gateway-handshake-diagnostics branch November 4, 2026 22:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant