Skip to content

perf(gateway): serve profile avatars without blocking SQLite reads - #158445

Merged
steipete merged 4 commits into
mainfrom
perf/l19-profile-avatar-reader
Sep 26, 2026
Merged

steipete merged 4 commits into
mainfrom
perf/l19-profile-avatar-reader

Conversation

@steipete

@steipete steipete commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Concurrent Control UI profile-avatar requests synchronously read and copy SQLite BLOBs on the Gateway thread, even for HEAD and unchanged responses.

User Impact

Saved-avatar reads run in the existing shared-state read worker. HEAD and 304 responses fetch no image bytes, and overlapping requests share unsettled reads. Avatar bytes, MIME types, ETags, merge behavior, authentication, and cache headers remain unchanged. There is no new configuration, public protocol, SQLite schema, or update migration.

Why This Change Was Made

The avatar owner prepares merge-aware metadata before requesting bytes, retains the selected physical database through refreshes, and checks the original alias and representation again when materializing an image. The existing profile publication revision fences local catalog changes; worker reads continue to observe foreign commits. Tailscale inspection shares the metadata query. The synchronous getter and duplicate inspection are removed.

A first worker-only cutover overloaded the existing 128-task reader limit during the 300-request proof. Pending-only coalescing fixes that failure without raising the limit or retaining completed avatar results. Explicit database/environment and maintenance/schema scopes keep their own admission. Current request authorization is checked after asynchronous preparation and before publishing responses.

Evidence

Actual HTTP handler, three synthetic uploaded profiles, 300 simultaneous calls, seven warmed rounds, Node 26.9.0/macOS arm64:

512 KiB avatar Median burst before → after Event-loop sentinel before → after
HEAD 43.808 → 13.493 ms 43.903 → 3.849 ms
304 50.033 → 16.434 ms 50.066 → 4.096 ms
GET 40.974 → 12.155 ms 41.903 → 4.314 ms

All 12,600 measured responses passed status, ETag, Content-Length, and body-length checks. Every final burst performed zero main-thread SQLite/BLOB reads in the avatar path and exactly three worker inspections. HEAD/304 transferred zero avatar bytes. GET transferred 1.5 MiB from workers while delivering 150 MiB across 300 responses, instead of materializing 300 BLOBs on the main thread.

The same 32 KiB cases reduced sentinel delays from 19.4–25.0 ms to 3.7–6.2 ms. Small-image GET completion increased 19.374 → 26.661 ms. These are synthetic handler measurements on a heavily shared host, without network transport. A 19.05-second source-worker startup outlier is retained in the samples; warm medians are not cold-start or deployed-latency claims.

  • Initial focused validation: 165 tests passed, 746.55 s wall, covering the three avatar HTTP suites, profile lifetime/worker/admission suites, profile and multi-account persistence, and skill-library persistence.
  • After coalescing: 51 tests passed, 993.52 s wall, via node scripts/run-vitest.mjs src/gateway/user-profiles-http.test.ts src/gateway/user-profiles-http.auth.test.ts src/gateway/user-profiles-http.gravatar.test.ts src/state/user-profiles.avatar-lifetime.test.ts --maxWorkers=1.
  • Final fixture cleanup: 45 tests passed, 603.74 s wall, via node scripts/run-vitest.mjs src/gateway/user-profiles-http.test.ts src/gateway/user-profiles-http.auth.test.ts --maxWorkers=1. Isolated databases now share suite-lifetime workers. The 300-request regression took 1.917 s; replacement/merge races took 1.127/1.134 s. Worker compilation dominates these wall times. CI seconds are pending.
  • Tests cover no byte materialization for HEAD/304, overload, replacement/merge races, credential rotation during inspection/materialization, foreign commits, and original physical-owner retention.
  • The final local changed-lane gate was interrupted; hosted exact-head CI is the landing gate. The prior run passed production and all test typechecks, then flagged a native selector exported only for fixture reads. The selector is now private, and fixture reads use the production dispatch function. A direct fixture proof passed absent/empty/nonempty/merged reads in 10.41 s wall. The earlier line-cap failure was fixed by moving avatar dispatch into its domain owner.
  • Production LOC: +372/-67 (net +305). Tests/support: +297/-67 (net +230). Positive production growth is the typed worker contract, metadata-only selector, representation/owner fencing, and pending-read coalescing required by the reproduced burst failure. No unrelated deletion was used to offset it.
  • Deslop completed. Independent Codex branch review with lifecycle context is scoped-clean through P2, with no actionable findings.

