Skip to content

improve(gateway): reuse profile facts during client connections - #170228

Merged
steipete merged 2 commits into
mainfrom
dbasync/connect2
Oct 12, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/connect2

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Client connections reread profile authority from SQLite even when the Gateway already holds the current role, display, GitHub login, and aliases in its profile catalog. On the measured reconnect path, this duplicate authority preparation costs four SELECTs plus BEGIN/COMMIT and one worker request.

User Impact

Connections now reuse the profile writer's receipt-maintained catalog facts. The catalog remains the single owner; no new cache, worker, schema, or invalidation protocol is added. Full-profile requests and cold/standalone callers keep the worker operation because the resident projection does not contain the complete profile. Existing authority revocation and credential/authz checks remain in place.

The hello snapshot, presence, configuration, and subscription projections already use resident owners. This change removes the redundant profile lookup rather than moving its SQL to another thread. Scope is separate from the startup projection and reply-initialization work.

Removed Duplicate Read and Accepted Edge Case

  • Removed the worker authority reread after authenticated profile resolution when the profile catalog is resident. Accepted edge case: unsupported external database writers are not polled; Gateway-owned writes publish receipts and role/profile changes revoke existing authority.

No security check is removed. The regression exercises real worker commits for admin-to-member changes, display changes, and source-to-target merging; the next authority is fresh, the prior authority is revoked, and no extra worker read occurs. No retired alternate cache or synchronous fallback remains.

Measurement

One same-host baseline/candidate pair under the current campaign proof policy: baseline 24dec4d6c370c9ac1b8f1f534efc20e8b37dd27a, candidate 5d38fc0582d7ef4b638321a21379e1a08cfbc1b4. Remote Testbox run. The measured patch is unchanged in final head b04e6cf6edf1f99f7ed647978801c833f896b4e9, which mechanically merges main a3bbfaab02b265775f443b4d5fd4029525bd1b65 to pick up unrelated export-scan fixes. Exact remote Git identities and harness hashes match; Node 24.21.0 / SQLite 3.53.4. Pre-run CPU idle was 99.25% for both revisions.

The task-local copy of shared harness v2 preserves all 13 original turns and adds 20 signed Control UI connections using one installation identity. Samples 2–20 measure retained-identity connections; sample 1 is separate. Causal instrumentation counts successful native executions across all threads, excludes prepares, and attributes admission to its originating operation. All SQL attributed to the 20 measured Control UI connections executed before snapshot receipt; none occurred afterward. All turns, child execution, cron, compaction, shutdown, and connections passed. The initial fixture omitted the required Control UI build ID; that failed run was discarded, then both revisions used the build ID advertised by the initial hello.

Connect → first snapshot, retained identity (19 samples) Baseline Candidate Change
SQL median [min–max] 15 [15–19] 9 [9–13] −40% median
SQL mean 15.211 9.211 −6 / −39.4%
Worker requests median [min–max] 4 [4–4] 3 [3–3] −25%
MAIN statements 0 0 unchanged
Latency p50 19.581 ms 21.128 ms +7.9%
Latency p95 52.153 ms 47.694 ms −8.5%

The SQL target is met at the median; the −30% latency target is not met. This pair demonstrates a deterministic SQL/request saving, not a reliable latency improvement. The first UI sample was 19→13 statements, 4→3 requests, 61.060→93.885 ms; those single latency samples are not a distribution. These are instrumented loopback auth=none connections with signed device identities, not browser-render or production token/Tailscale measurements. Owner attribution covers SQL/requests; wall time is measured for the entire connect-to-snapshot boundary.

Owner, mean per retained connect SQL baseline → candidate Requests baseline → candidate
Pairing/auth 5.211 → 5.211 2 → 2
Profile catalog 10 → 4 2 → 1
Session list/snapshot 0 → 0 0 → 0
Agents/catalog/config 0 → 0 0 → 0
Presence 0 → 0 0 → 0
Subscriptions 0 → 0 0 → 0

Zeros indicate no connect-caused SQL/worker request, not absence of in-memory work.

Warmed turns, causal median [min–max] (10 turns per revision) Baseline Candidate
All-thread statements 201 [201–201] 201 [201–201]
Worker requests 45 [45–45] 45 [45–45]
MAIN statements 0 [0–0] 0 [0–0]

Legacy warmed-window means were 214.2→213.7 statements and 55.4→55.3 requests. Whole-workload totals, including boot and background work, were 6,966→6,831 statements, 1,300→1,283 requests, and MAIN 838→838. The profile authority operation saves exactly six statements and one request per connection; background scheduling is not credited as a product saving.

Shared read family, causal statements / warmed turn Baseline Candidate
Exact-entry facts 4 4
Actor hydration 2 2
Entry-cache snapshot loads 0 0
Row facts 0 0
Watermark reads 6 6

The corresponding distinct attached worker-request counts are 4, 2, 0, 0, 5 on both revisions (non-additive across families). Whole-workload family counts also do not rise: exact-entry 65→64, actor 36→36, snapshot 7→7, row facts 6→6, watermark 129→129. Stable SQL aliases/direct execution frames identify each family; no broad worker-operation name is substituted for a query family.

Proof and Scope

  • Local changed-file oxfmt/oxlint and git diff --check: passed.
  • Two isolated Codex autoreview rounds: clean, no actionable findings.
  • Implementation-head PR CI: passed, including production/test types, type-aware core lint, source/export-collision contracts, changed tests, Madge (zero cycles), and T1/dialect ratchets.
  • Changed test file: 9 tests passed; Vitest duration 8.41s, harness wall 10.54s. New regression: 794ms.
  • T1 call expressions in the touched production owner: 0→0. Repository T1 ratchet: 471→471; compatibility tier: 9→9. The removed operation was already off-thread.
  • Merged-head CI: passed, all 62 jobs completed without failures. Merged-head Knip matches the independently reproduced main failure exactly: script and production scans pass; full-tree scan has the three inherited UI-fixture exports below. Main a3bbfaab02b265775f443b4d5fd4029525bd1b65 independently passes script/production Knip scans; its full-tree scan flags only TEAM_SCALE_CATALOG_PROGRESS_ID, TEAM_SCALE_COUNTS, and TeamScaleEvent in untouched ui/src/test-helpers/control-ui-team-scale-fixture.ts.
  • No update/Doctor/migration/schema/plugin-loading/service-lifecycle or SDK contract changes; update cell and SDK surface diff do not apply.
  • Diff: +74/−2 lines total; production +24/−2, regression +45, docs +5. No changelog edit; release-note context is this PR.

@clawsweeper

clawsweeper Bot commented Oct 12, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR reuses committed profile catalog facts during authority preparation instead of issuing another worker read.

Example: [email protected] reconnects with role admin while the Gateway profile catalog is resident.

  • Before: Authority preparation queries the shared-state worker for profile facts already held by the Gateway.
  • After: Preparation reads those facts from the existing catalog and retains the existing authority-revocation check.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The patch is focused and source-consistent, but required authority-boundary evidence is absent; no stored format or migration changes are introduced.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Client connections perform an unnecessary worker request before profile acquisition completes.
Reason: The narrow optimization follows established feature-owner direction and adds no configuration, schema, or public API.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: this PR provides a focused connection-path optimization that current main does not implement; no concrete introduced defect was found.

Priority: P2
Reviewed head: 5d38fc0582d7ef4b638321a21379e1a08cfbc1b4

Before merge

  • Add real behavior proof - Authority-chain proof required: Exercise authenticated Gateway connection with a resident catalog, show an administrator-only mutation succeeds, and show a member cannot perform it and demotion or profile merge during awaited work prevents its commit. Supply redacted terminal output or logs identifying the candidate and showing the optimized connection avoids the authority worker read; redact IPs, API keys, phone numbers, and non-public endpoints. The supplied regression stops at prepared facts and isCurrent, and the body and discussion provide no recorded final-effect run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve security review attention item - No concrete bypass was found, but the changed authority source requires final-effect validation.
  • Resolve merge risk - Before merge, validate that the new resident authority source cannot retain privileged access for a member or a demoted or merged former administrator at the final effect boundary.

Findings

None.

Tests

  • Missing end-to-end proof: Missing a recorded resident-catalog Gateway connection with allowed, forbidden, and revoked privileged effects; no base-fails/head-passes execution of the added regression is supplied.
Agent review details

How this fits together

The profile owner publishes committed identity, role, login, alias, and display facts; Gateway authentication and session-access consumers prepare those facts and check their authority before use.

flowchart TD
  A[Profile mutations] --> B[Shared state writer]
  B --> C[Committed profile catalog]
  C --> D[Authority preparation]
  E[Standalone or full profile worker read] --> D
  D --> F[Live authority checks]
  F --> G[Gateway connection and privileged effects]
Loading

Technical review

Best possible solution:

Reuse the committed catalog under the existing authority fence, retaining worker reads for full profiles and standalone callers.

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

Current main unconditionally dispatches the authority worker read even when the profile catalog is resident; the redundant request is source-verifiable, but no runtime measurement was run during this review.

