Skip to content

improve(database): rebuild ported memory indexes concurrently - #185237

Merged
steipete merged 1 commit into
openclaw:mainfrom
etzelm:improve/port-memory-rebuild-parallel
Oct 27, 2026
Merged

steipete merged 1 commit into
openclaw:mainfrom
etzelm:improve/port-memory-rebuild-parallel

Conversation

@etzelm

@etzelm etzelm commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Related: #181859

What Problem This Solves

Moving an installation's agent databases to PostgreSQL keeps the Gateway down while every agent's memory index is rebuilt, one agent after another, so downtime grows with the total of all agents instead of the slowest one.

User Impact

User impact: operators running openclaw database port on a multi-agent installation get their Gateway back sooner, because memory indexes for up to four agents now rebuild at the same time when the host has the CPUs and free memory for it. Small hosts (two or fewer CPUs, or under 2 GiB free memory) keep the previous one-at-a-time behavior. Results, warnings, and the per-agent openclaw memory index --agent <id> retry guidance are unchanged, and one agent's failure still leaves the others rebuilt. The Gateway must still stay stopped until the command finishes.

On a real 11-agent installation, the data copy finished in about 6 minutes and the sequential rebuilds then took 5,738 s (96 min); the slowest single agent took 2,865 s (48 min). With this change that installation's rebuild step is bounded by roughly the slowest agent instead of the sum.

Why This Change Was Made

Each agent's memory index lives in its own store with its own reindex lock, and the rebuild added in #182008 already isolates failures per agent, but it ran the agents in a plain loop. This change runs that same per-agent body through the repository's bounded task runner. The width is measured from the host at run time: the existing compute worker sizing (CPU count minus one, at most four) further limited by free memory at 512 MiB per rebuild with half kept in reserve. Embedding requests per agent keep their existing in-agent limit and retry/backoff on retryable provider errors, so a remote rate-limited provider sees at most four agents' worth of requests.

Starting the Gateway before the rebuild finishes is not part of this change: the rebuild acquires fresh offline ownership (runWithLocalStateOwner with onForeignOwner: "refuse"), so a running Gateway would make it refuse. Changing that ownership model is a larger design decision.

Evidence

  • Focused tests (node scripts/run-vitest.mjs): a new scheduling test shows three rebuilds in flight at once with one agent failing and the other three rebuilt; each fake rebuild waits, with no timer, until three have started, so a one-at-a-time scheduler (as on main) never releases them and fails by the test timeout. A second test shows a host limit of one keeps rebuilds strictly sequential. Sizing tests (doctor-database-port-memory-concurrency.test.ts) cover 1 CPU, 2 CPUs, no free memory, 2 GiB, and a large host. All 6 port-memory tests, 5 sizing tests, and the existing doctor-database-port.test.ts pass.
  • PR wrapper source closure: test/scripts/pr-wrapper-source-closure.test.ts, test/scripts/eager-import-closure.test.ts (27/27) and test/scripts/pr-worktree-provision.test.ts pass with the sizing helper kept beside its consumer, leaving the trusted-anchor wrapper inventory unchanged. One provisioner case (materializes full cold/warm PR siblings, then preserves native sparse transitions) times out at 120 s on the test host, and does the same on main with no diff.
  • PostgreSQL conformance agent-port.postgres.test.ts (consumer of the rebuild results) passes against a local PostgreSQL 17.11: 9/9.
  • End-to-end timed run on macOS (32 CPUs): a synthetic 11-agent installation with memory volume proportional to the production timings, real openclaw database port --family agent --to postgres from built dist, local PostgreSQL 17, and an OpenAI-compatible embedding stub answering each request after 2 s. The embedding model changed between seeding and the port so every chunk was re-embedded (287 requests in both runs).
Run Whole port wall time Peak embedding requests in flight Agents rebuilt
Before (main 3b3efe9) 216.5 s 4 11/11
After (this branch) 118.7 s 16 11/11

The slowest agent took 76.5 s in both runs, which is the floor for the rebuild step. Small agents took slightly longer each when sharing the host (for example 2.5 s to 4.8 s), with no failures.

  • pnpm changed:lanes --json: core, core tests, docs. pnpm check:changed: typecheck core and core tests, lint, format, mock-export ratchet, and the other guards pass. Two checks fail identically on main in files this change does not touch (deprecated API usage in extensions/codex/harness.ts:261, and the Knip unused-export scan). git diff --check is clean.
Technical detail
  • src/commands/doctor-database-port-memory.ts: the per-target loop body becomes a rebuild(target) function that returns its result instead of pushing and continuing, and runTasksWithConcurrency runs it in continue-on-error mode. Results stay in target order. A defensive fallback maps any slot left empty by an unexpected throw to that agent's existing failure result with recovery guidance.
  • src/commands/doctor-database-port-memory-concurrency.ts: resolveMemoryRebuildConcurrency() returns max(1, min(resolveWorkerPoolSize("compute"), floor(readHostFreeMemoryBytes() / 2 / 512 MiB))). It is measured once per port. It lives beside its only consumer rather than in src/infra/worker-pool-sizing.ts, which belongs to the PR wrapper inventory (scripts/pr-lib/wrapper-components.txt) that the closure tests keep closed over its relative imports.
  • Ordering: targets keep their discovery order. If the largest agent happens to be scheduled late, the rebuild step can exceed the slowest agent by up to the other lanes' remaining work. Longest-first ordering would need a size estimate before opening stores and is left out.
  • Docs: docs/gateway/postgresql.md and docs/reference/database-engines.md describe the concurrent rebuild, the small-host fallback, and that the rebuild stays offline.
  • Update behavior: no config, schema, or state format change. The port command already in an installation keeps its behavior; the candidate's port command is the one that rebuilds concurrently.

@clawsweeper

clawsweeper Bot commented Oct 27, 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 docs Improvements or additions to documentation gateway Gateway runtime commands Command implementations size: S labels Oct 27, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Rebuilds ported agents’ memory indexes concurrently, with fanout bounded by host CPU capacity and free memory.

Example: Port 11 agents to PostgreSQL on a 32-CPU Mac using a delayed local embedding endpoint.

  • Before: The reported built-CLI run took 216.5 seconds, with four embedding requests in flight.
  • After: The reported run took 118.7 seconds, with 16 requests in flight; all 11 agents rebuilt with the same 287 total requests.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused, and supported by shipped-CLI results and passing exact-head gates; the timing evidence supports the tested workload rather than a general performance guarantee.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied macOS built-CLI comparison exercises the changed post-port rebuild owner against PostgreSQL 17 with 11 agents and a delayed embedding endpoint, showing successful concurrent rebuilding and shorter completion with equal request totals.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Operators keep the Gateway stopped while independent agents’ memory indexes rebuild one after another.
Reason: The supplied workload shows substantially shorter whole-command downtime with unchanged embedding work, while existing ownership and recovery behavior remain intact.

Merge readiness

✅ Ready for maintainer review

This PR provides a focused, supported reduction in database-port downtime that current main still lacks; no actionable defects remain.

Priority: P2
Reviewed head: 5956e4ea67b3e91e111b8bc491757c3c71995da9

Before merge

None.

Findings

None.

Agent review details

How this fits together

After database publication releases port custody, the command acquires offline memory ownership, rebuilds the ported agents through the selected memory plugin, and returns ordered results and recovery warnings.

flowchart TD
A[Database port command] --> B[Publish agent stores]
B --> C[Acquire offline memory ownership]
C --> D[Resource bounded scheduler]
D --> E[Selected memory plugin]
E --> F[Agent memory indexes]
E --> G[Ordered results and warnings]
Loading

Technical review

Best possible solution:

Use the existing bounded scheduler within the existing offline owner, preserving per-agent cleanup, ordered results, and recovery guidance.

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

Current main visibly awaits agent rebuilds sequentially, and the supplied built-CLI comparison demonstrates the resulting multi-agent downtime.

Is this the best way to solve the issue?

The smallest complete improvement is bounded scheduling around the existing per-agent operation; this patch does that without adding another state owner or changing persisted contracts.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Offline post-port memory rebuilding keeps the original intent (215cb73: Rebuild before agent ports return, preserve reusable embeddings, and isolate failures under fresh offline ownership.)
  • Post-rebuild planner statistics keeps the original intent (660b252: Refresh PostgreSQL statistics after each memory manager finishes and closes, retaining successful data publication when statistics refresh fails.)
  • Command test structure keeps the original intent (d754f7c: Remove duplicate test layers while retaining owner-boundary assertions; the added scheduling cases cover distinct concurrent and sequential limits.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 215cb73 adds src/commands/doctor-database-port-memory.ts:72 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 215cb73bea18; files: src/commands/doctor-database-port-memory.ts)

PR surface

Source +17, Tests +120, Docs +5. Total +142 across 6 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 33 16 +17
Tests 2 120 0 +120
Docs 2 8 3 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 161 19 +142

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Reduces offline maintenance downtime for multi-agent installations without changing ordinary Gateway operation.
  • 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.
  • 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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-27T00:36:03.084Z sha b3f72cc08eb961544fef5cc498bd41b5462a6a6b :: blocked before merge. :: [P1] Include the new dependency in the trusted wrapper inventory | [P3] Replace the overlap test's real-time deadline with controlled release
  • reviewed 2026-10-27T01:14:27.149Z sha 4a75ef2ef9c6d7fe9464d39cc74629dc3ab942a6 :: blocked before merge. :: [P3] Replace the overlap test's real-time deadline with controlled release
  • reviewed 2026-10-27T01:36:14.659Z sha 5956e4e :: needs maintainer review before merge. :: none

Reviewed October 27, 2026, 3:43 PM ET / 19:43 UTC (Revision 4).

@etzelm
etzelm force-pushed the improve/port-memory-rebuild-parallel branch from b3f72cc to 4a75ef2 Compare October 27, 2026 01:09
@etzelm

etzelm commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 27, 2026
- Run post-port memory index rebuilds through runTasksWithConcurrency instead of one agent at a time.
- Size fanout with resolveMemoryRebuildConcurrency in src/commands/doctor-database-port-memory-concurrency.ts: min(compute pool size, free memory / 2 / 512 MiB), at least 1, so hosts with two or fewer CPUs or under 2 GiB free stay sequential.
- Keep the sizing next to its only consumer and leave src/infra/worker-pool-sizing.ts unchanged: that file is in the trusted-anchor PR wrapper inventory (scripts/pr-lib/wrapper-components.txt), and test/scripts/pr-wrapper-source-closure.test.ts and eager-import-closure.test.ts require the inventory to stay closed over its relative runtime imports.
- Keep failures per agent: each rebuild returns its own result and recovery command, and an unexpected throw fails only that agent.
- Rebuild still runs under fresh offline ownership; the Gateway starts after the command finishes.
- Document concurrent rebuilds in the PostgreSQL guide and database engine reference.

Related: openclaw#181859
@etzelm
etzelm force-pushed the improve/port-memory-rebuild-parallel branch from 4a75ef2 to 5956e4e Compare October 27, 2026 01:31
@etzelm

etzelm commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed 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. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper clawsweeper Bot added the status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. label Oct 27, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 27, 2026
@steipete
steipete merged commit e41fa08 into openclaw:main Oct 27, 2026
133 of 136 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

@etzelm
etzelm deleted the improve/port-memory-rebuild-parallel branch October 27, 2026 20:03
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…aw#185237)

- Run post-port memory index rebuilds through runTasksWithConcurrency instead of one agent at a time.
- Size fanout with resolveMemoryRebuildConcurrency in src/commands/doctor-database-port-memory-concurrency.ts: min(compute pool size, free memory / 2 / 512 MiB), at least 1, so hosts with two or fewer CPUs or under 2 GiB free stay sequential.
- Keep the sizing next to its only consumer and leave src/infra/worker-pool-sizing.ts unchanged: that file is in the trusted-anchor PR wrapper inventory (scripts/pr-lib/wrapper-components.txt), and test/scripts/pr-wrapper-source-closure.test.ts and eager-import-closure.test.ts require the inventory to stay closed over its relative runtime imports.
- Keep failures per agent: each rebuild returns its own result and recovery command, and an unexpected throw fails only that agent.
- Rebuild still runs under fresh offline ownership; the Gateway starts after the command finishes.
- Document concurrent rebuilds in the PostgreSQL guide and database engine reference.

Related: openclaw#181859
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime 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: S 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