Landing validation

Exact-head CI run 36206083575 found a type-import cycle: the shared read-worker contract imported avatar types through the database implementation. The run was cancelled after that failure, and its CI gate reflected the architecture failure. Commit 9a9a492c3e8473e5861d82476e0c7c7d70ea86da moves the contracts into the existing leaf type modules without changing runtime behavior.

  • node --import ./scripts/tsx.mjs scripts/check-madge-import-cycles.ts: 0 cycles, 120.36 s wall.
  • Core tsgo: passed, 45.52 s wall.
  • node scripts/run-vitest.mjs src/state/user-profiles.avatar-worker.test.ts: 17 passed, 1157.59 s total wall including source-worker compilation and cleanup; Vitest duration 644.54 s.
  • Formatting and git diff --check: passed. Independent Codex review of the repair: scoped-clean through P2, no actionable findings.
  • Earlier local proof attempts were interrupted while adjusting the candidate. The completed results above cover the final repair; hosted CI must pass on its exact published head before native landing.

Review disposition: shared reader saturation

ClawSweeper's latest review identifies a real capacity limit: concurrent requests for distinct profiles cannot share a pending read, so enough outstanding requests can reach the shared reader's 128-task admission bound and receive profile_lookup_failed HTTP 500. The reported burst proof covers coalescing across a small set of profiles; it does not establish success for arbitrary distinct-profile saturation.

For this requested as-is landing, the shared admission policy is retained and this limitation is recorded as a follow-up, rather than adding another queue owned by the avatar adapter. src/state/openclaw-state-read-worker.ts selects the shared task limit, and src/infra/worker-task-pool-core.ts deliberately rejects excess tasks; the worker-pool tests protect that capacity contract. Queueing or overload-response improvements should be addressed through those existing owners. This disposition does not claim that saturation is fixed or that a distinct-profile burst passed.

Main-merge validation

Native merge admission stopped before dispatch when advancing main introduced an import conflict in src/state/user-profiles-multi-account.test.ts. Merge commit 4fca52f4a968d4f37b5a35f3141e692deb9e176c incorporates main at 37259b7cab6b1816211d381200848048a05f197d and keeps both independent imports. The stable context-free patch ID before and after the merge is identical (10d2c4debf9cf97e4f0e88f1a228ac31baa177de), preserving the independently reviewed PR delta.

  • Focused HTTP-auth and multi-account suites: 24 tests passed, 262.63 s total wall.
  • Core tsgo: passed, 40.21 s wall.
  • Import-cycle check: 0 cycles, 82.11 s wall.
  • Exact-head CI is green on the merged head: run 36214101429, GitHub rollup SUCCESS with zero pending checks. The pre-merge repair also passed run 36209392042.

@clawsweeper

clawsweeper Bot commented Sep 25, 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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: L labels Sep 25, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 25, 2026
@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 25, 2026, 11:20 PM ET / September 26, 2026, 03:20 UTC (Revision 6).

ClawSweeper review

What this changes

Moves authenticated Control UI avatar reads to a shared SQLite worker, avoids fetching image bytes for HEAD and 304 responses, and shares pending reads for the same profile.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still has the synchronous avatar path, and this PR remains a distinct, coherent candidate. The earlier shared-reader capacity concern has an explicit as-is disposition in the PR discussion.

Priority: P2
Reviewed head: 4fca52f4a968d4f37b5a35f3141e692deb9e176c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The owner-level cutover has focused handler and authorization coverage, with measured performance evidence limited to synthetic traffic.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR reports running the changed production avatar handler with real SQLite read workers and synthetic uploaded profiles on Node 26.9/macOS arm64; 300-request bursts produced checked after-fix responses and lower warmed event-loop delay. The capture excludes network transport and cold-start claims. The diff changes read execution, not a stored-data contract.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR reports running the changed production avatar handler with real SQLite read workers and synthetic uploaded profiles on Node 26.9/macOS arm64; 300-request bursts produced checked after-fix responses and lower warmed event-loop delay. The capture excludes network transport and cold-start claims. The diff changes read execution, not a stored-data contract.
Evidence reviewed 9 items Current-main behavior: The current-main HTTP handler still calls the synchronous saved-avatar getter before responding; the central performance problem remains.
Introduced Gateway path: The handler awaits avatar inspection and, when needed, byte loading; it rechecks request authorization before sending the response.
Read-worker ownership: Metadata inspection selects length and identity without selecting avatar bytes; materialization checks the canonical profile, hash, and MIME before reading bytes.
Findings None None.
Security None None.

How this fits together

The Gateway serves profile images requested by Control UI browsers after checking read access. It reads saved avatars from OpenClaw's SQLite profile store and returns an image, a conditional response, or a host-photo or Gravatar fallback.

flowchart LR
A[Control UI image request] --> B[Gateway access check]
B --> C[Avatar reader]
C --> D[SQLite read worker]
D --> E{Saved avatar available?}
E -->|Yes| F[Image or conditional response]
E -->|No| G[Host photo or Gravatar]
G --> H[Image or not found]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +305, Tests +230. Total +535 across 21 files.

View PR surface stats
Area Files Added Removed Net
Source 11 372 67 +305
Tests 10 297 67 +230
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 21 669 134 +535

Review metrics

Metric Value Why it matters
Code growth production net +305, tests and support net +230 The PR body attributes production growth to worker contracts, metadata selection, and refresh checks needed for the changed path.

Technical review

Best possible solution:

Keep the off-thread avatar path and its authorization and representation checks; address sustained distinct-profile overload through the shared reader's capacity owner if demand warrants it.

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

Yes. Current main calls the synchronous full-avatar getter in the authenticated HTTP handler, and the PR gives a concrete concurrent-request benchmark; this read-only review did not rerun it.

Is this the best way to solve the issue?

Yes. The existing shared SQLite reader owns database work, while the Gateway retains authorization and HTTP response decisions; the PR adds no competing store or setting.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8ccd3f581c1e.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The change addresses bounded Gateway event-loop latency from concurrent avatar requests.
  • merge-risk: 🚨 availability: Distinct-profile bursts can still exhaust the shared reader's 128-task limit and return HTTP 500; the PR explicitly records this accepted limitation.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports running the changed production avatar handler with real SQLite read workers and synthetic uploaded profiles on Node 26.9/macOS arm64; 300-request bursts produced checked after-fix responses and lower warmed event-loop delay. The capture excludes network transport and cold-start claims. The diff changes read execution, not a stored-data contract.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports running the changed production avatar handler with real SQLite read workers and synthetic uploaded profiles on Node 26.9/macOS arm64; 300-request bursts produced checked after-fix responses and lower warmed event-loop delay. The capture excludes network transport and cold-start claims. The diff changes read execution, not a stored-data contract.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • RoboClaw: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (5 earlier review cycles)
  • reviewed 2026-09-25T23:52:28.231Z sha d26c483 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T00:22:25.105Z sha 1bb85ae :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T00:52:11.927Z sha 1bb85ae :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T01:52:18.762Z sha 9a9a492 :: blocked before merge. :: [P2] Bound avatar reads across distinct profiles
  • reviewed 2026-09-26T02:04:06.031Z sha 9a9a492 :: needs maintainer review before merge. :: none

@steipete
steipete marked this pull request as ready for review September 26, 2026 00:46
Break the type-import cycle between the shared read-worker contract and the profile database implementation. Preserve avatar runtime behavior and keep one leaf definition for the request, reply, and metadata types.
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 26, 2026
Retain both independent multi-account test imports and preserve the reviewed avatar delta. The stable context-free patch ID is unchanged; focused auth and multi-account tests, core types, and the cycle check pass on the merged candidate.
@steipete
steipete merged commit bbd40ab into main Sep 26, 2026
215 checks passed
@steipete
steipete deleted the perf/l19-profile-avatar-reader branch September 26, 2026 03:44
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
…penclaw#158445)

* perf(gateway): prepare profile avatars outside the main thread

* refactor(state): keep avatar byte selection private

* fix(state): keep avatar read contracts in leaf modules

Break the type-import cycle between the shared read-worker contract and the profile database implementation. Preserve avatar runtime behavior and keep one leaf definition for the request, reply, and metadata types.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

1 participant