Is this the best way to solve the issue?

The change fits the existing owner and preserves fallback and revision checks, avoiding another cache or freshness mechanism.

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Hold merge for targeted authority evidence (recommended)
    Keep the PR open until the resident-catalog path demonstrates allowed administrator work and rejection of forbidden or revoked authority before the privileged effect.

Provenance checked

  • Profile authority preparation keeps the original intent (c69b8b9: Verified profile facts were qualified against the physical profile owner's mutation lifetime before privileged use.)
  • Resident role-policy facts keeps the original intent (bc1d2b9: Reuse the retained canonical profile catalog while preserving the authority fence and standalone worker fallback.)
  • Connection worker-access documentation keeps the original intent (1509b04: Reduce redundant connection reads while preserving authentication and visibility checks.)

Testing

Proof path: in-process harness.

Security

Needs attention: No concrete bypass was found, but the changed authority source requires final-effect validation.

Evidence

What I checked:

PR surface

Source +22, Tests +45, Docs +5. Total +72 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 24 2 +22
Tests 1 45 0 +45
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 74 2 +72

Review metrics

Metric Value Why it matters
Production versus regression LOC Production +24/−2; tests +45 The production growth implements reuse within the existing owner; the regression covers committed fact replacement and authority invalidation.

Labels

Label changes:

  • add P2: This is a bounded connection-performance improvement with no established urgent user-facing failure.
  • add merge-risk: 🚨 security-boundary: The patch substitutes resident role and login facts on authentication and session-authority paths; preparation assertions do not establish rejection at a final privileged effect.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: This is a bounded connection-performance improvement with no established urgent user-facing failure.
  • merge-risk: 🚨 security-boundary: The patch substitutes resident role and login facts on authentication and session-authority paths; preparation assertions do not establish rejection at a final privileged effect.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Add final-effect proof that a member cannot perform the administrator-only mutation and that demotion or profile merge during awaited work prevents its commit.

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 12, 2026, 4:47 PM ET / 20:47 UTC.

@steipete
steipete merged commit 655d575 into main Oct 12, 2026
132 of 136 checks passed
@steipete
steipete deleted the dbasync/connect2 branch October 12, 2026 21:46
steipete added a commit that referenced this pull request Oct 12, 2026
Two tests still encode contracts that changed on main. The resident profile authority path added by #170228 consumes aliases and display facts that the personal-file mock does not provide; seven cases fail before exercising their intended behavior. The fallback notice added by #169773 is a stopped assistant message, so the cron test incorrectly counts the notice as a second answer.

Complete the personal-file mock using the existing `UserProfileIdentity` and `UserProfileDisplay` types. In the cron test, assert one primary-to-backup timeout notice through `readModelFallbackNotice`, then count successful assistant answers separately. Preserve the original requester, revocation, filesystem, one-user-turn, provider-order, and successful-result assertions. Production code and authority checks are unchanged.

Cached failure evidence:

- Personal-file mock: [Bun job 115027766429](https://github.com/openclaw/openclaw/actions/runs/38313840692/job/115027766429), `profile.aliases` spread failure.
- Cron transcript: scheduled-main [run 38317311743, job 115037168335](https://github.com/openclaw/openclaw/actions/runs/38317311743/job/115037168335), expected one stopped assistant message, received two. The same signature appeared in prior candidate CI.

Source and history were checked against main `395ea60dea893feb48782c0ac5fd4fc5a148a42a`. The profile failure is a prior candidate observation; the cron failure is reproduced by the cited scheduled-main run. Changed-file formatting, basic lint, and whitespace checks passed. One isolated Codex review completed scoped-clean with no actionable P0–P2 findings; both changed tests passed in PR CI [38318717235](https://github.com/openclaw/openclaw/actions/runs/38318717235), testing merge `634ae26bddea49d922f784c57805b11db5159773` (candidate `d171a04362e17b99fae68e59f1e593f2b173edf2` into base `f307d643`). The run finished green: 20 successful and 29 skipped jobs. Selected lint, test types, baseline ratchets, source contracts, boundaries, guards, and the CI gate passed:

```sh
pnpm test src/gateway/server-methods/users-personal-file.test.ts --maxWorkers=1
pnpm test src/cron/isolated-agent/run.fallback-transcript.test.ts --maxWorkers=1
```

Test-only change: two files, +31/−3. One commit per root cause.

CI executed all 42 personal-file cases (26.40s Vitest, 28.34s wrapper) and the cron fallback case (15.580s case, 29.67s Vitest, 31.20s wrapper). No local runtime timing is claimed.

Standalone Knip and Madge jobs were not selected for this test-only PR; no fresh whole-tree graph pass is claimed. The bounded source disposition reuses the prior clean topology and unaffected production/export scans: these two test leaves add no exports or production edges. The only value import added is the existing leaf `readModelFallbackNotice`, whose sole dependency is the existing normalization-core record coercer. Other added imports are erased types from an already-imported module. The historical full-tree unused-file findings concern the unrelated executable roots repaired separately in #170347.

Before landing, source checks against main `81ad3bf71935d80c60a8b4a34492e51630d883c3` found no changes to either repaired test or the imported fallback-notice helper. No SDK, schema, update, Doctor, plugin-loading or service-lifecycle change; no SQL/T1 performance claim. Direct-main publication previously hit repository protection, so this emergency repair uses the authorized exact-head PR squash fallback.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…penclaw#170228)

Reuse the receipt-maintained profile catalog when preparing connection authority. Keep cold/full-profile worker reads and existing authority revocation and authorization checks.

Retained Control UI connections use 15 -> 9 SQL statements and 4 -> 3 worker requests. Warmed-turn statements, requests, and main-thread SQL are unchanged; no latency improvement is established.

Cover committed role/display updates and profile merges with a regression. Two Codex review rounds are clean; merged-head CI passes. Knip has only the independently reproduced unused UI-fixture exports already present on main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…law#170355)

Two tests still encode contracts that changed on main. The resident profile authority path added by openclaw#170228 consumes aliases and display facts that the personal-file mock does not provide; seven cases fail before exercising their intended behavior. The fallback notice added by openclaw#169773 is a stopped assistant message, so the cron test incorrectly counts the notice as a second answer.

Complete the personal-file mock using the existing `UserProfileIdentity` and `UserProfileDisplay` types. In the cron test, assert one primary-to-backup timeout notice through `readModelFallbackNotice`, then count successful assistant answers separately. Preserve the original requester, revocation, filesystem, one-user-turn, provider-order, and successful-result assertions. Production code and authority checks are unchanged.

Cached failure evidence:

- Personal-file mock: [Bun job 115027766429](https://github.com/openclaw/openclaw/actions/runs/38313840692/job/115027766429), `profile.aliases` spread failure.
- Cron transcript: scheduled-main [run 38317311743, job 115037168335](https://github.com/openclaw/openclaw/actions/runs/38317311743/job/115037168335), expected one stopped assistant message, received two. The same signature appeared in prior candidate CI.

Source and history were checked against main `3dd81bae92980aecaf0920bbad841c10486dea75`. The profile failure is a prior candidate observation; the cron failure is reproduced by the cited scheduled-main run. Changed-file formatting, basic lint, and whitespace checks passed. One isolated Codex review completed scoped-clean with no actionable P0–P2 findings; both changed tests passed in PR CI [38318717235](https://github.com/openclaw/openclaw/actions/runs/38318717235), testing merge `634ae26bddea49d922f784c57805b11db5159773` (candidate `d171a04362e17b99fae68e59f1e593f2b173edf2` into base `68ba0b0a`). The run finished green: 20 successful and 29 skipped jobs. Selected lint, test types, baseline ratchets, source contracts, boundaries, guards, and the CI gate passed:

```sh
pnpm test src/gateway/server-methods/users-personal-file.test.ts --maxWorkers=1
pnpm test src/cron/isolated-agent/run.fallback-transcript.test.ts --maxWorkers=1
```

Test-only change: two files, +31/−3. One commit per root cause.

CI executed all 42 personal-file cases (26.40s Vitest, 28.34s wrapper) and the cron fallback case (15.580s case, 29.67s Vitest, 31.20s wrapper). No local runtime timing is claimed.

Standalone Knip and Madge jobs were not selected for this test-only PR; no fresh whole-tree graph pass is claimed. The bounded source disposition reuses the prior clean topology and unaffected production/export scans: these two test leaves add no exports or production edges. The only value import added is the existing leaf `readModelFallbackNotice`, whose sole dependency is the existing normalization-core record coercer. Other added imports are erased types from an already-imported module. The historical full-tree unused-file findings concern the unrelated executable roots repaired separately in openclaw#170347.

Before landing, source checks against main `53575ccd561ef562d46ff259fc47b7f4582dc7dc` found no changes to either repaired test or the imported fallback-notice helper. No SDK, schema, update, Doctor, plugin-loading or service-lifecycle change; no SQL/T1 performance claim. Direct-main publication previously hit repository protection, so this emergency repair uses the authorized exact-head PR squash fallback.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant