Skip to content

fix(gateway): avoid redundant presence and equivalent-policy disconnects - #177254

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-presence-churn-and-policy-disconnects-20260919
Oct 19, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-presence-churn-and-policy-disconnects-20260919

Conversation

@steipete

@steipete steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes unnecessary presence traffic when a chat pane is replaced with another owner of the same watched session, and false policy disconnects when an identity grant is rewritten with equivalent implied scopes.

User Impact

Viewer presence remains stable through same-turn pane replacement, and equivalent scope edits keep existing connections and accepted work alive. Real viewer changes and grant revocations retain their current behavior. Native clients retain their full-snapshot protocol.

Why This Change Was Made

The viewer owner cleared its last subscription synchronously but scheduled additions, producing an empty declaration followed by the unchanged set. Both now use the existing lifecycle scheduler; detachment waits for the empty declaration's acknowledgment.

Policy generation compared scope spellings rather than effective grants. Identity grant comparison and operator proxy caps now share the existing permission-implication owner, so equivalent grants agree at admission and reload. Stored authority fingerprints and all non-grant policy facts are preserved. Identity elevation auditing records the final admitted scopes after all caps.

Evidence

Acceptance rule, written before the measurement: synthetic real Gateway, 42 connected operators including 2 legacy readers, 20 same-turn pane replacements at 1-second intervals, then a real viewer change and departure. Compare two concurrent A/B pairs with core halves swapped; count viewer RPCs, presence frames and UTF-8 bytes, and retain both positive-control publications. A win removes unchanged-viewer RPCs and frames while real changes still reach both reader formats. Record CPU/RSS as contextual measurements, not startup or full application performance claims.

Focused regressions were red on the original code: same-turn viewer replacement sent three requests instead of one, and four implication-equivalent grant edits incorrectly invalidated the policy. All 45 focused tests now pass across session-viewer-presence.test.ts, ws-origin-policy.test.ts, and server-reload-handlers.identity-scopes.test.ts. Reload integration covers retained accepted work followed by real scope, allowlist, and origin revocations. Nine additional focused admission, audit, and persistent-device-cap cases pass. The new real-Gateway cap regression was red on the original literal intersection: write-only grants under a read cap admitted no scopes. It now admits read, rejects writes, and preserves empty/disjoint caps. Changed-file lint/format pass; pnpm tsgo:core (native checker) passed on the initial repair. Independent Codex autoreview covered the complete revision; all actionable findings are addressed. The audit test still passes after extracting its fixture/assertions into existing test support. Export-name collision checks and all 22 focused import-closure checks pass.

Two concurrent A/B pairs passed under the exclusive measurement lock, with CPU halves swapped for pair 2. Both sides used identical Gateway source and dependencies; only the viewer owner differed. Startup was excluded, and outside CPU load was recorded throughout each measured window.

Same 20 pane replacements, 42 readers Baseline (each pair) Candidate (each pair)
Viewer RPCs 40 0
Presence frames 840 0
Raw JSON bytes 6,901,000 0
Frames/min 2,518.67 / 2,518.49 0 / 0
Raw bytes/min 20,692,092 / 20,690,630 0 / 0

Paired B-minus-A differences are -2,518.67 and -2,518.49 frames/min, and -20,692,092 and -20,690,630 raw bytes/min. Every run retained all 84 positive-control frames: a real session change and departure reached all 40 delta and 2 legacy readers. Combined server/client CPU differences were -334.8 ms and -354.6 ms; RSS differences were +2.7 MB and -81.8 MB, so no memory claim. These are uncompressed event bytes, not compressed wire bytes or a forecast for total production traffic. No Testbox lease allocated; broad validation belongs to PR CI.

Production source delta: +42 lines (+52 for preserving stored authority fingerprints during semantic comparison, -2 for viewer lifecycle simplification, -8 for a single final scope calculation). The added standalone benchmark is 259 lines; documentation and tests are excluded from that source count. No schema, protocol, or configuration changes. Native readers still receive compatible full snapshots for real changes; this removes redundant publications, without truncating their roster. The reproduced lifecycle explains one avoidable traffic source, not all observed production activity.

CI identified two type-only repairs: importing the full browser application interface pulled JSX into the benchmark scripts typecheck, and the extracted audit fixture supplied an optional scope-cap value to a string-only headers map. The benchmark now uses its concrete transport adapter and protocol types; the fixture omits an absent header while preserving an explicit empty cap. The focused audit regression passed again (733 ms test time; 27.1 s including worker preparation), and independent review of the one-line fixture repair is clean. Production code and measured workload are unchanged by these repairs.

CI also caught a chat-page assertion that assumed one microtask was enough for both bridge disposal and the newly scheduled viewer clear. It reproduced locally; the test now uses its existing page-settlement helper and retains the exact empty-declaration assertion. All 31 tests in chat-page.test.ts pass (1.76 s Vitest duration, 2.78 s wrapper wall time). Independent review of this test-only correction is clean.

Final validation: all 70 checks passed on 4cbfd4cd14d08fc863d44ee51e96f4a078335efd, including all three PostgreSQL conformance shards, UI/E2E, production and test type checks, security checks, and the required CI gate. CI run. Squash-merged as 4a74bc62b4c1ea81a182ae87e20ee1b4c48c0459; verified on main. No CI reruns or inherited-failure exception were needed.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@steipete
steipete marked this pull request as ready for review October 19, 2026 10:28
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T10:58:37.018721Z 4cbfd4c New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts size: M labels Oct 19, 2026
@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 4cbfd4cd14d08fc863d44ee51e96f4a078335efd
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/auth-policy.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/connect-admission.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/connect-auth.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/connect-device-pairing.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/connect-session.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cb7b4a5a0f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/gateway/auth-policy.ts Resolved
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@steipete
steipete force-pushed the steipete/perf-micro-presence-churn-and-policy-disconnects-20260919 branch from cb7b4a5 to d279214 Compare October 19, 2026 10:43
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated head d27921413c8eb36f78ed5e2eb9857fb7d77f08fe addresses the proxy-cap finding and the benchmark type-import CI failure. The PR body now includes both paired measurements, retained positive controls, focused validation, and the production-code tradeoff.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR coalesces unchanged viewer declarations and preserves connections across permission-equivalent identity-grant edits.

Example: Replace a chat pane watching agent:main:visible with another owner of the same session during one browser turn.

  • Before: Presence sends an empty declaration followed by the unchanged session set.
  • After: The unchanged viewer set produces no additional declaration.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused repair has useful transport measurements and final-effect authority coverage; supplied execution is centered on an in-process Gateway and production-path harness.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): The supplied real-Gateway WebSocket workload exercises the changed viewer owner with legacy and delta readers; the reported passing production-path authority harness permits accepted native execution after equivalent edits and rejects delegated execution before filesystem I/O after revocation and restoration. This maintainer-authored PR satisfies the authority-specific proof requirement without an additional ordinary contributor proof gate.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Replacing an unchanged viewer produces redundant presence traffic, and permission-equivalent identity edits unnecessarily disconnect clients and revoke accepted work.
Reason: The maintainer-authored direction addresses demonstrated waste and false revocation while retaining real viewer changes and permission boundaries.

Merge readiness

✅ Ready for maintainer review

This maintainer-owned PR remains useful. The revised head addresses the earlier proxy-cap finding, and I found no additional actionable defect; exact-head CI is still pending.

Priority: P2
Reviewed head: d27921413c8eb36f78ed5e2eb9857fb7d77f08fe

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Control UI declares watched sessions over Gateway WebSockets; Gateway admission and reload policy resolve identity grants, apply permission ceilings, and retain or revoke connection and accepted-work authority.

flowchart TD
  A[Chat pane owners] --> B[Viewer declaration lifecycle]
  B --> C[Gateway WebSocket]
  D[Identity grants and proxy caps] --> E[Shared permission rules]
  E --> C
  C --> F[Presence readers]
  E --> G[Accepted work authority]
Loading

Technical review

Best possible solution:

Retain the existing lifecycle and permission owners, preserving acknowledgment-driven departure, compatible stored fingerprints, and revocation before effects.

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

The base synchronously clears the last viewer before scheduling its replacement and compares literal grant fingerprints; supplied measurements and reported red-before regressions match both source paths.

Is this the best way to solve the issue?

The repair uses the existing scheduler and shared permission-implication functions, with narrowly justified comparison logic to retain stored fingerprint compatibility.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +42, Tests +149, Docs +41, Other +259. Total +491 across 19 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 82 40 +42
Tests 7 184 35 +149
Docs 5 43 2 +41
Config 0 0 0 0
Generated 0 0 0 0
Other 1 259 0 +259
Total 19 568 77 +491

Review metrics

Metric Value Why it matters
Runtime versus regression coverage Runtime +82/-40 lines; tests and test support +184/-35 lines. Runtime growth principally preserves stored fingerprint compatibility; regression coverage addresses acknowledgment ordering, semantic grants, permission ceilings, persistent approval, and final-scope auditing.

Labels

Label changes:

  • add P2: The repair removes avoidable presence fan-out and false policy disconnects without evidence of an urgent widespread outage.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • 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: The repair removes avoidable presence fan-out and false policy disconnects without evidence of an urgent widespread outage.
  • 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.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 19, 2026, 6:49 AM ET / 10:49 UTC.

Coalesce same-turn viewer owner replacement through the existing lifecycle scheduler, retaining acknowledgment-driven departure. Compare identity grant implications without changing persisted authority fingerprints, so equivalent scope edits preserve connections and accepted runs while real revocations still apply.
Use the shared operator permission intersection for admission and device approval caps, and compute identity elevation from final admitted scopes. Preserve literal node caps and prove empty/disjoint caps and persistent narrowed device grants. Keep the synthetic presence benchmark type graph independent of browser application JSX.
@steipete
steipete force-pushed the steipete/perf-micro-presence-churn-and-policy-disconnects-20260919 branch from d279214 to 4cbfd4c Compare October 19, 2026 10:56
@steipete
steipete merged commit 4a74bc6 into main Oct 19, 2026
118 checks passed
@steipete
steipete deleted the steipete/perf-micro-presence-churn-and-policy-disconnects-20260919 branch October 19, 2026 11:22
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
…cts (openclaw#177254)

* fix(gateway): avoid redundant presence and equivalent-policy disconnects

Coalesce same-turn viewer owner replacement through the existing lifecycle scheduler, retaining acknowledgment-driven departure. Compare identity grant implications without changing persisted authority fingerprints, so equivalent scope edits preserve connections and accepted runs while real revocations still apply.

* fix(gateway): apply proxy caps consistently to equivalent grants

Use the shared operator permission intersection for admission and device approval caps, and compute identity elevation from final admitted scopes. Preserve literal node caps and prove empty/disjoint caps and persistent narrowed device grants. Keep the synthetic presence benchmark type graph independent of browser application JSX.

* test(gateway): omit absent proxy scope header in audit fixture

* test(ui): settle page disposal before checking viewer clear
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts security-sensitive-changed size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant