From 12ea2024a796c58c3a8162bd921cc47d80f61051 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 6 Nov 2026 16:46:55 +0100 Subject: [PATCH 1/7] feat(worker): stage-class workers with concurrent slots (D145) `worker --class convert|llm [--concurrency N]` serves every stage of its class from one process with N tasks in flight (convert 1, llm 20 by default). Slots claim the first route with due work: steady lanes before backfill, downstream stages first, found by one probe query. LISTEN/NOTIFY and SKIP LOCKED stay; a wake-up rouses one idle slot and a slot that finds work rouses one more. The main thread runs the lease reaper. The worker's database pool is sized from its concurrency. Compose runs worker-convert and worker-llm instead of fourteen stage workers; docs, the LoCoMo shard runner, CI service lists and the design corpus follow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- .env.example | 9 +- .github/ci/integration-paths.txt | 1 + .github/workflows/ci.yml | 20 +- benchmarks/locomo/sharding/README.md | 6 +- benchmarks/locomo/sharding/run_shard.sh | 28 +- compose.yaml | 94 +---- decisions.md | 37 ++ design/benchmarks/runbook.md | 4 +- plan/designs/chunk_level_extract_design.md | 8 +- .../e3_claim_level_normalize_fanout_design.md | 5 +- plan/designs/orchestration_design.md | 5 +- plan/designs/packaging_distribution_design.md | 39 +- src/rememberstack/adapters/selfhost/queue.py | 202 +++++++--- src/rememberstack/profiles/selfhost.py | 85 ++-- src/rememberstack/spine/work_ledger.py | 61 ++- src/tests/adapters/test_selfhost_queue.py | 4 +- .../adapters/test_selfhost_worker_classes.py | 371 ++++++++++++++++++ .../benchmarks/test_locomo_store_backup.py | 10 +- src/tests/profiles/test_selfhost_profile.py | 58 ++- website/public/llms-full.txt | 114 +++--- website/public/llms.txt | 2 +- .../docs/guides/versions-in-force/page.mdx | 2 +- website/src/app/docs/reference/cli/page.mdx | 2 +- .../app/docs/self-hosting/install/page.mdx | 24 +- .../docs/self-hosting/observability/page.mdx | 2 +- .../docs/self-hosting/requirements/page.mdx | 19 +- .../app/docs/self-hosting/scaling/page.mdx | 57 ++- .../self-hosting/troubleshooting/page.mdx | 10 +- .../src/app/docs/start/choose/page.cloud.mdx | 4 +- 29 files changed, 918 insertions(+), 365 deletions(-) create mode 100644 src/tests/adapters/test_selfhost_worker_classes.py diff --git a/.env.example b/.env.example index 69856f780..6496d00f6 100644 --- a/.env.example +++ b/.env.example @@ -1,9 +1,14 @@ REMEMBERSTACK_POSTGRES_USER=rememberstack REMEMBERSTACK_POSTGRES_DB=rememberstack # PostgreSQL max_connections. The default 300 covers the stock stack's ceiling -# of 215 connections (API 23 + 12 workers x 16) with headroom; raise it when you -# add API replicas or worker containers. +# of 71 connections (API 23 + worker-llm 43 + worker-convert 5) with headroom; +# a worker needs 2 x concurrency + 3. Raise it when you add API replicas, worker +# containers or concurrency. # REMEMBERSTACK_POSTGRES_MAX_CONNECTIONS=300 +# Tasks in flight per worker container (D145): worker-llm runs every stage +# except convert; worker-convert converts one file at a time by default. +# REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY=20 +# REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY=1 # Every variable in this file reaches the engine containers (compose.yaml # loads .env with env_file), so any engine setting can be set here. # diff --git a/.github/ci/integration-paths.txt b/.github/ci/integration-paths.txt index 6f1d95c98..a48484003 100644 --- a/.github/ci/integration-paths.txt +++ b/.github/ci/integration-paths.txt @@ -2,6 +2,7 @@ src/tests/adapters/test_mount_provisioning.py src/tests/adapters/test_p1_ranked_pg.py src/tests/adapters/test_postgres_p1_document_filters.py src/tests/adapters/test_selfhost_queue.py +src/tests/adapters/test_selfhost_worker_classes.py src/tests/eval/test_harness_skeleton.py src/tests/eval/test_s58_consumption.py src/tests/profiles/test_selfhost_profile.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49d02e774..217b36206 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -339,11 +339,7 @@ jobs: running_services="$( docker compose --env-file .env ps --status running --services )" - for service in \ - api worker-convert worker-structure worker-chunk worker-embed-chunk \ - worker-extract-claims worker-normalize-relations \ - worker-adjudicate-observations worker-adjudicate-supersession \ - worker-embed-claim worker-reconcile worker-label-relation; do + for service in api worker-convert worker-llm; do printf '%s\n' "$running_services" | grep -qx "$service" done ingested="$( @@ -389,11 +385,7 @@ jobs: - name: Stage an upgrade from the prior schema run: | - docker compose --env-file .env stop \ - api worker-convert worker-structure worker-chunk worker-embed-chunk \ - worker-extract-claims worker-normalize-relations \ - worker-adjudicate-observations worker-adjudicate-supersession \ - worker-embed-claim worker-reconcile worker-label-relation + docker compose --env-file .env stop api worker-convert worker-llm # Build an empty pre-D119 fixture. Temporal/span migrations refuse # lossy conversion or downgrade of populated stores. docker compose --env-file .env run --rm --no-deps -T \ @@ -466,7 +458,7 @@ jobs: docker compose "${compose_args[@]}" ps --status running --services )" test -z "$(printf '%s\n' "$running_services" \ - | grep -E '^(api|worker-(convert|structure|chunk|embed-chunk|extract-claims|normalize-relations|adjudicate-observations|adjudicate-supersession|embed-claim|reconcile|label-relation))$' || true)" + | grep -E '^(api|worker-(convert|llm))$' || true)" test "$(docker compose "${compose_args[@]}" exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ 'SELECT version_num FROM alembic_version')" = 'p9_31_0052' @@ -483,11 +475,7 @@ jobs: running_services="$( docker compose "${compose_args[@]}" ps --status running --services )" - for service in \ - api worker-convert worker-structure worker-chunk worker-embed-chunk \ - worker-extract-claims worker-normalize-relations \ - worker-adjudicate-observations worker-adjudicate-supersession \ - worker-embed-claim worker-reconcile worker-label-relation; do + for service in api worker-convert worker-llm; do printf '%s\n' "$running_services" | grep -qx "$service" done curl --fail http://localhost:8000/healthz diff --git a/benchmarks/locomo/sharding/README.md b/benchmarks/locomo/sharding/README.md index 31baced06..b1710ed3c 100644 --- a/benchmarks/locomo/sharding/README.md +++ b/benchmarks/locomo/sharding/README.md @@ -193,11 +193,7 @@ as source-derived data. | `LOCOMO_BACKUP_TOOL` | `benchmarks/locomo/sharding/store_backup.py` | backup tool path; use an absolute path only when operating a pinned clean campaign checkout with a newer compatible safety runner | | `LOCOMO_COMPOSE_PROJECT` | `rememberstack` | Compose label used to resolve exactly four volumes | | `LOCOMO_RUNNER_LOCK` | `/var/lock/rememberstack-locomo-shard.lock` | host-wide exclusive runner lock | -| `LOCOMO_EXTRACT_CLAIM_WORKERS` | `8` | chunk-level Selection worker replicas | -| `LOCOMO_GROUND_CLAIM_WORKERS` | `8` | chunk-level Claimify worker replicas | -| `LOCOMO_NORMALIZE_RELATION_WORKERS` | `6` | claim-level E3 normalize worker replicas | -| `LOCOMO_ADJUDICATE_OBSERVATION_WORKERS` | `4` | post-barrier observation-flush worker replicas | -| `LOCOMO_EMBED_CLAIM_WORKERS` | `2` | P1 claim/fact embedding worker replicas | +| `LOCOMO_LLM_CONCURRENCY` | `40` | tasks in flight in the `worker-llm` process, which serves every stage except `convert` | | `LOCOMO_GCP_CREDENTIALS_FILE` | `/etc/rememberstack/locomo-gcs/credentials.json` | public external-account configuration | | `LOCOMO_GCP_CERTIFICATE_CONFIG_FILE` | `/etc/rememberstack/locomo-gcs/certificate-config.json` | public client-certificate path configuration | | `LOCOMO_VERTEX_GCP_CREDENTIALS_FILE` | unset | optional process-wide generation credential configuration; backups continue to use `LOCOMO_GCP_CREDENTIALS_FILE` | diff --git a/benchmarks/locomo/sharding/run_shard.sh b/benchmarks/locomo/sharding/run_shard.sh index 2b3ff3d30..a829740a4 100755 --- a/benchmarks/locomo/sharding/run_shard.sh +++ b/benchmarks/locomo/sharding/run_shard.sh @@ -39,11 +39,7 @@ backup_project=${LOCOMO_GCP_PROJECT:-} backup_staging_root=${LOCOMO_BACKUP_STAGING_ROOT:-/var/lib/rememberstack-locomo-backups} compose_project=${LOCOMO_COMPOSE_PROJECT:-rememberstack} runner_lock=${LOCOMO_RUNNER_LOCK:-/var/lock/rememberstack-locomo-shard.lock} -extract_claim_workers=${LOCOMO_EXTRACT_CLAIM_WORKERS:-8} -ground_claim_workers=${LOCOMO_GROUND_CLAIM_WORKERS:-8} -normalize_relation_workers=${LOCOMO_NORMALIZE_RELATION_WORKERS:-6} -adjudicate_observation_workers=${LOCOMO_ADJUDICATE_OBSERVATION_WORKERS:-4} -embed_claim_workers=${LOCOMO_EMBED_CLAIM_WORKERS:-2} +llm_concurrency=${LOCOMO_LLM_CONCURRENCY:-40} backup_tool=${LOCOMO_BACKUP_TOOL:-benchmarks/locomo/sharding/store_backup.py} compose=(docker compose --project-name "$compose_project") @@ -104,11 +100,7 @@ for value in \ "$max_judge_calls" \ "$drain_timeout_seconds" \ "$drain_poll_seconds" \ - "$extract_claim_workers" \ - "$ground_claim_workers" \ - "$normalize_relation_workers" \ - "$adjudicate_observation_workers" \ - "$embed_claim_workers"; do + "$llm_concurrency"; do [[ "$value" =~ ^[1-9][0-9]*$ ]] || die "integer caps must be positive" done @@ -330,12 +322,8 @@ require_verified_final_backup() { } start_existing_store() { - "${compose[@]}" up --detach --wait --no-recreate \ - --scale "worker-extract-claims=$extract_claim_workers" \ - --scale "worker-ground-claims=$ground_claim_workers" \ - --scale "worker-normalize-relations=$normalize_relation_workers" \ - --scale "worker-adjudicate-observations=$adjudicate_observation_workers" \ - --scale "worker-embed-claim=$embed_claim_workers" + REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY="$llm_concurrency" \ + "${compose[@]}" up --detach --wait --no-recreate bind_benchmark_api attest_worker_environment } @@ -464,12 +452,8 @@ for sample_id in "${pending_samples[@]}"; do "${compose[@]}" down --volumes --remove-orphans backup_python "$backup_tool" clear-live --run-dir "$run_dir" --lock-fd 9 log "sample=$sample_id stage=stack status=starting" - "${compose[@]}" up --detach --wait \ - --scale "worker-extract-claims=$extract_claim_workers" \ - --scale "worker-ground-claims=$ground_claim_workers" \ - --scale "worker-normalize-relations=$normalize_relation_workers" \ - --scale "worker-adjudicate-observations=$adjudicate_observation_workers" \ - --scale "worker-embed-claim=$embed_claim_workers" + REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY="$llm_concurrency" \ + "${compose[@]}" up --detach --wait bind_benchmark_api attest_worker_environment backup_python "$backup_tool" record-live \ diff --git a/compose.yaml b/compose.yaml index debd1e7dd..3254fefcf 100644 --- a/compose.yaml +++ b/compose.yaml @@ -237,100 +237,20 @@ services: # otherwise; set a token before publishing on another address. - "${REMEMBERSTACK_SELFHOST_API_PUBLISH_ADDRESS:-127.0.0.1}:${REMEMBERSTACK_SELFHOST_API_PORT}:8000" + # Two worker classes (D145): `convert` runs one conversion at a time, so its + # memory is bounded by the largest allowed input; `llm` serves every other + # stage with many tasks in flight. Scale either with `--scale` or with its + # concurrency. worker-convert: <<: *app - command: ["worker", "--stage", "convert"] + command: ["worker", "--class", "convert", "--concurrency", "${REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY:-1}"] depends_on: setup: condition: service_completed_successfully - worker-structure: + worker-llm: <<: *app - command: ["worker", "--stage", "structure"] - depends_on: - setup: - condition: service_completed_successfully - - worker-crossref: - <<: *app - command: ["worker", "--stage", "crossref"] - depends_on: - setup: - condition: service_completed_successfully - - worker-chunk: - <<: *app - command: ["worker", "--stage", "chunk"] - depends_on: - setup: - condition: service_completed_successfully - - worker-embed-chunk: - <<: *app - command: ["worker", "--stage", "embed_chunk"] - depends_on: - setup: - condition: service_completed_successfully - - worker-extract-claims: - <<: *app - command: ["worker", "--stage", "extract_claims"] - depends_on: - setup: - condition: service_completed_successfully - - worker-ground-claims: - <<: *app - command: ["worker", "--stage", "ground_claims"] - depends_on: - setup: - condition: service_completed_successfully - - worker-normalize-relations: - <<: *app - command: ["worker", "--stage", "normalize_relations"] - depends_on: - setup: - condition: service_completed_successfully - - worker-adjudicate-observations: - <<: *app - command: ["worker", "--stage", "adjudicate_observations"] - depends_on: - setup: - condition: service_completed_successfully - - worker-adjudicate-supersession: - <<: *app - command: ["worker", "--stage", "adjudicate_supersession"] - depends_on: - setup: - condition: service_completed_successfully - - worker-embed-claim: - <<: *app - command: ["worker", "--stage", "embed_claim"] - depends_on: - setup: - condition: service_completed_successfully - - worker-reconcile: - <<: *app - command: ["worker", "--stage", "reconcile"] - depends_on: - setup: - condition: service_completed_successfully - - worker-label-relation: - <<: *app - command: ["worker", "--stage", "label_relation"] - depends_on: - setup: - condition: service_completed_successfully - - worker-review-fact-windows: - <<: *app - command: ["worker", "--stage", "review_fact_windows"] + command: ["worker", "--class", "llm", "--concurrency", "${REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY:-20}"] depends_on: setup: condition: service_completed_successfully diff --git a/decisions.md b/decisions.md index eaaeea5a1..e0bbd3d72 100644 --- a/decisions.md +++ b/decisions.md @@ -7455,3 +7455,40 @@ first sweep recovers them. [Orchestration §6](plan/designs/orchestration_design holds the contract; [schema §2](plan/designs/postgres_schema_design.md) the column, index and queries. +## D145. One worker process serves a class of stages, with a fixed number of tasks in flight + +**Status:** accepted. **Date:** 2026-11-06. + +**Context.** Each pipeline stage ran in its own worker process (fourteen in the stock Compose), +each importing the full dependency set, holding its own database pool and `LISTEN` connection, +being woken by every notification, and running one task at a time. Almost every stage spends +its time waiting on a model, embedding or database call, so this was the most memory for the +least concurrency: about two thirds of an idle deployment's memory, and one task per stage in +flight even during a large upload. A combined worker must still never run out of memory, and +conversion's memory grows with the input. + +**Decision.** + +- Two **worker classes**: `convert` (the `convert` stage) and `llm` (every other stage). + `worker --class convert|llm [--concurrency N]` serves every stage of its class from one + process with N tasks in flight, each in its own thread. Starting points to be measured: + `convert` 1, `llm` 20. No dynamic memory accounting: a class's process is sized as peak memory + per task × concurrency + headroom. +- **Fair order:** a free slot claims from the first route with due work in the order steady + lanes, then backfill lanes, each with stages downstream first, so work already in the pipeline + drains before new uploads take the slots. One probe query finds the routes with due work. +- **Delivery is unchanged:** `LISTEN/NOTIFY` wake-ups and `SELECT … FOR UPDATE SKIP LOCKED` + claims (D67). A wake-up rouses one idle slot; a slot that finds work rouses one more. Claim + leases (D144) make it safe for a class process to die with many tasks in flight. +- A process's database pool is sized from its concurrency. + +**Alternatives.** One process per stage with in-process concurrency keeps fourteen idle +interpreters. A single class for everything lets one large conversion share a process, and its +memory, with twenty LLM tasks. Asynchronous handlers would need every handler and adapter +rewritten; threads reuse the synchronous handlers, which share no mutable state. + +**Consequences.** The stock Compose runs `worker-convert` and `worker-llm` +(`REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY`, `REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY`) instead +of fourteen stage workers; `worker --stage` is gone. Contract in +[packaging §3, worker classes](plan/designs/packaging_distribution_design.md#3-task-execution--one-model-two-delivery-shells). + diff --git a/design/benchmarks/runbook.md b/design/benchmarks/runbook.md index 3f848399c..8c4fffa67 100644 --- a/design/benchmarks/runbook.md +++ b/design/benchmarks/runbook.md @@ -98,8 +98,8 @@ Manual equivalents, when you need them: | --- | --- | --- | | `answer` refuses: deployment lacks required pipeline/P1/live-graph/P3 capability readiness | Drain not actually complete, live graph catalog/helper health failed, or P3 published before the last ingest event | Finish the true drain, repair live graph catalog if reported, rebuild P3, then answer. P3 must follow ingest. | | Rows stuck in `dead_letter` | A chunk's extraction (or a relation stage) exhausted 3 attempts — usually glm non-JSON (#174) | `docker compose exec -T api remember ops replay --deployment --attempts 3`, then wait for the drain again. In practice one replay round clears it; bound retries (the wrappers use 3 rounds) so a truly poisoned chunk stops the run loudly instead of looping. | -| A worker reports a model different from `state.json` | A separate post-launch `docker compose up --scale` read stale ambient `.env` values and created a mixed-model fleet | Stop the invalid run. Relaunch through `run_shard.sh` only; set its `LOCOMO_*_WORKERS` variables if different replica counts are needed. The runner attests every app container before ingest and during every drain poll. | -| Extract or normalize remains slow | Replica counts are too low for the current chunk/claim fan-out | Set `LOCOMO_EXTRACT_CLAIM_WORKERS`, `LOCOMO_NORMALIZE_RELATION_WORKERS`, `LOCOMO_ADJUDICATE_OBSERVATION_WORKERS`, or `LOCOMO_EMBED_CLAIM_WORKERS` on the original `run_shard.sh` invocation. Never scale the benchmark with a second Compose command. | +| A worker reports a model different from `state.json` | A separate post-launch `docker compose up --scale` read stale ambient `.env` values and created a mixed-model fleet | Stop the invalid run. Relaunch through `run_shard.sh` only; set its `LOCOMO_LLM_CONCURRENCY` if a different concurrency is needed. The runner attests every app container before ingest and during every drain poll. | +| Extract or normalize remains slow | The `worker-llm` concurrency is too low for the current chunk/claim fan-out | Set `LOCOMO_LLM_CONCURRENCY` on the original `run_shard.sh` invocation. Never scale the benchmark with a second Compose command. | | run_shard refuses: "partial checkpoint; resume stages manually" | A previous attempt died mid-sample, leaving partial ingest/answer records in the run dir | If the stack matches the checkpoint, run the incomplete stage directly; `ingest` first proves the exact public live-lineage/visible-version join. If it does not match and the sample has no answer/judge records, rerun that sample in a new run directory and merge it with the old run. If any answer/judge record exists, restart every sample assigned to that run directory; merging a replacement sample would correctly fail as overlap. Never edit or force a checkpoint forward. | | Item failures recorded in run state | Per-item failures are terminal in that run | Missing items (never attempted, e.g. after a stage-level refusal) can be answered in the same run dir. A terminal failed item requires a fresh deployment and restarting every sample assigned to that run directory; a replacement sample cannot be merged over existing records. | | Preflight/answer/judge cost cap hit | Caps are run-cumulative, not per-invocation | Pass a positive finite run-absolute cap (`--max-evaluator-cost-usd`), sized from §7. | diff --git a/plan/designs/chunk_level_extract_design.md b/plan/designs/chunk_level_extract_design.md index c78e7b53b..774e89887 100644 --- a/plan/designs/chunk_level_extract_design.md +++ b/plan/designs/chunk_level_extract_design.md @@ -20,7 +20,7 @@ workers and tests without reopening product debate. ## 1. Problem `extract_claims` is leased **once per document version** and then walks every E1 -chunk serially inside one handler. Scaling `worker-extract-claims` does not +chunk serially inside one handler. Scaling the `extract_claims` workers does not parallelize Claimify on a single large document (BEAM 1M/10M). E1 already partitions text into section-bounded chunks; the ledger must claim work at that grain. @@ -174,7 +174,7 @@ Connector-cycle finalization SQL must likewise wait on pending/running/failed `processing_state` aggregates by `stage` already power readiness. After this change, `extract_claims` pending/running counts approximate **chunk** backlog. -Document for operators and UMC: scale `worker-extract-claims` on that depth. +Document for operators and UMC: scale the `llm` worker class (D145) on that depth. No new public HTTP API is required for v1. @@ -207,7 +207,7 @@ Chunk ids are internal UUIDs; no new mount surface. ### 9.1 Auto-deploy -- Same container image, same worker entrypoints (`worker --stage extract_claims`). +- Same container image, same worker entrypoint (`worker --class llm`, D145). - No new Coolify service names, secrets, or migrations of the `processing_target` enum (CHUNK already exists). Alembic may still be needed only if readiness SQL lives purely in app code (preferred). @@ -224,7 +224,7 @@ UMC must **not** manufacture extract work. It may: 1. Observe OSS `processing_state` (or a safe aggregate export) for `stage=extract_claims`, statuses pending/running. -2. Set replica count for the data-plane `worker-extract-claims` process. +2. Set the concurrency or replica count of the data-plane `llm` worker class (D145). Chunk-level grain makes that observation **useful**. Control plane remains non- authoritative for work truth (D2/D6/D67 as used in UMC integration analysis). diff --git a/plan/designs/e3_claim_level_normalize_fanout_design.md b/plan/designs/e3_claim_level_normalize_fanout_design.md index fb09203a6..d2094f43c 100644 --- a/plan/designs/e3_claim_level_normalize_fanout_design.md +++ b/plan/designs/e3_claim_level_normalize_fanout_design.md @@ -292,8 +292,9 @@ retry then drop; systemic provider/DB re-raise; mint defense; cost keys ## 9. UMC / compose -Same image; `worker --stage normalize_relations`. Scale on claim-grain -pending/running. No control-plane work manufacture (D67). Single-revision +Same image; `normalize_relations` runs in the `llm` worker class +(`worker --class llm`, D145). Scale that class's concurrency or containers on +claim-grain pending/running. No control-plane work manufacture (D67). Single-revision deploy for all normalize workers. ## 10. Implementation plan (ordered) diff --git a/plan/designs/orchestration_design.md b/plan/designs/orchestration_design.md index 98ce31263..3db4d625f 100644 --- a/plan/designs/orchestration_design.md +++ b/plan/designs/orchestration_design.md @@ -120,8 +120,9 @@ isolate state the two lanes share (below). Rules: metered for) a backfill version's earlier application on a shared entity, and opens its repair on the steady lane; and a fresh version of a lineage that is still being backfilled waits for its predecessors (D143 lineage order). The duplicate-promotion rule above is unchanged. -- **The self-host profile serves the backfill lane** from the same per-stage worker: a worker - claims from its stage's backfill route whenever its steady route has no due row. +- **The self-host profile serves the backfill lane** from the same worker process: a worker + class claims from its stages' backfill routes whenever none of their steady routes has a due + row ([packaging §3, worker classes](packaging_distribution_design.md#3-task-execution--one-model-two-delivery-shells), D145). - **Lane budgets are separate** (§4): backfill spend is a knob turned deliberately; apart from the shared-entity applications above, it does not draw on the steady-state budget. The two dominant backfill costs are metered per lane diff --git a/plan/designs/packaging_distribution_design.md b/plan/designs/packaging_distribution_design.md index 2a89ab440..46cc262a9 100644 --- a/plan/designs/packaging_distribution_design.md +++ b/plan/designs/packaging_distribution_design.md @@ -131,12 +131,41 @@ are hints, never inputs to a state transition. construction. The self-host adapter's `announce` method never inserts: for retry, replay, or janitor re-announcement it invokes the injected `spine/` notification primitive for the existing row (SQL remains exclusively in `spine/`). Worker processes sleep - on `LISTEN`; a notify wakes them in milliseconds; the woken worker claims only rows on its - configured `(deployment, stage, lane)` route whose `not_before <= now()`, using + on `LISTEN`; a notify wakes them in milliseconds; the woken worker claims only rows on the + routes of its **worker class** whose `not_before <= now()`, using `SELECT … FOR UPDATE SKIP LOCKED LIMIT n` and the schema §2 due-work index. A **slow fallback - poll (~30 s)** exists only as a safety net for missed notifications, scheduled work becoming - due, and crash recovery. Application attempts/backoff remain row state; per-route rate limits - are a token bucket consulted around the claim. Scaling = `docker compose up --scale worker=N`. + poll (~30 s)** exists only as a safety net for missed notifications and scheduled work becoming + due; crash recovery is the lease reaper (orchestration §6, D144). Application attempts/backoff + remain row state; a per-process rate limit is a token bucket consulted around the claim. + Scaling = raise a class's concurrency, or `docker compose up --scale worker-llm=N`. + + **Worker classes (D145).** One worker process serves every stage of one class, with a fixed + number of tasks in flight (its *concurrency*), each in its own thread: + + | Class | Stages | Tasks in flight (starting point) | Why | + |---|---|---|---| + | `convert` | `convert` | 1 | Conversion runs LibreOffice and PDF rendering in-process; its memory grows with the input, so one at a time bounds a process by the largest allowed input, and a conversion that kills its process takes only itself down. | + | `llm` | every other stage | 20 | These stages spend almost all their time waiting on model, embedding or database calls; many in flight per process is cheap. | + + Memory is safe by construction rather than by accounting: a class's process is sized as peak + memory per task × concurrency + headroom, measured once per class. A process that still runs + out of memory loses only its own in-flight tasks; their leases expire and they are retried, + and a task that kills its worker every time dead-letters after `max_attempts` (D144). + + **Fair order.** A class process lists its routes as every stage's steady lane, then every + stage's backfill lane, each in pipeline order **downstream first** (e.g. `label_relation` + before `extract_claims` before `structure`). A free slot claims from the first route with due + work. Work already inside the pipeline therefore finishes before a large new upload takes the + slots, and steady work keeps priority over backfill exactly as with one process per stage. + Finding that route is one probe query over all routes (the claim's own due predicate per + route), not one claim attempt per route. + + **Slots and wake-ups.** The process's main thread holds the `LISTEN` connection and runs the + lease reaper. A notification or the fallback poll wakes **one** idle slot; a slot that finds + due work wakes one more before running it. Idle slots therefore look for work one at a time, + and a burst ramps up to full concurrency within a few claims. A process's database pool is + sized from its concurrency (two connections per task, since one code path nests a read inside a + transaction, plus a few for lease renewal and the reaper). - **GCP reference shell — Cloud Tasks push.** Announcement = create a Cloud Task; delivery = an HTTP push to a thin Cloud Run handler-dispatch server. The task carries `processing_id` plus a snapshot of route and `not_before`; Cloud Tasks scheduling and per-route rate limits reduce diff --git a/src/rememberstack/adapters/selfhost/queue.py b/src/rememberstack/adapters/selfhost/queue.py index 01b7d2231..26f1d61d2 100644 --- a/src/rememberstack/adapters/selfhost/queue.py +++ b/src/rememberstack/adapters/selfhost/queue.py @@ -3,12 +3,13 @@ Work is Postgres rows; this shell only delivers wake-ups. The schema-owned insert trigger provides the transactional initial wake; `announce` re-announces existing rows through the spine's notification primitive; the worker loop -sleeps on LISTEN with a slow fallback poll and claims only its configured -route, consulting a token bucket around each claim. +sleeps on LISTEN with a slow fallback poll and claims only the routes of its +worker class, consulting a token bucket around each claim. """ from collections.abc import Callable import logging +import threading import time from uuid import UUID @@ -68,98 +69,173 @@ def __init__( self._clock = clock self._tokens = capacity self._refilled_at = clock() + self._lock = threading.Lock() def try_acquire(self) -> bool: - """Take one token if available; never blocks.""" - now = self._clock() - self._tokens = min( - self._capacity, self._tokens + (now - self._refilled_at) * self._rate_per_s - ) - self._refilled_at = now - if self._tokens < 1.0: - return False - self._tokens -= 1.0 - return True + """Take one token if available; never blocks. Safe across threads.""" + with self._lock: + now = self._clock() + self._tokens = min( + self._capacity, + self._tokens + (now - self._refilled_at) * self._rate_per_s, + ) + self._refilled_at = now + if self._tokens < 1.0: + return False + self._tokens -= 1.0 + return True class SelfHostWorkerLoop: - """One route's worker loop: sleep on LISTEN, drain due work, fall back to polling.""" + """One worker class's loop: concurrent slots drain due work across its stages. + + The loop serves every route of its stages, steady lanes before backfill + lanes, and within a lane the stages in the order given (callers list + downstream stages first, so work already in the pipeline drains before new + uploads take the slots). ``concurrency`` slots each run one task at a time + in their own thread. The calling thread sleeps on LISTEN with a slow + fallback poll; every wake-up, and every claim that found work, wakes one + idle slot, so idle slots look for work one at a time instead of all at + once. The calling thread also sweeps expired claims (D144) at most once + per fallback-poll interval. + """ def __init__( self, *, worker: Worker, + ledger: WorkLedger, deployment_id: UUID, - stage: PipelineStage, - lane: ProcessingLane | None, + stages: tuple[PipelineStage, ...], bucket: TokenBucket, database_url: str, fallback_poll_s: float = 30.0, - serve_backfill: bool = False, + concurrency: int = 1, ) -> None: - """Bind the loop to its route, rate limit, and LISTEN connection source. - - ``serve_backfill`` lets a steady-route loop also claim its stage's - backfill route whenever the steady route has no due row (D143 §5.5), - so priority stays structural: steady first, every time. - """ + """Bind the loop to its stages, rate limit, slots and LISTEN connection.""" + if concurrency < 1: + raise ValueError("a worker loop needs at least one slot") self._worker = worker + self._ledger = ledger self._deployment_id = deployment_id - self._stage = stage - self._lane = lane + self._routes = tuple( + (stage, lane) + for lane in (ProcessingLane.STEADY, ProcessingLane.BACKFILL) + for stage in stages + ) self._bucket = bucket self._database_url = database_url self._fallback_poll_s = fallback_poll_s - self._serve_backfill = serve_backfill and lane is ProcessingLane.STEADY + self._concurrency = concurrency self._reaped_at = float("-inf") + self._wake = threading.Condition() + self._wake_pending = False def drain_due(self) -> tuple[RunResult, ...]: - """Claim and run due work on the route until none remains or tokens run out. - - At most once per fallback-poll interval, also between tasks of a long - drain, it takes back expired claims on its stage, so work a killed - worker held runs again. - """ + """Run due work in the calling thread until none remains or tokens run out.""" results: list[RunResult] = [] - while True: - self._reap_if_due() - if not self._bucket.try_acquire(): - break - result = self._worker.run_one( - deployment_id=self._deployment_id, stage=self._stage, lane=self._lane - ) - if result.outcome is RunResultOutcome.NO_WORK and self._serve_backfill: - result = self._worker.run_one( - deployment_id=self._deployment_id, - stage=self._stage, - lane=ProcessingLane.BACKFILL, - ) - if result.outcome is RunResultOutcome.NO_WORK: - break + while (result := self._run_next()) is not None: results.append(result) return tuple(results) - def _reap_if_due(self) -> None: - """Sweep expired claims when a fallback-poll interval has passed.""" - if time.monotonic() - self._reaped_at >= self._fallback_poll_s: - self._reaped_at = time.monotonic() - self._worker.reap_expired_leases(deployment_id=self._deployment_id) - def run_for(self, *, duration_s: float) -> tuple[RunResult, ...]: - """Listen, drain on every wake, and fall back to polling, for a bounded time. + """Listen and run the slots for a bounded time, then let in-flight tasks finish. The production loop is this method called with a large duration under a supervisor; tests call it with a short one. Missed notifications are - covered by the fallback poll, per the packaging design. + covered by the fallback poll, per the packaging design. A slot that + raises stops the loop, and the error is re-raised here. """ - results: list[RunResult] = list(self.drain_due()) + stop = threading.Event() + results: list[RunResult] = [] + errors: list[BaseException] = [] + slots = [ + threading.Thread( + target=self._slot, + kwargs={"stop": stop, "results": results, "errors": errors}, + name=f"worker-slot-{index}", + daemon=True, + ) + for index in range(self._concurrency) + ] + started: list[threading.Thread] = [] deadline = time.monotonic() + duration_s - with psycopg.connect(self._database_url, autocommit=True) as connection: - connection.execute(f"LISTEN {_WAKE_CHANNEL}") - while (remaining := deadline - time.monotonic()) > 0: - timeout = min(remaining, self._fallback_poll_s) - woken = list(connection.notifies(timeout=timeout, stop_after=1)) - if woken: - _logger.debug("wake received: %s", woken[0].payload) - results.extend(self.drain_due()) + try: + with psycopg.connect(self._database_url, autocommit=True) as connection: + connection.execute(f"LISTEN {_WAKE_CHANNEL}") + for slot in slots: + slot.start() + started.append(slot) + self._reap_if_due() + self._signal() + while not stop.is_set() and ( + (remaining := deadline - time.monotonic()) > 0 + ): + timeout = min(remaining, self._fallback_poll_s) + woken = list(connection.notifies(timeout=timeout, stop_after=1)) + if woken: + _logger.debug("wake received: %s", woken[0].payload) + self._reap_if_due() + self._signal() + finally: + stop.set() + with self._wake: + self._wake.notify_all() + for slot in started: + slot.join() + if errors: + raise errors[0] return tuple(results) + + def _slot( + self, + *, + stop: threading.Event, + results: list[RunResult], + errors: list[BaseException], + ) -> None: + """Run due work until stopped; sleep until signalled when none is due.""" + try: + while not stop.is_set(): + result = self._run_next() + if result is not None: + results.append(result) + continue + with self._wake: + while not self._wake_pending and not stop.is_set(): + self._wake.wait() + self._wake_pending = False + except BaseException as error: # re-raised by run_for + errors.append(error) + stop.set() + with self._wake: + self._wake.notify_all() + + def _run_next(self) -> RunResult | None: + """Claim and run the first due unit of work in route order, if any.""" + if not self._bucket.try_acquire(): + return None + due = self._ledger.due_routes( + deployment_id=self._deployment_id, routes=self._routes + ) + if due: + self._signal() # there may be more: let one idle slot look too + for stage, lane in due: + result = self._worker.run_one( + deployment_id=self._deployment_id, stage=stage, lane=lane + ) + if result.outcome is not RunResultOutcome.NO_WORK: + return result + return None + + def _signal(self) -> None: + """Wake one idle slot (or the next slot to go idle) to look for work.""" + with self._wake: + self._wake_pending = True + self._wake.notify() + + def _reap_if_due(self) -> None: + """Sweep expired claims when a fallback-poll interval has passed.""" + if time.monotonic() - self._reaped_at >= self._fallback_poll_s: + self._reaped_at = time.monotonic() + self._worker.reap_expired_leases(deployment_id=self._deployment_id) diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index 1e21fb9ee..9331d85a8 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -114,6 +114,23 @@ PipelineStage.REVIEW_FACT_WINDOWS, ) +#: The worker classes (D145). ``convert`` is the one input-size-dependent, +#: CPU- and memory-heavy stage; ``llm`` is every other stage, which mostly +#: waits on model and embedding calls or the database. Each class lists its +#: stages downstream first: that is the order a worker drains them in. +WORKER_CLASSES: dict[str, tuple[PipelineStage, ...]] = { + "convert": (PipelineStage.CONVERT,), + "llm": tuple( + stage + for stage in reversed(_SUPPORTED_WORKER_STAGES) + if stage is not PipelineStage.CONVERT + ), +} +#: Tasks in flight per worker process when ``--concurrency`` is not given. +#: Starting points to be measured: one conversion at a time bounds memory by +#: the largest allowed input; LLM-bound tasks spend most of their time waiting. +DEFAULT_WORKER_CONCURRENCY: dict[str, int] = {"convert": 1, "llm": 20} + class BuildProvenanceSettings(BaseSettings): """The source revision stamped into this image when it was built. @@ -1468,17 +1485,18 @@ def run_meter_receipts(self, *, once: bool = False, limit: int = 100) -> None: return time.sleep(self._settings.meter_receipt_poll_s) - def worker_loop(self, *, stage: PipelineStage) -> SelfHostWorkerLoop: - """Build one continuous route's ordinary LISTEN/NOTIFY worker loop.""" + def worker_loop(self, *, worker_class: str, concurrency: int) -> SelfHostWorkerLoop: + """Build one worker class's LISTEN/NOTIFY loop over all of its stages (D146).""" from rememberstack.adapters.selfhost import SelfHostWorkerLoop from rememberstack.adapters.selfhost import TokenBucket - from rememberstack.model import ProcessingLane + from rememberstack.spine import WorkLedger + stages = WORKER_CLASSES[worker_class] return SelfHostWorkerLoop( - worker=self._worker(stage=stage), + worker=self._worker(stages=stages), + ledger=WorkLedger(engine=self._engine, settings=self._work_ledger_settings), deployment_id=self._settings.deployment_id, - stage=stage, - lane=ProcessingLane.STEADY, + stages=stages, bucket=TokenBucket( rate_per_s=self._settings.worker_rate_per_s, capacity=self._settings.worker_burst, @@ -1487,7 +1505,7 @@ def worker_loop(self, *, stage: PipelineStage) -> SelfHostWorkerLoop: hide_password=False ), fallback_poll_s=self._settings.worker_fallback_poll_s, - serve_backfill=True, + concurrency=concurrency, ) def run_task(self, *, processing_id: UUID) -> RunResult: @@ -1515,8 +1533,12 @@ def run_task(self, *, processing_id: UUID) -> RunResult: f"processing row {processing_id} belongs to deployment" f" {route.deployment_id}, not {self._settings.deployment_id}" ) + if route.stage not in _SUPPORTED_WORKER_STAGES: + raise ValueError( + f"the self-host profile has no handler for stage {route.stage}" + ) with collect_new_work() as created: - result = self._worker(stage=route.stage).run_one( + result = self._worker(stages=(route.stage,)).run_one( deployment_id=route.deployment_id, stage=route.stage, lane=route.lane, @@ -1545,18 +1567,17 @@ def _queue(self, *, ledger: WorkLedger) -> TaskQueuePort: return self._task_queue or SelfHostTaskQueue(ledger=ledger) - def _worker(self, *, stage: PipelineStage) -> Worker: - """One stage's claim-and-run boundary over this deployment's ledger.""" + def _worker(self, *, stages: tuple[PipelineStage, ...]) -> Worker: + """The claim-and-run boundary for some stages over this deployment's ledger.""" from rememberstack.adapters.selfhost import FanoutTelemetry from rememberstack.adapters.selfhost import JsonLineTelemetry from rememberstack.spine import WorkLedger from rememberstack.workers import HandlerRegistry from rememberstack.workers import Worker - if stage not in _SUPPORTED_WORKER_STAGES: - raise ValueError(f"the self-host profile has no handler for stage {stage}") registry = HandlerRegistry() - registry.register(stage=stage, handler=self._handler(stage=stage)) + for stage in stages: + registry.register(stage=stage, handler=self._handler(stage=stage)) ledger = WorkLedger(engine=self._engine, settings=self._work_ledger_settings) local_telemetry = JsonLineTelemetry() telemetry = ( @@ -1571,9 +1592,9 @@ def _worker(self, *, stage: PipelineStage) -> Worker: telemetry=telemetry, ) - def run_worker(self, *, stage: PipelineStage) -> None: - """Run one configured continuous route until stopped or failed.""" - loop = self.worker_loop(stage=stage) + def run_worker(self, *, worker_class: str, concurrency: int) -> None: + """Run one worker class until stopped or failed.""" + loop = self.worker_loop(worker_class=worker_class, concurrency=concurrency) while True: loop.run_for(duration_s=self._settings.worker_session_s) @@ -1624,7 +1645,7 @@ def publish_mounts( ).publish(deployment_id=self._settings.deployment_id) def _handler(self, *, stage: PipelineStage) -> StageHandler: - """Compose exactly one implemented stage handler for one worker process.""" + """Compose the handler of one implemented stage.""" from rememberstack.adapters.postgres_p1 import PostgresP1Index from rememberstack.core import chunker_version from rememberstack.core import ChunkerParams @@ -1867,11 +1888,14 @@ def main(argv: list[str] | None = None) -> int: subparsers = parser.add_subparsers(dest="command", required=True) subparsers.add_parser("setup", help="migrate and bootstrap the deployment") subparsers.add_parser("api", help="serve the deployment HTTP API") - worker = subparsers.add_parser("worker", help="run one continuous worker route") + worker = subparsers.add_parser("worker", help="run every stage of one worker class") worker.add_argument( - "--stage", - choices=tuple(stage.value for stage in _SUPPORTED_WORKER_STAGES), - required=True, + "--class", dest="worker_class", choices=tuple(WORKER_CLASSES), required=True + ) + worker.add_argument( + "--concurrency", + type=_positive_int, + help="tasks in flight (default: 1 for convert, 20 for llm)", ) meter = subparsers.add_parser( "meter-receipts", help="replay managed ingest measurement/outcome receipts" @@ -1909,8 +1933,15 @@ def main(argv: list[str] | None = None) -> int: error_telemetry = _initialize_error_tracking( command=args.command, deployment_slug=settings.deployment_slug ) + concurrency = ( + (args.concurrency or DEFAULT_WORKER_CONCURRENCY[args.worker_class]) + if args.command == "worker" + else 0 + ) profile = SelfHostProfile.from_settings( - EngineSettings.from_env(), error_telemetry=error_telemetry + EngineSettings.from_env(), + error_telemetry=error_telemetry, + worker_concurrency=concurrency or None, ) try: if args.command == "setup": @@ -1931,7 +1962,7 @@ def main(argv: list[str] | None = None) -> int: if args.command == "meter-receipts": profile.run_meter_receipts(once=args.once, limit=args.limit) return 0 - profile.run_worker(stage=PipelineStage(args.stage)) + profile.run_worker(worker_class=args.worker_class, concurrency=concurrency) return 0 finally: profile.close() @@ -1955,6 +1986,14 @@ def _initialize_error_tracking( ) +def _positive_int(value: str) -> int: + """Parse a strictly positive integer command-line value.""" + number = int(value) + if number < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return number + + def _expected_components() -> dict[PipelineStage, str]: """The per-version continuous generations composed by this profile. diff --git a/src/rememberstack/spine/work_ledger.py b/src/rememberstack/spine/work_ledger.py index 0945b5748..e60e5986c 100644 --- a/src/rememberstack/spine/work_ledger.py +++ b/src/rememberstack/spine/work_ledger.py @@ -9,6 +9,7 @@ """ from collections.abc import Collection +from collections.abc import Sequence from dataclasses import dataclass from datetime import datetime from datetime import timedelta @@ -809,6 +810,34 @@ def fail( ) return None + def due_routes( + self, + *, + deployment_id: UUID, + routes: Sequence[tuple[PipelineStage, ProcessingLane]], + ) -> tuple[tuple[PipelineStage, ProcessingLane], ...]: + """Return, in the given order, the laned routes that have claimable work now. + + One round trip probes every route with the claim's own due predicate, + so a worker serving many routes does not open a claim transaction per + empty route. The answer is a hint: a claim on a listed route can still + find nothing (another worker took it, or a hold applies). + """ + if not routes: + return () + with self._engine.connect() as connection: + due = set( + connection.execute( + _DUE_ROUTES, + { + "deployment_id": deployment_id, + "stages": [stage.value for stage, _ in routes], + "lanes": [lane.value for _, lane in routes], + }, + ).scalars() + ) + return tuple(route for index, route in enumerate(routes, 1) if index in due) + @property def lease_renewal_interval_s(self) -> float: """How often a worker renews its claims: a third of the lease.""" @@ -1967,11 +1996,9 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: """ ) -_CLAIM_DUE_ON_ROUTE = """ - deployment_id = :deployment_id - AND stage = :stage - AND lane IS NOT DISTINCT FROM :lane - AND status IN ('pending', 'failed') +# The claimable-now predicate shared by the claims and the due-route probe. +_CLAIMABLE = """ + status IN ('pending', 'failed') AND not_before <= now() AND attempts < max_attempts -- D117: no_route work is parked on a CONFIGURATION fact, not a clock. @@ -1981,6 +2008,13 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: AND (defer_reason IS NULL OR defer_reason::text <> 'no_route') """ +_CLAIM_DUE_ON_ROUTE = f""" + deployment_id = :deployment_id + AND stage = :stage + AND lane IS NOT DISTINCT FROM :lane + AND {_CLAIMABLE} +""" + _CLAIM_SELECT = text( f""" SELECT processing_id @@ -2002,6 +2036,23 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: """ ) +_DUE_ROUTES = text( + f""" + SELECT r.ordinal + FROM unnest( + CAST(:stages AS pipeline_stage[]), CAST(:lanes AS processing_lane[]) + ) WITH ORDINALITY AS r(stage, lane, ordinal) + WHERE EXISTS ( + SELECT 1 + FROM processing_state + WHERE deployment_id = :deployment_id + AND stage = r.stage + AND lane = r.lane + AND {_CLAIMABLE} + ) + """ +) + _SELECT_ROUTE = text( """ SELECT deployment_id, stage, lane diff --git a/src/tests/adapters/test_selfhost_queue.py b/src/tests/adapters/test_selfhost_queue.py index 4bd9850da..52ffec27a 100644 --- a/src/tests/adapters/test_selfhost_queue.py +++ b/src/tests/adapters/test_selfhost_queue.py @@ -197,9 +197,9 @@ def test_demo_chain_runs_on_selfhost_shell_with_zero_gcp_deps( registry.register(stage=PipelineStage.EXTRACT_CLAIMS, handler=_NoOpHandler()) loop = SelfHostWorkerLoop( worker=Worker(ledger=ledger, registry=registry), + ledger=ledger, deployment_id=_DEPLOYMENT_ID, - stage=PipelineStage.EXTRACT_CLAIMS, - lane=ProcessingLane.STEADY, + stages=(PipelineStage.EXTRACT_CLAIMS,), bucket=TokenBucket(rate_per_s=100.0, capacity=10.0), database_url=_psycopg_url(database_url), fallback_poll_s=0.2, diff --git a/src/tests/adapters/test_selfhost_worker_classes.py b/src/tests/adapters/test_selfhost_worker_classes.py new file mode 100644 index 000000000..c7a5032e8 --- /dev/null +++ b/src/tests/adapters/test_selfhost_worker_classes.py @@ -0,0 +1,371 @@ +"""Real-PostgreSQL proofs for stage-class workers (D145). + +One worker process serves every stage of its class with several tasks in +flight. Downstream stages drain first, steady lanes before backfill lanes, and +two deployments in two databases run side by side in one process without +touching each other's rows. +""" + +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path +import threading +import time +from uuid import UUID +from uuid import uuid4 + +from alembic import command +from alembic.config import Config +from pydantic import ValidationError +import pytest +from sqlalchemy import create_engine +from sqlalchemy import text +from sqlalchemy.engine import Engine +from sqlalchemy.engine import make_url + +from rememberstack.adapters.selfhost import SelfHostWorkerLoop +from rememberstack.adapters.selfhost import TokenBucket +from rememberstack.model import ClaimedWork +from rememberstack.model import DeploymentBootstrapInput +from rememberstack.model import EnqueueWork +from rememberstack.model import PipelineStage +from rememberstack.model import ProcessingLane +from rememberstack.model import ProcessingTarget +from rememberstack.model import RunResultOutcome +from rememberstack.ports.cost_meter import CostMeterPort +from rememberstack.spine import DeploymentBootstrapper +from rememberstack.spine import WorkLedger +from rememberstack.spine import WorkLedgerSettings +from rememberstack.spine.settings import load_database_settings +from rememberstack.workers import HandlerOutcome +from rememberstack.workers import HandlerRegistry +from rememberstack.workers import Worker +from tests.database_reset import reset_database + +_ROOT = Path(__file__).resolve().parents[3] +_DEPLOYMENT_A = UUID("60000000-0000-0000-0000-00000000000a") +_DEPLOYMENT_B = UUID("60000000-0000-0000-0000-00000000000b") +_VERSION = "worker-class-test-2026-11" +_UPSTREAM = PipelineStage.EXTRACT_CLAIMS +_DOWNSTREAM = PipelineStage.EMBED_CLAIM +_STAGES = (_DOWNSTREAM, _UPSTREAM) # downstream first, as the profile lists them + + +def _migrated_engine(url: str, *, deployment_id: UUID, slug: str) -> Engine: + config = Config(str(_ROOT / "alembic.ini")) + config.set_main_option("sqlalchemy.url", url) + reset_database(config=config) + command.upgrade(config=config, revision="head") + engine = create_engine(url, pool_size=20, max_overflow=20) + DeploymentBootstrapper(engine=engine).bootstrap_deployment( + deployment_input=DeploymentBootstrapInput( + deployment_id=deployment_id, + slug=slug, + name=f"Worker class proofs {slug}", + default_language="en", + raw_bucket="mem://raw", + artifacts_bucket="mem://artifacts", + corpusfs_bucket="mem://corpusfs", + ) + ) + return engine + + +@pytest.fixture(scope="module") +def database_url() -> str: + """The accepted integration database URL, or a module-wide skip.""" + try: + return load_database_settings().sqlalchemy_url() + except ValidationError: + pytest.skip("REMEMBERSTACK_DATABASE_URL is required for worker class proofs") + + +@pytest.fixture(scope="module") +def second_database_url(database_url: str) -> str: + """A second database on the same server: a second deployment's own store.""" + url = make_url(database_url) + name = f"{url.database}_second" + admin = create_engine(url, isolation_level="AUTOCOMMIT") + try: + with admin.connect() as connection: + exists = connection.execute( + text("SELECT 1 FROM pg_database WHERE datname = :name"), {"name": name} + ).first() + if exists is None: + connection.execute(text(f'CREATE DATABASE "{name}"')) + finally: + admin.dispose() + return url.set(database=name).render_as_string(hide_password=False) + + +@pytest.fixture(scope="module") +def migrated_engine(database_url: str) -> Iterator[Engine]: + """A migrated store holding deployment A, shared by the module.""" + engine = _migrated_engine(database_url, deployment_id=_DEPLOYMENT_A, slug="a") + try: + yield engine + finally: + engine.dispose() + + +@pytest.fixture() +def engine(migrated_engine: Engine) -> Engine: + """Deployment A's store with an empty work ledger.""" + with migrated_engine.begin() as connection: + connection.execute(text("TRUNCATE processing_state CASCADE")) + return migrated_engine + + +def _psycopg_url(database_url: str) -> str: + return database_url.replace("postgresql+psycopg://", "postgresql://", 1) + + +def _ledger(engine: Engine) -> WorkLedger: + return WorkLedger( + engine=engine, + settings=WorkLedgerSettings(retry_backoff_base_s=0.0, retry_backoff_max_s=0.0), + ) + + +def _enqueue( + ledger: WorkLedger, + *, + deployment_id: UUID, + stage: PipelineStage, + lane: ProcessingLane = ProcessingLane.STEADY, +) -> UUID: + return ledger.enqueue( + work=EnqueueWork( + deployment_id=deployment_id, + target_kind=ProcessingTarget.CHUNK, + target_id=uuid4(), + stage=stage, + component_version=_VERSION, + content_hash="sha256:test", + lane=lane, + ) + ).processing_id + + +@dataclass(frozen=True) +class _Run: + deployment_id: UUID + stage: PipelineStage + lane: ProcessingLane | None + started: float + finished: float + + +class _Recording: + """A handler shared by every stage and slot: records runs and peak overlap.""" + + def __init__(self, *, seconds: float = 0.0) -> None: + self._seconds = seconds + self._lock = threading.Lock() + self._in_flight = 0 + self.peak = 0 + self.runs: list[_Run] = [] + + def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: + del meter + started = time.monotonic() + with self._lock: + self._in_flight += 1 + self.peak = max(self.peak, self._in_flight) + time.sleep(self._seconds) + with self._lock: + self._in_flight -= 1 + self.runs.append( + _Run( + deployment_id=work.deployment_id, + stage=work.stage, + lane=work.lane, + started=started, + finished=time.monotonic(), + ) + ) + return HandlerOutcome() + + +def _loop( + *, + engine: Engine, + database_url: str, + deployment_id: UUID, + handler: _Recording, + concurrency: int, +) -> SelfHostWorkerLoop: + ledger = _ledger(engine) + registry = HandlerRegistry() + for stage in _STAGES: + registry.register(stage=stage, handler=handler) + return SelfHostWorkerLoop( + worker=Worker(ledger=ledger, registry=registry), + ledger=ledger, + deployment_id=deployment_id, + stages=_STAGES, + bucket=TokenBucket(rate_per_s=1_000.0, capacity=1_000.0), + database_url=_psycopg_url(database_url), + fallback_poll_s=0.2, + concurrency=concurrency, + ) + + +def test_due_routes_lists_only_routes_with_claimable_work_in_order( + engine: Engine, +) -> None: + """The one-query probe answers in the caller's order and skips idle routes.""" + ledger = _ledger(engine) + _enqueue(ledger, deployment_id=_DEPLOYMENT_A, stage=_UPSTREAM) + _enqueue( + ledger, + deployment_id=_DEPLOYMENT_A, + stage=_DOWNSTREAM, + lane=ProcessingLane.BACKFILL, + ) + routes = ( + (_DOWNSTREAM, ProcessingLane.STEADY), + (_UPSTREAM, ProcessingLane.STEADY), + (_DOWNSTREAM, ProcessingLane.BACKFILL), + (_UPSTREAM, ProcessingLane.BACKFILL), + ) + assert ledger.due_routes(deployment_id=_DEPLOYMENT_A, routes=routes) == ( + (_UPSTREAM, ProcessingLane.STEADY), + (_DOWNSTREAM, ProcessingLane.BACKFILL), + ) + + +def test_one_slot_drains_downstream_stages_first_and_steady_before_backfill( + database_url: str, engine: Engine +) -> None: + """Fair order: steady downstream, steady upstream, then the backfill lanes.""" + ledger = _ledger(engine) + for stage, lane in ( + (_UPSTREAM, ProcessingLane.BACKFILL), + (_UPSTREAM, ProcessingLane.STEADY), + (_DOWNSTREAM, ProcessingLane.BACKFILL), + (_UPSTREAM, ProcessingLane.STEADY), + (_DOWNSTREAM, ProcessingLane.STEADY), + ): + _enqueue(ledger, deployment_id=_DEPLOYMENT_A, stage=stage, lane=lane) + handler = _Recording() + loop = _loop( + engine=engine, + database_url=database_url, + deployment_id=_DEPLOYMENT_A, + handler=handler, + concurrency=1, + ) + + results = loop.drain_due() + + assert [result.outcome for result in results] == [RunResultOutcome.SUCCEEDED] * 5 + assert [(run.stage, run.lane) for run in handler.runs] == [ + (_DOWNSTREAM, ProcessingLane.STEADY), + (_UPSTREAM, ProcessingLane.STEADY), + (_UPSTREAM, ProcessingLane.STEADY), + (_DOWNSTREAM, ProcessingLane.BACKFILL), + (_UPSTREAM, ProcessingLane.BACKFILL), + ] + + +def test_slots_run_tasks_of_several_stages_at_once( + database_url: str, engine: Engine +) -> None: + """With four slots, four tasks overlap and both stages are in flight together. + + Three downstream tasks fill three slots first; the fourth slot takes an + upstream task alongside them. + """ + ledger = _ledger(engine) + for stage in (_UPSTREAM, _DOWNSTREAM) * 3: + _enqueue(ledger, deployment_id=_DEPLOYMENT_A, stage=stage) + handler = _Recording(seconds=0.6) + loop = _loop( + engine=engine, + database_url=database_url, + deployment_id=_DEPLOYMENT_A, + handler=handler, + concurrency=4, + ) + + results = loop.run_for(duration_s=2.0) + + assert len(results) == 6 + assert {result.outcome for result in results} == {RunResultOutcome.SUCCEEDED} + assert handler.peak == 4 + assert _overlap(handler.runs, _UPSTREAM, _DOWNSTREAM) + + +def test_two_deployments_in_two_databases_interleave_in_one_process( + database_url: str, second_database_url: str, engine: Engine +) -> None: + """Two deployments' loops run side by side; each drains only its own store.""" + second = _migrated_engine( + second_database_url, deployment_id=_DEPLOYMENT_B, slug="b" + ) + try: + stores = ( + (engine, database_url, _DEPLOYMENT_A), + (second, second_database_url, _DEPLOYMENT_B), + ) + for store, _, deployment_id in stores: + for stage in (_UPSTREAM, _DOWNSTREAM) * 3: + _enqueue(_ledger(store), deployment_id=deployment_id, stage=stage) + handler = _Recording(seconds=0.4) + loops = [ + _loop( + engine=store, + database_url=url, + deployment_id=deployment_id, + handler=handler, + concurrency=3, + ) + for store, url, deployment_id in stores + ] + outcomes: dict[UUID, tuple[RunResultOutcome, ...]] = {} + + def run(loop: SelfHostWorkerLoop, deployment_id: UUID) -> None: + outcomes[deployment_id] = tuple( + result.outcome for result in loop.run_for(duration_s=2.0) + ) + + threads = [ + threading.Thread(target=run, args=(loop, deployment_id)) + for loop, (_, _, deployment_id) in zip(loops, stores, strict=True) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert outcomes == { + _DEPLOYMENT_A: (RunResultOutcome.SUCCEEDED,) * 6, + _DEPLOYMENT_B: (RunResultOutcome.SUCCEEDED,) * 6, + } + assert handler.peak > 3 # more than one loop's slots were busy at once + runs_a = [run for run in handler.runs if run.deployment_id == _DEPLOYMENT_A] + runs_b = [run for run in handler.runs if run.deployment_id == _DEPLOYMENT_B] + assert any( + a.started < b.finished and b.started < a.finished + for a in runs_a + for b in runs_b + ) + for store, _, deployment_id in stores: + with store.connect() as connection: + rows = connection.execute( + text("SELECT deployment_id, status::text FROM processing_state") + ).all() + assert {tuple(row) for row in rows} == {(deployment_id, "succeeded")} + finally: + second.dispose() + + +def _overlap(runs: list[_Run], first: PipelineStage, second: PipelineStage) -> bool: + return any( + a.started < b.finished and b.started < a.finished + for a in runs + if a.stage is first + for b in runs + if b.stage is second + ) diff --git a/src/tests/benchmarks/test_locomo_store_backup.py b/src/tests/benchmarks/test_locomo_store_backup.py index f84407f11..810173109 100644 --- a/src/tests/benchmarks/test_locomo_store_backup.py +++ b/src/tests/benchmarks/test_locomo_store_backup.py @@ -1038,13 +1038,11 @@ def test_shard_runner_guards_wipe_and_backs_up_before_scoring() -> None: "REMEMBERSTACK_OPENROUTER_INVALID_COMPLETION_CAPTURE_DIR=" "/var/lib/rememberstack/invalid-completions" ) in script - assert "extract_claim_workers=${LOCOMO_EXTRACT_CLAIM_WORKERS:-8}" in script - assert "ground_claim_workers=${LOCOMO_GROUND_CLAIM_WORKERS:-8}" in script - assert '--scale "worker-ground-claims=$ground_claim_workers"' in script + assert "llm_concurrency=${LOCOMO_LLM_CONCURRENCY:-40}" in script assert ( - "adjudicate_observation_workers=${LOCOMO_ADJUDICATE_OBSERVATION_WORKERS:-4}" - in script - ) + 'REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY="$llm_concurrency" \\\n' + ' "${compose[@]}" up --detach --wait --no-recreate' + ) in script assert ( "REMEMBERSTACK_BUILD_REVISION" in script[script.index("attest_worker_environment") :] diff --git a/src/tests/profiles/test_selfhost_profile.py b/src/tests/profiles/test_selfhost_profile.py index eae574f72..b01e1e482 100644 --- a/src/tests/profiles/test_selfhost_profile.py +++ b/src/tests/profiles/test_selfhost_profile.py @@ -16,7 +16,9 @@ from rememberstack.profiles.selfhost import _initialize_error_tracking from rememberstack.profiles.selfhost import _model_bindings from rememberstack.profiles.selfhost import _SUPPORTED_WORKER_STAGES +from rememberstack.profiles.selfhost import DEFAULT_WORKER_CONCURRENCY from rememberstack.profiles.selfhost import SelfHostSettings +from rememberstack.profiles.selfhost import WORKER_CLASSES _ROOT = Path(__file__).resolve().parents[3] @@ -89,6 +91,32 @@ def test_selfhost_composes_every_implemented_continuous_route() -> None: ) +def test_worker_classes_split_convert_from_the_rest_downstream_first() -> None: + """D145: convert alone; every other stage in one class, downstream first.""" + assert WORKER_CLASSES["convert"] == (PipelineStage.CONVERT,) + assert WORKER_CLASSES["llm"] == tuple(reversed(_SUPPORTED_WORKER_STAGES[1:])) + assert DEFAULT_WORKER_CONCURRENCY == {"convert": 1, "llm": 20} + + +@pytest.mark.parametrize( + "argv", + ( + ["worker", "--stage", "convert"], + ["worker", "--class", "embed"], + ["worker", "--class", "llm", "--concurrency", "0"], + ), +) +def test_worker_command_takes_a_class_and_a_positive_concurrency( + argv: list[str], +) -> None: + """The per-stage form is gone; bad classes and concurrency are refused.""" + from rememberstack.profiles.selfhost import main + + with pytest.raises(SystemExit) as exit_info: + main(argv) + assert exit_info.value.code == 2 + + def test_enum_only_and_fused_stages_are_not_advertised_as_workers() -> None: """A stage enum is not proof that an independently runnable handler exists.""" assert { @@ -103,12 +131,16 @@ def test_enum_only_and_fused_stages_are_not_advertised_as_workers() -> None: def test_compose_wires_the_exact_supported_worker_set_and_projection_job() -> None: """Keep deployable Compose wiring in lockstep with the executable profile.""" compose = (_ROOT / "compose.yaml").read_text(encoding="utf-8") - composed_stages = tuple( - PipelineStage(value) - for value in re.findall(r'command: \["worker", "--stage", "([^"]+)"\]', compose) + composed_classes = tuple( + re.findall( + r'command: \["worker", "--class", "([^"]+)", "--concurrency"', compose + ) ) - assert composed_stages == _SUPPORTED_WORKER_STAGES + assert composed_classes == tuple(WORKER_CLASSES) == ("convert", "llm") + served = [stage for stages in WORKER_CLASSES.values() for stage in stages] + assert sorted(served) == sorted(_SUPPORTED_WORKER_STAGES) + assert len(served) == len(set(served)) assert 'profiles: ["operations"]' in compose assert 'command: ["project", "--plane", "p3"]' in compose for name in ( @@ -165,17 +197,25 @@ def test_compose_restarts_long_running_services_but_not_one_shot_jobs() -> None: def test_postgres_connection_limit_covers_the_stock_stack_ceilings() -> None: - """API (general 15 + retrieval + graph pools) plus 16 per worker fits, with headroom.""" + """API pools plus each worker class's pool and LISTEN connection fit, with headroom.""" compose = (_ROOT / "compose.yaml").read_text(encoding="utf-8") limits = re.findall( r"- max_connections=\$\{REMEMBERSTACK_POSTGRES_MAX_CONNECTIONS:-(\d+)\}\n", compose, ) assert len(limits) == 1 - workers = len(re.findall(r'command: \["worker", "--stage", "[^"]+"\]', compose)) + concurrency = [ + int(value) + for value in re.findall( + r'"--concurrency", "\$\{REMEMBERSTACK_SELFHOST_[A-Z]+_CONCURRENCY:-(\d+)\}"', + compose, + ) + ] + assert concurrency == [DEFAULT_WORKER_CONCURRENCY[c] for c in WORKER_CLASSES] api = 15 + 4 + 4 # general pool (5 + 10 overflow), retrieval 4, graph 4 - ceiling = api + workers * (15 + 1) # general pool + one LISTEN connection - assert ceiling == 247 + # A worker's pool is (concurrency + 2) + concurrency overflow, plus LISTEN. + ceiling = api + sum(2 * n + 2 + 1 for n in concurrency) + assert ceiling == 71 assert int(limits[0]) >= ceiling + 50 @@ -455,7 +495,7 @@ def test_compose_hands_the_whole_env_file_to_every_engine_service() -> None: assert " env_file:\n - path: .env\n required: false\n" in anchor engine_services = re.findall(r"\n ([a-z0-9-]+):\n <<: \*app\n", services) assert {"setup", "api", "projections", "meter-receipts"} <= set(engine_services) - assert len(engine_services) == len(_SUPPORTED_WORKER_STAGES) + 4 + assert len(engine_services) == len(WORKER_CLASSES) + 4 def test_no_shared_deployment_id_ships() -> None: diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index e03e7d4ec..96c17faf1 100644 --- a/website/public/llms-full.txt +++ b/website/public/llms-full.txt @@ -5304,7 +5304,7 @@ that pages with a cursor keeps seeing the periods as they were when it started. Changing periods later also rechecks the dates of the facts the document -supports. After the call commits, the `worker-review-fact-windows` worker asks +supports. After the call commits, the `review_fact_windows` stage (in `worker-llm`) asks the model, once for each fact whose evidence's periods moved, whether the fact's dates still fit; it keeps them or replaces them with dates grounded in the claims, and records the decision in the fact's adjudication history. The @@ -6889,13 +6889,14 @@ connections as it needs them, up to these ceilings: | Process | General pool | Other | Ceiling | |---|---|---|---| | `api` | 15 (5 kept open, 10 more under load) | retrieval pool 4, graph pool 4 | 23 | -| Each `worker-…` | 15 (5 kept open, 10 more under load) | 1 held open to listen for new work | 16 | - -The ceilings of the default stack add up to 23 + 13 × 16 = 231, which fits -within 300 with room to spare. They are ceilings, not what a stack holds: -pools open connections only on demand. Nothing caps the total, though, so -budget against the ceilings when you add replicas or API processes: each -worker replica can add 16 connections and each API process 23, plus any +| `worker-llm` (20 at once) | 42 (22 kept open, 20 more under load) | 1 held open to listen for new work | 43 | +| `worker-convert` (1 at once) | 4 (3 kept open, 1 more under load) | 1 held open to listen for new work | 5 | + +A worker's ceiling is 2 × its concurrency + 3. The ceilings of the default +stack add up to 23 + 43 + 5 = 71, which fits within 300 with room to spare. +They are ceilings, not what a stack holds: pools open connections only on +demand. Nothing caps the total, though, so budget against the ceilings when +you raise concurrency or add worker containers or API processes, plus any increase in the retrieval and graph pool sizes. When the sum passes the limit, raise it by setting `REMEMBERSTACK_POSTGRES_MAX_CONNECTIONS` in `.env`; see [Scaling](https://remember.dev/docs/self-hosting/scaling#database-connections). @@ -6904,8 +6905,8 @@ Other configured bounds: | Bound | Default | |---|---| -| Containers started by `docker compose up` | 16: `postgres`, `object-store`, `setup` (exits), `api`, 13 workers | -| Items one worker process runs at once | 1 | +| Containers started by `docker compose up` | 6: `postgres`, `object-store`, `setup` (exits), `api`, `worker-convert`, `worker-llm` | +| Items one worker process runs at once | 1 for `worker-convert`, 20 for `worker-llm` | | Claims per second per worker process | 20, burst 20 | | Graph connection pool in the API | 4 connections, at most 2 graph queries at once | | Graph query `work_mem` | 16,384 KiB | @@ -7002,24 +7003,14 @@ RememberStack image, and starts everything in dependency order: | `object-store` | `server -s3` | [SeaweedFS](https://github.com/seaweedfs/seaweedfs), S3-compatible storage for original files, converted Markdown and snapshots. Reachable only by the other containers; no host port is published. | | `setup` | `setup` | One-shot: migrations, buckets, the deployment row, seed data. Runs again, harmlessly, on every `up`. | | `api` | `api` | The HTTP API on port 8000 inside the container, published on `127.0.0.1:REMEMBERSTACK_SELFHOST_API_PORT`. | -| `worker-convert` | `worker --stage convert` | Turns an uploaded file into Markdown using the configured [converter](https://remember.dev/docs/self-hosting/converters). | -| `worker-structure` | `worker --stage structure` | Finds the document's sections and writes section summaries. | -| `worker-crossref` | `worker --stage crossref` | Writes the references a caller supplied for a version, after checking them against the version's sections. See [Versions in force](https://remember.dev/docs/guides/versions-in-force#supply-references). | -| `worker-chunk` | `worker --stage chunk` | Splits the document into chunks. | -| `worker-embed-chunk` | `worker --stage embed_chunk` | Embeds chunks for semantic search. | -| `worker-extract-claims` | `worker --stage extract_claims` | Reads each chunk and selects the sentences that state something. | -| `worker-ground-claims` | `worker --stage ground_claims` | Turns those sentences into claims (what the source said), each tied to its passage. | -| `worker-normalize-relations` | `worker --stage normalize_relations` | Resolves entities and turns claims into relations and facts. | -| `worker-adjudicate-observations` | `worker --stage adjudicate_observations` | Decides, entity by entity, whether a new statement confirms, contradicts or replaces a fact the memory holds. | -| `worker-adjudicate-supersession` | `worker --stage adjudicate_supersession` | Records the follow-up of those decisions for the version and refreshes affected entity profiles. | -| `worker-embed-claim` | `worker --stage embed_claim` | Embeds claims for semantic search. | -| `worker-reconcile` | `worker --stage reconcile` | Settles the version's lifecycle once the other stages are done. | -| `worker-review-fact-windows` | `worker --stage review_fact_windows` | Rechecks the dates of facts whose evidence comes from documents with declared periods, when those periods change. Idle unless you declare periods. See [Versions in force](https://remember.dev/docs/guides/versions-in-force#withdraw-an-edition). | -| `worker-label-relation` | `worker --stage label_relation` | Writes the searchable label of each relation and embeds facts for semantic search. | +| `worker-convert` | `worker --class convert` | Turns an uploaded file into Markdown using the configured [converter](https://remember.dev/docs/self-hosting/converters), one file at a time. | +| `worker-llm` | `worker --class llm` | Runs every other pipeline stage, up to 20 items at once: finds sections and writes summaries, checks supplied references, splits documents into chunks, embeds them, selects the sentences that state something and turns them into claims, resolves entities into relations and facts, decides whether a new statement confirms, contradicts or replaces a fact, embeds claims and facts, writes relation labels, settles each version's lifecycle, and rechecks fact dates when declared periods change. | | `projections` | `project --plane p3` | Profile `operations` only. Builds a [filesystem view](https://remember.dev/docs/self-hosting/filesystem-views) snapshot on demand. | -Each worker handles one stage and wakes when new work for that stage is -committed. [The pipeline and readiness](https://remember.dev/docs/concepts/pipeline) explains +Each worker wakes when new work for one of its stages is committed. The +`llm` worker finishes items further along the pipeline before it starts +new ones, so a large upload does not hold back documents that are nearly +done. [The pipeline and readiness](https://remember.dev/docs/concepts/pipeline) explains what the stages produce. ## 4. Check that it is healthy @@ -7076,7 +7067,7 @@ a query sent straight away may find nothing yet. how to wait for a version. To watch the work happen: ```bash -docker compose logs -f worker-extract-claims worker-normalize-relations +docker compose logs -f worker-llm ``` **Note:** @@ -8214,7 +8205,7 @@ RememberStack publishes no throughput figures: how many documents per hour, or queries per second, a machine handles depends mostly on your model provider and corpus. What exists are explicit bounds on every process, so a busy deployment slows down or refuses work. The one budget you keep -yourself is PostgreSQL's connection limit, once you add replicas. This +yourself is PostgreSQL's connection limit, once you raise concurrency or add containers. This page lists those bounds and how to move them. The model provider is usually the first limit you meet. Most pipeline @@ -8223,10 +8214,14 @@ own rate limits apply to your account. ## Workers -Each pipeline stage runs in its own container. A worker process claims one -item of work at a time from PostgreSQL, runs it, and claims the next. It -wakes on a notification when new work is committed and also polls in case a -notification was missed. +The pipeline runs in two worker containers. `worker-convert` converts +uploaded files one at a time, so its memory stays bounded by the largest +file you accept. `worker-llm` runs every other stage with up to 20 items in +flight at once, because those stages spend most of their time waiting on +model calls. Both claim work from PostgreSQL, wake on a notification when +new work is committed, and also poll in case a notification was missed. The +`llm` worker takes items further along the pipeline before new ones, and +live work before [backfill](https://remember.dev/docs/self-hosting/operating) work. | Variable | Default | Meaning | |---|---|---| @@ -8236,26 +8231,38 @@ notification was missed. | `REMEMBERSTACK_SELFHOST_WORKER_SESSION_S` | `3600` | Length of one worker session in seconds; the worker then starts the next one. | Set them in `.env`. Lowering the rate is the way to stay under a provider's rate limit; the -rate applies per process, so it multiplies with replicas. +rate applies per process, so it multiplies with containers. + +### More items in flight + +Raise a worker's concurrency in `.env` and recreate it: + +| Variable | Default | Meaning | +|---|---|---| +| `REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY` | `20` | Items `worker-llm` runs at once. | +| `REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY` | `1` | Files `worker-convert` converts at once. Each conversion can take as much memory as the file needs. | -### More replicas of a stage +```bash +echo 'REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY=40' >> .env +docker compose up -d worker-llm +``` -Items are claimed with `SELECT … FOR UPDATE SKIP LOCKED`, so several -processes can serve the same stage without taking the same item. Add -replicas of the stage that is behind: +Items are claimed with `SELECT … FOR UPDATE SKIP LOCKED`, so you can also +run more than one container of a worker without two taking the same item: ```bash -docker compose up -d --scale worker-extract-claims=3 --scale worker-normalize-relations=2 +docker compose up -d --scale worker-llm=2 ``` -To find the stage that is behind, look at the pending counts per stage in +To see which stage is behind, look at the pending counts per stage in `remember ops inspect` ([Operating the pipeline](https://remember.dev/docs/self-hosting/operating#inspect-the-pipeline)). The claim-heavy stages (`extract_claims`, `ground_claims`, `normalize_relations`, `adjudicate_observations`) make the most model calls -per document. +per document. A higher concurrency also means more calls at once to your +model provider, whose rate limits still apply. -Every replica holds its own database connections; see -[Database connections](#database-connections) before adding many. +Every container holds its own database connections, and more items in +flight need more of them; see [Database connections](#database-connections). ## Database connections @@ -8267,16 +8274,17 @@ size itself against that limit. The ceilings per process are: | Process | Ceiling | Made of | |---|---|---| | `api` | 23 | General pool 15 (5 kept open, 10 more under load), retrieval pool 4, graph pool 4 | -| Each `worker-…` replica | 16 | General pool 15, plus 1 connection that listens for new work | +| Each worker container | 2 × concurrency + 3 | General pool of concurrency + 2 kept open and as many more under load (one task can briefly need two connections), plus 1 connection that listens for new work. `worker-llm` at 20: 43; `worker-convert` at 1: 5 | -The general pool's size is fixed. The retrieval and graph pools follow +The API's general pool size is fixed. The retrieval and graph pools follow `REMEMBERSTACK_SELFHOST_RETRIEVAL_POOL_SIZE` and `REMEMBERSTACK_SELFHOST_GRAPH_POOL_SIZE` (see [Retrieval and graph queries](#retrieval-and-graph-queries)). Pools open connections only on demand, so a running stack holds fewer than -the sum of its ceilings. The default stack's ceilings add up to 231 (23 + -13 × 16), within the default limit of 300. When you add replicas or API +the sum of its ceilings. The default stack's ceilings add up to 71 (23 + +43 + 5), within the default limit of 300. When you raise concurrency or add +containers or API processes, keep the sum of their ceilings under the limit, and when PostgreSQL refuses connections (`too many clients already` in the logs), raise it in `.env` and restart PostgreSQL: @@ -8843,14 +8851,14 @@ stage before. Check where work is piling up: ```bash docker compose exec -T api \ remember ops inspect --deployment "$DEPLOYMENT_ID" | python3 -m json.tool -docker compose logs -f --since 10m worker-extract-claims worker-normalize-relations +docker compose logs -f --since 10m worker-llm ``` | Sign | Cause | Fix | |---|---|---| -| A large `pending` count on one stage in `routes` | That stage is the bottleneck. | Add replicas: `docker compose up -d --scale worker-extract-claims=3`. See [Scaling](https://remember.dev/docs/self-hosting/scaling#more-replicas-of-a-stage). | -| Log lines with `overloaded (429)` | OpenRouter or a provider behind it is rate-limiting you. More replicas make it worse. | Lower the worker rate, or set a provider order; see [Scaling](https://remember.dev/docs/self-hosting/scaling) and [Models and providers](https://remember.dev/docs/self-hosting/models#openrouter-routing-and-limits). | -| `pending` counts that do not move, no log activity | The worker for that stage is not running, or a budget parked the work. | `docker compose ps -a`; [Work parked by a spend budget](#work-parked-by-a-spend-budget). | +| A large `pending` count on one stage in `routes` | That stage is the bottleneck. | Raise `REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY` (or `REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY` for `convert`). See [Scaling](https://remember.dev/docs/self-hosting/scaling#more-items-in-flight). | +| Log lines with `overloaded (429)` | OpenRouter or a provider behind it is rate-limiting you. More items in flight make it worse. | Lower the worker rate, or set a provider order; see [Scaling](https://remember.dev/docs/self-hosting/scaling) and [Models and providers](https://remember.dev/docs/self-hosting/models#openrouter-routing-and-limits). | +| `pending` counts that do not move, no log activity | The worker for that stage (`worker-convert` for `convert`, `worker-llm` for the rest) is not running, or a budget parked the work. | `docker compose ps -a`; [Work parked by a spend budget](#work-parked-by-a-spend-budget). | | Every call slow | Reasoning models spend time and tokens thinking. | Lower `REMEMBERSTACK_OPENROUTER_REASONING_EFFORT_MAP` for the small models; see [Models and providers](https://remember.dev/docs/self-hosting/models#openrouter-routing-and-limits). | ## Model key and provider errors @@ -8866,7 +8874,7 @@ out of credit) in the traceback. After three attempts, a few seconds apart, the items dead-letter. ```bash -docker compose logs --since 30m worker-structure worker-extract-claims | grep -i openrouter +docker compose logs --since 30m worker-llm | grep -i openrouter ``` Fix: put a valid key in `.env`, apply it with `docker compose up -d`, then @@ -9017,7 +9025,7 @@ Every container writes to standard output, which Docker keeps: ```bash docker compose logs -f api -docker compose logs -f worker-extract-claims +docker compose logs -f worker-llm docker compose logs --since 1h ``` @@ -18267,7 +18275,7 @@ orchestration. |---|---| | `setup` | Applies database migrations and prepares the deployment. Runs once; the other services start after it succeeds. | | `api` | The HTTP API. Listens on `REMEMBERSTACK_SELFHOST_API_HOST` (default `0.0.0.0`) and `REMEMBERSTACK_SELFHOST_API_PORT` (default `8000`). This is the image's default command. | -| `worker --stage STAGE` | One pipeline worker. `STAGE` is one of `convert`, `structure`, `chunk`, `embed_chunk`, `extract_claims`, `ground_claims`, `normalize_relations`, `adjudicate_observations`, `adjudicate_supersession`, `embed_claim`, `reconcile`, `label_relation`. Run one process per stage. | +| `worker --class CLASS [--concurrency N]` | One pipeline worker for a class of stages. `convert` runs the `convert` stage; `llm` runs every other stage (`structure`, `crossref`, `chunk`, `embed_chunk`, `extract_claims`, `ground_claims`, `normalize_relations`, `adjudicate_observations`, `adjudicate_supersession`, `embed_claim`, `reconcile`, `label_relation`, `review_fact_windows`). `N` is how many items it runs at once (default `1` for `convert`, `20` for `llm`). Run one process per class; add processes to add capacity. | | `project --plane p3` | Builds the filesystem view snapshot once. In `compose.yaml` it belongs to the `operations` profile. | | `mounts --root PATH [--raw-root PATH] [--artifacts-root PATH]` | Publishes the latest snapshot under a local directory. | diff --git a/website/public/llms.txt b/website/public/llms.txt index f3ee871bb..f543972d7 100644 --- a/website/public/llms.txt +++ b/website/public/llms.txt @@ -52,7 +52,7 @@ Agents: resolve entities first (`resolve_entity`), then ask for facts (`facts_co - [Models and providers](https://remember.dev/docs/self-hosting/models): Which model each pipeline step uses, how to change it, how RememberStack routes calls through OpenRouter, and what changing the embedding model does. - [File formats and converters](https://remember.dev/docs/self-hosting/converters): Which file types a self-hosted RememberStack accepts, how to route more types to converters, and what happens to a file no converter accepts. - [Authentication and scopes](https://remember.dev/docs/self-hosting/authentication): Protect a self-hosted RememberStack API with a shared secret or signed keys, understand read, ingest and write scopes, and allow browser origins. -- [Scaling](https://remember.dev/docs/self-hosting/scaling): The bounds a self-hosted RememberStack runs within — worker claim rates, replicas per stage, connection pools for retrieval and graph queries, API admission limits, and SQL query limits. +- [Scaling](https://remember.dev/docs/self-hosting/scaling): The bounds a self-hosted RememberStack runs within — worker concurrency and claim rates, connection pools for retrieval and graph queries, API admission limits, and SQL query limits. - [Operating the pipeline](https://remember.dev/docs/self-hosting/operating): Inspect a self-hosted RememberStack pipeline, replay failed work, release parked conversions, set spend budgets, and repair the graph catalog. - [Troubleshooting](https://remember.dev/docs/self-hosting/troubleshooting): Symptom, first check and fix for a self-hosted RememberStack that does not start, refuses requests, never finishes a document, or gives answers you did not expect. - [Observability](https://remember.dev/docs/self-hosting/observability): What a self-hosted RememberStack logs, how to send its errors to Sentry or a compatible service, and how to export what it spent on models. diff --git a/website/src/app/docs/guides/versions-in-force/page.mdx b/website/src/app/docs/guides/versions-in-force/page.mdx index 559f0f641..fc44e70d6 100644 --- a/website/src/app/docs/guides/versions-in-force/page.mdx +++ b/website/src/app/docs/guides/versions-in-force/page.mdx @@ -215,7 +215,7 @@ that pages with a cursor keeps seeing the periods as they were when it started. Changing periods later also rechecks the dates of the facts the document -supports. After the call commits, the `worker-review-fact-windows` worker asks +supports. After the call commits, the `review_fact_windows` stage (in `worker-llm`) asks the model, once for each fact whose evidence's periods moved, whether the fact's dates still fit; it keeps them or replaces them with dates grounded in the claims, and records the decision in the fact's adjudication history. The diff --git a/website/src/app/docs/reference/cli/page.mdx b/website/src/app/docs/reference/cli/page.mdx index 0a4b4a83c..db1e212a5 100644 --- a/website/src/app/docs/reference/cli/page.mdx +++ b/website/src/app/docs/reference/cli/page.mdx @@ -664,7 +664,7 @@ orchestration. |---|---| | `setup` | Applies database migrations and prepares the deployment. Runs once; the other services start after it succeeds. | | `api` | The HTTP API. Listens on `REMEMBERSTACK_SELFHOST_API_HOST` (default `0.0.0.0`) and `REMEMBERSTACK_SELFHOST_API_PORT` (default `8000`). This is the image's default command. | -| `worker --stage STAGE` | One pipeline worker. `STAGE` is one of `convert`, `structure`, `chunk`, `embed_chunk`, `extract_claims`, `ground_claims`, `normalize_relations`, `adjudicate_observations`, `adjudicate_supersession`, `embed_claim`, `reconcile`, `label_relation`. Run one process per stage. | +| `worker --class CLASS [--concurrency N]` | One pipeline worker for a class of stages. `convert` runs the `convert` stage; `llm` runs every other stage (`structure`, `crossref`, `chunk`, `embed_chunk`, `extract_claims`, `ground_claims`, `normalize_relations`, `adjudicate_observations`, `adjudicate_supersession`, `embed_claim`, `reconcile`, `label_relation`, `review_fact_windows`). `N` is how many items it runs at once (default `1` for `convert`, `20` for `llm`). Run one process per class; add processes to add capacity. | | `project --plane p3` | Builds the filesystem view snapshot once. In `compose.yaml` it belongs to the `operations` profile. | | `mounts --root PATH [--raw-root PATH] [--artifacts-root PATH]` | Publishes the latest snapshot under a local directory. | diff --git a/website/src/app/docs/self-hosting/install/page.mdx b/website/src/app/docs/self-hosting/install/page.mdx index dfc6abb8e..afda2389c 100644 --- a/website/src/app/docs/self-hosting/install/page.mdx +++ b/website/src/app/docs/self-hosting/install/page.mdx @@ -92,24 +92,14 @@ RememberStack image, and starts everything in dependency order: | `object-store` | `server -s3` | [SeaweedFS](https://github.com/seaweedfs/seaweedfs), S3-compatible storage for original files, converted Markdown and snapshots. Reachable only by the other containers; no host port is published. | | `setup` | `setup` | One-shot: migrations, buckets, the deployment row, seed data. Runs again, harmlessly, on every `up`. | | `api` | `api` | The HTTP API on port 8000 inside the container, published on `127.0.0.1:REMEMBERSTACK_SELFHOST_API_PORT`. | -| `worker-convert` | `worker --stage convert` | Turns an uploaded file into Markdown using the configured [converter](/docs/self-hosting/converters). | -| `worker-structure` | `worker --stage structure` | Finds the document's sections and writes section summaries. | -| `worker-crossref` | `worker --stage crossref` | Writes the references a caller supplied for a version, after checking them against the version's sections. See [Versions in force](/docs/guides/versions-in-force#supply-references). | -| `worker-chunk` | `worker --stage chunk` | Splits the document into chunks. | -| `worker-embed-chunk` | `worker --stage embed_chunk` | Embeds chunks for semantic search. | -| `worker-extract-claims` | `worker --stage extract_claims` | Reads each chunk and selects the sentences that state something. | -| `worker-ground-claims` | `worker --stage ground_claims` | Turns those sentences into claims (what the source said), each tied to its passage. | -| `worker-normalize-relations` | `worker --stage normalize_relations` | Resolves entities and turns claims into relations and facts. | -| `worker-adjudicate-observations` | `worker --stage adjudicate_observations` | Decides, entity by entity, whether a new statement confirms, contradicts or replaces a fact the memory holds. | -| `worker-adjudicate-supersession` | `worker --stage adjudicate_supersession` | Records the follow-up of those decisions for the version and refreshes affected entity profiles. | -| `worker-embed-claim` | `worker --stage embed_claim` | Embeds claims for semantic search. | -| `worker-reconcile` | `worker --stage reconcile` | Settles the version's lifecycle once the other stages are done. | -| `worker-review-fact-windows` | `worker --stage review_fact_windows` | Rechecks the dates of facts whose evidence comes from documents with declared periods, when those periods change. Idle unless you declare periods. See [Versions in force](/docs/guides/versions-in-force#withdraw-an-edition). | -| `worker-label-relation` | `worker --stage label_relation` | Writes the searchable label of each relation and embeds facts for semantic search. | +| `worker-convert` | `worker --class convert` | Turns an uploaded file into Markdown using the configured [converter](/docs/self-hosting/converters), one file at a time. | +| `worker-llm` | `worker --class llm` | Runs every other pipeline stage, up to 20 items at once: finds sections and writes summaries, checks supplied references, splits documents into chunks, embeds them, selects the sentences that state something and turns them into claims, resolves entities into relations and facts, decides whether a new statement confirms, contradicts or replaces a fact, embeds claims and facts, writes relation labels, settles each version's lifecycle, and rechecks fact dates when declared periods change. | | `projections` | `project --plane p3` | Profile `operations` only. Builds a [filesystem view](/docs/self-hosting/filesystem-views) snapshot on demand. | -Each worker handles one stage and wakes when new work for that stage is -committed. [The pipeline and readiness](/docs/concepts/pipeline) explains +Each worker wakes when new work for one of its stages is committed. The +`llm` worker finishes items further along the pipeline before it starts +new ones, so a large upload does not hold back documents that are nearly +done. [The pipeline and readiness](/docs/concepts/pipeline) explains what the stages produce. ## 4. Check that it is healthy @@ -166,7 +156,7 @@ a query sent straight away may find nothing yet. how to wait for a version. To watch the work happen: ```bash -docker compose logs -f worker-extract-claims worker-normalize-relations +docker compose logs -f worker-llm ``` diff --git a/website/src/app/docs/self-hosting/observability/page.mdx b/website/src/app/docs/self-hosting/observability/page.mdx index 6760ff7b6..121b9fd5c 100644 --- a/website/src/app/docs/self-hosting/observability/page.mdx +++ b/website/src/app/docs/self-hosting/observability/page.mdx @@ -18,7 +18,7 @@ Every container writes to standard output, which Docker keeps: ```bash docker compose logs -f api -docker compose logs -f worker-extract-claims +docker compose logs -f worker-llm docker compose logs --since 1h ``` diff --git a/website/src/app/docs/self-hosting/requirements/page.mdx b/website/src/app/docs/self-hosting/requirements/page.mdx index 014fa9395..5d421f403 100644 --- a/website/src/app/docs/self-hosting/requirements/page.mdx +++ b/website/src/app/docs/self-hosting/requirements/page.mdx @@ -179,13 +179,14 @@ connections as it needs them, up to these ceilings: | Process | General pool | Other | Ceiling | |---|---|---|---| | `api` | 15 (5 kept open, 10 more under load) | retrieval pool 4, graph pool 4 | 23 | -| Each `worker-…` | 15 (5 kept open, 10 more under load) | 1 held open to listen for new work | 16 | - -The ceilings of the default stack add up to 23 + 13 × 16 = 231, which fits -within 300 with room to spare. They are ceilings, not what a stack holds: -pools open connections only on demand. Nothing caps the total, though, so -budget against the ceilings when you add replicas or API processes: each -worker replica can add 16 connections and each API process 23, plus any +| `worker-llm` (20 at once) | 42 (22 kept open, 20 more under load) | 1 held open to listen for new work | 43 | +| `worker-convert` (1 at once) | 4 (3 kept open, 1 more under load) | 1 held open to listen for new work | 5 | + +A worker's ceiling is 2 × its concurrency + 3. The ceilings of the default +stack add up to 23 + 43 + 5 = 71, which fits within 300 with room to spare. +They are ceilings, not what a stack holds: pools open connections only on +demand. Nothing caps the total, though, so budget against the ceilings when +you raise concurrency or add worker containers or API processes, plus any increase in the retrieval and graph pool sizes. When the sum passes the limit, raise it by setting `REMEMBERSTACK_POSTGRES_MAX_CONNECTIONS` in `.env`; see [Scaling](/docs/self-hosting/scaling#database-connections). @@ -194,8 +195,8 @@ Other configured bounds: | Bound | Default | |---|---| -| Containers started by `docker compose up` | 16: `postgres`, `object-store`, `setup` (exits), `api`, 13 workers | -| Items one worker process runs at once | 1 | +| Containers started by `docker compose up` | 6: `postgres`, `object-store`, `setup` (exits), `api`, `worker-convert`, `worker-llm` | +| Items one worker process runs at once | 1 for `worker-convert`, 20 for `worker-llm` | | Claims per second per worker process | 20, burst 20 | | Graph connection pool in the API | 4 connections, at most 2 graph queries at once | | Graph query `work_mem` | 16,384 KiB | diff --git a/website/src/app/docs/self-hosting/scaling/page.mdx b/website/src/app/docs/self-hosting/scaling/page.mdx index b75a0f117..706e5aab5 100644 --- a/website/src/app/docs/self-hosting/scaling/page.mdx +++ b/website/src/app/docs/self-hosting/scaling/page.mdx @@ -1,6 +1,6 @@ export const metadata = { title: "Scaling", - description: "The bounds a self-hosted RememberStack runs within \u2014 worker claim rates, replicas per stage, connection pools for retrieval and graph queries, API admission limits, and SQL query limits.", + description: "The bounds a self-hosted RememberStack runs within \u2014 worker concurrency and claim rates, connection pools for retrieval and graph queries, API admission limits, and SQL query limits.", }; # Scaling @@ -11,7 +11,7 @@ RememberStack publishes no throughput figures: how many documents per hour, or queries per second, a machine handles depends mostly on your model provider and corpus. What exists are explicit bounds on every process, so a busy deployment slows down or refuses work. The one budget you keep -yourself is PostgreSQL's connection limit, once you add replicas. This +yourself is PostgreSQL's connection limit, once you raise concurrency or add containers. This page lists those bounds and how to move them. The model provider is usually the first limit you meet. Most pipeline @@ -20,10 +20,14 @@ own rate limits apply to your account. ## Workers -Each pipeline stage runs in its own container. A worker process claims one -item of work at a time from PostgreSQL, runs it, and claims the next. It -wakes on a notification when new work is committed and also polls in case a -notification was missed. +The pipeline runs in two worker containers. `worker-convert` converts +uploaded files one at a time, so its memory stays bounded by the largest +file you accept. `worker-llm` runs every other stage with up to 20 items in +flight at once, because those stages spend most of their time waiting on +model calls. Both claim work from PostgreSQL, wake on a notification when +new work is committed, and also poll in case a notification was missed. The +`llm` worker takes items further along the pipeline before new ones, and +live work before [backfill](/docs/self-hosting/operating) work. | Variable | Default | Meaning | |---|---|---| @@ -33,26 +37,38 @@ notification was missed. | `REMEMBERSTACK_SELFHOST_WORKER_SESSION_S` | `3600` | Length of one worker session in seconds; the worker then starts the next one. | Set them in `.env`. Lowering the rate is the way to stay under a provider's rate limit; the -rate applies per process, so it multiplies with replicas. +rate applies per process, so it multiplies with containers. -### More replicas of a stage +### More items in flight -Items are claimed with `SELECT … FOR UPDATE SKIP LOCKED`, so several -processes can serve the same stage without taking the same item. Add -replicas of the stage that is behind: +Raise a worker's concurrency in `.env` and recreate it: + +| Variable | Default | Meaning | +|---|---|---| +| `REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY` | `20` | Items `worker-llm` runs at once. | +| `REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY` | `1` | Files `worker-convert` converts at once. Each conversion can take as much memory as the file needs. | + +```bash +echo 'REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY=40' >> .env +docker compose up -d worker-llm +``` + +Items are claimed with `SELECT … FOR UPDATE SKIP LOCKED`, so you can also +run more than one container of a worker without two taking the same item: ```bash -docker compose up -d --scale worker-extract-claims=3 --scale worker-normalize-relations=2 +docker compose up -d --scale worker-llm=2 ``` -To find the stage that is behind, look at the pending counts per stage in +To see which stage is behind, look at the pending counts per stage in `remember ops inspect` ([Operating the pipeline](/docs/self-hosting/operating#inspect-the-pipeline)). The claim-heavy stages (`extract_claims`, `ground_claims`, `normalize_relations`, `adjudicate_observations`) make the most model calls -per document. +per document. A higher concurrency also means more calls at once to your +model provider, whose rate limits still apply. -Every replica holds its own database connections; see -[Database connections](#database-connections) before adding many. +Every container holds its own database connections, and more items in +flight need more of them; see [Database connections](#database-connections). ## Database connections @@ -64,16 +80,17 @@ size itself against that limit. The ceilings per process are: | Process | Ceiling | Made of | |---|---|---| | `api` | 23 | General pool 15 (5 kept open, 10 more under load), retrieval pool 4, graph pool 4 | -| Each `worker-…` replica | 16 | General pool 15, plus 1 connection that listens for new work | +| Each worker container | 2 × concurrency + 3 | General pool of concurrency + 2 kept open and as many more under load (one task can briefly need two connections), plus 1 connection that listens for new work. `worker-llm` at 20: 43; `worker-convert` at 1: 5 | -The general pool's size is fixed. The retrieval and graph pools follow +The API's general pool size is fixed. The retrieval and graph pools follow `REMEMBERSTACK_SELFHOST_RETRIEVAL_POOL_SIZE` and `REMEMBERSTACK_SELFHOST_GRAPH_POOL_SIZE` (see [Retrieval and graph queries](#retrieval-and-graph-queries)). Pools open connections only on demand, so a running stack holds fewer than -the sum of its ceilings. The default stack's ceilings add up to 231 (23 + -13 × 16), within the default limit of 300. When you add replicas or API +the sum of its ceilings. The default stack's ceilings add up to 71 (23 + +43 + 5), within the default limit of 300. When you raise concurrency or add +containers or API processes, keep the sum of their ceilings under the limit, and when PostgreSQL refuses connections (`too many clients already` in the logs), raise it in `.env` and restart PostgreSQL: diff --git a/website/src/app/docs/self-hosting/troubleshooting/page.mdx b/website/src/app/docs/self-hosting/troubleshooting/page.mdx index 8440e3e96..2e3701554 100644 --- a/website/src/app/docs/self-hosting/troubleshooting/page.mdx +++ b/website/src/app/docs/self-hosting/troubleshooting/page.mdx @@ -303,14 +303,14 @@ stage before. Check where work is piling up: ```bash docker compose exec -T api \ remember ops inspect --deployment "$DEPLOYMENT_ID" | python3 -m json.tool -docker compose logs -f --since 10m worker-extract-claims worker-normalize-relations +docker compose logs -f --since 10m worker-llm ``` | Sign | Cause | Fix | |---|---|---| -| A large `pending` count on one stage in `routes` | That stage is the bottleneck. | Add replicas: `docker compose up -d --scale worker-extract-claims=3`. See [Scaling](/docs/self-hosting/scaling#more-replicas-of-a-stage). | -| Log lines with `overloaded (429)` | OpenRouter or a provider behind it is rate-limiting you. More replicas make it worse. | Lower the worker rate, or set a provider order; see [Scaling](/docs/self-hosting/scaling) and [Models and providers](/docs/self-hosting/models#openrouter-routing-and-limits). | -| `pending` counts that do not move, no log activity | The worker for that stage is not running, or a budget parked the work. | `docker compose ps -a`; [Work parked by a spend budget](#work-parked-by-a-spend-budget). | +| A large `pending` count on one stage in `routes` | That stage is the bottleneck. | Raise `REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY` (or `REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY` for `convert`). See [Scaling](/docs/self-hosting/scaling#more-items-in-flight). | +| Log lines with `overloaded (429)` | OpenRouter or a provider behind it is rate-limiting you. More items in flight make it worse. | Lower the worker rate, or set a provider order; see [Scaling](/docs/self-hosting/scaling) and [Models and providers](/docs/self-hosting/models#openrouter-routing-and-limits). | +| `pending` counts that do not move, no log activity | The worker for that stage (`worker-convert` for `convert`, `worker-llm` for the rest) is not running, or a budget parked the work. | `docker compose ps -a`; [Work parked by a spend budget](#work-parked-by-a-spend-budget). | | Every call slow | Reasoning models spend time and tokens thinking. | Lower `REMEMBERSTACK_OPENROUTER_REASONING_EFFORT_MAP` for the small models; see [Models and providers](/docs/self-hosting/models#openrouter-routing-and-limits). | ## Model key and provider errors @@ -326,7 +326,7 @@ out of credit) in the traceback. After three attempts, a few seconds apart, the items dead-letter. ```bash -docker compose logs --since 30m worker-structure worker-extract-claims | grep -i openrouter +docker compose logs --since 30m worker-llm | grep -i openrouter ``` Fix: put a valid key in `.env`, apply it with `docker compose up -d`, then diff --git a/website/src/app/docs/start/choose/page.cloud.mdx b/website/src/app/docs/start/choose/page.cloud.mdx index 9f5f6b962..4cdbccab6 100644 --- a/website/src/app/docs/start/choose/page.cloud.mdx +++ b/website/src/app/docs/start/choose/page.cloud.mdx @@ -36,8 +36,8 @@ needs the pgvector, pg_textsearch, pg_partman, pg_trgm, fuzzystrmatch, unaccent, btree_gist and pgcrypto extensions. The Compose file builds that database for you. -Each document passes through the pipeline's stages, and each stage runs as its own -worker. You provide model access for them, keep them healthy, and upgrade +Each document passes through the pipeline's stages, which run in two worker +containers. You provide model access for them, keep them healthy, and upgrade them together. You are responsible for authentication, TLS, backups and monitoring. [Requirements](/docs/self-hosting/requirements) lists every piece. From 09f52defe5db96395f5a96752c55eb559f8bd1a2 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 6 Nov 2026 16:51:56 +0100 Subject: [PATCH 2/7] fix(worker): only a real claim wakes another slot A route the probe lists but no slot can claim (a held window-review route) made slots wake each other in a loop. Worker.run_one now takes an on_claimed callback, called between the claim and the handler, and the claimed-attempt execution is its own small method, run_claimed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- src/rememberstack/adapters/selfhost/queue.py | 17 ++++--- src/rememberstack/workers/base.py | 28 ++++++++--- .../adapters/test_selfhost_worker_classes.py | 47 +++++++++++++++++++ 3 files changed, 78 insertions(+), 14 deletions(-) diff --git a/src/rememberstack/adapters/selfhost/queue.py b/src/rememberstack/adapters/selfhost/queue.py index 26f1d61d2..db5b45100 100644 --- a/src/rememberstack/adapters/selfhost/queue.py +++ b/src/rememberstack/adapters/selfhost/queue.py @@ -94,7 +94,7 @@ class SelfHostWorkerLoop: downstream stages first, so work already in the pipeline drains before new uploads take the slots). ``concurrency`` slots each run one task at a time in their own thread. The calling thread sleeps on LISTEN with a slow - fallback poll; every wake-up, and every claim that found work, wakes one + fallback poll; every wake-up, and every successful claim, wakes one idle slot, so idle slots look for work one at a time instead of all at once. The calling thread also sweeps expired claims (D144) at most once per fallback-poll interval. @@ -215,14 +215,17 @@ def _run_next(self) -> RunResult | None: """Claim and run the first due unit of work in route order, if any.""" if not self._bucket.try_acquire(): return None - due = self._ledger.due_routes( + for stage, lane in self._ledger.due_routes( deployment_id=self._deployment_id, routes=self._routes - ) - if due: - self._signal() # there may be more: let one idle slot look too - for stage, lane in due: + ): result = self._worker.run_one( - deployment_id=self._deployment_id, stage=stage, lane=lane + deployment_id=self._deployment_id, + stage=stage, + lane=lane, + # A claim succeeded, so more may be due: let one idle slot + # look too. Only real claims wake slots, so a route the probe + # lists but nobody can claim never keeps slots spinning. + on_claimed=self._signal, ) if result.outcome is not RunResultOutcome.NO_WORK: return result diff --git a/src/rememberstack/workers/base.py b/src/rememberstack/workers/base.py index 8322e93d1..e88bfe7db 100644 --- a/src/rememberstack/workers/base.py +++ b/src/rememberstack/workers/base.py @@ -6,6 +6,7 @@ either retried with backoff or dead-lettered — it never disappears. """ +from collections.abc import Callable from datetime import datetime from datetime import UTC import logging @@ -329,18 +330,16 @@ def run_one( stage: PipelineStage, lane: ProcessingLane | None, processing_id: UUID | None = None, + on_claimed: Callable[[], None] | None = None, ) -> RunResult: """Claim and run at most one due unit of work on the route. ``processing_id`` restricts the claim to that one row (D147). - - This is the worker's single catch-to-log boundary (core value 6): the - full traceback is logged and recorded on the row; a - `NonRetryableHandlerError` dead-letters immediately, anything else - retries with backoff until the attempt limit dead-letters it. + ``on_claimed`` is called after a claim succeeds and before the handler + runs (a concurrent worker loop uses it to wake another slot). """ started_ns = time.monotonic_ns() - handler = self._registry.handler_for(stage=stage) # before any claim: + self._registry.handler_for(stage=stage) # before any claim: # an unregistered stage must never strand a claimed row as running. claimed = self._ledger.claim_one( deployment_id=deployment_id, @@ -374,6 +373,19 @@ def run_one( processing_id=claimed.processing_id, outcome=RunResultOutcome.BUDGET_PARKED, ) + if on_claimed is not None: + on_claimed() + return self.run_claimed(claimed=claimed, started_ns=started_ns) + + def run_claimed(self, *, claimed: ClaimedWork, started_ns: int) -> RunResult: + """Run one claimed attempt and record how it ended. + + This is the worker's single catch-to-log boundary (core value 6): the + full traceback is logged and recorded on the row; a + `NonRetryableHandlerError` dead-letters immediately, anything else + retries with backoff until the attempt limit dead-letters it. + """ + handler = self._registry.handler_for(stage=claimed.stage) meter = _LedgerCostMeter(ledger=self._ledger, work=claimed) try: with _LeaseRenewal(ledger=self._ledger, work=claimed): @@ -465,7 +477,9 @@ def run_one( self._queue.announce( processing_id=claimed.processing_id, route_snapshot=QueueRoute( - deployment_id=deployment_id, stage=stage, lane=lane + deployment_id=claimed.deployment_id, + stage=claimed.stage, + lane=claimed.lane, ), not_before_snapshot=retry_at, ) diff --git a/src/tests/adapters/test_selfhost_worker_classes.py b/src/tests/adapters/test_selfhost_worker_classes.py index c7a5032e8..4a1846507 100644 --- a/src/tests/adapters/test_selfhost_worker_classes.py +++ b/src/tests/adapters/test_selfhost_worker_classes.py @@ -297,6 +297,53 @@ def test_slots_run_tasks_of_several_stages_at_once( assert _overlap(handler.runs, _UPSTREAM, _DOWNSTREAM) +class _HeldLedger(WorkLedger): + """Lists due work but never hands it out, like a held review route.""" + + def __init__(self, *, engine: Engine) -> None: + super().__init__( + engine=engine, + settings=WorkLedgerSettings( + retry_backoff_base_s=0.0, retry_backoff_max_s=0.0 + ), + ) + self.probes = 0 + + def due_routes( + self, **kwargs: object + ) -> tuple[tuple[PipelineStage, ProcessingLane], ...]: + self.probes += 1 + return super().due_routes(**kwargs) # type: ignore[arg-type] + + def claim_one(self, **_: object) -> None: # type: ignore[override] + return None + + +def test_work_that_is_listed_but_cannot_be_claimed_does_not_spin_the_slots( + database_url: str, engine: Engine +) -> None: + """Only real claims wake further slots; otherwise slots wait for a wake-up.""" + _enqueue(_ledger(engine), deployment_id=_DEPLOYMENT_A, stage=_UPSTREAM) + ledger = _HeldLedger(engine=engine) + registry = HandlerRegistry() + for stage in _STAGES: + registry.register(stage=stage, handler=_Recording()) + loop = SelfHostWorkerLoop( + worker=Worker(ledger=ledger, registry=registry), + ledger=ledger, + deployment_id=_DEPLOYMENT_A, + stages=_STAGES, + bucket=TokenBucket(rate_per_s=1_000.0, capacity=1_000.0), + database_url=_psycopg_url(database_url), + fallback_poll_s=0.25, + concurrency=4, + ) + + assert loop.run_for(duration_s=1.0) == () + # One probe per wake-up (start plus about four polls), not a busy loop. + assert ledger.probes <= 8 + + def test_two_deployments_in_two_databases_interleave_in_one_process( database_url: str, second_database_url: str, engine: Engine ) -> None: From 1bf705c13e805a981e21f6faeb005cd444f78c7a Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 6 Nov 2026 16:58:54 +0100 Subject: [PATCH 3/7] feat(ledger): a reaper sweep can cover every stage of a database WorkLedger.reap_expired_leases takes stages=None to sweep all stages, so a sweeper serving many deployment databases can run one pass per database. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- plan/designs/orchestration_design.md | 5 ++++- src/rememberstack/spine/work_ledger.py | 21 ++++++++++++++++----- src/tests/workers/test_claim_leases.py | 4 ++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/plan/designs/orchestration_design.md b/plan/designs/orchestration_design.md index 3db4d625f..6a5eeac86 100644 --- a/plan/designs/orchestration_design.md +++ b/plan/designs/orchestration_design.md @@ -279,7 +279,10 @@ is killed mid-task (out of memory, a container restart, a preempted instance) wo finalizer runs), because claiming requires `attempts < max_attempts` and a pending row at the limit could never be claimed again. Since `attempts` increments at claim, a task that kills its worker every time dead-letters after `max_attempts` instead of looping. Concurrent sweeps skip - each other's rows (`SKIP LOCKED`). + each other's rows (`SKIP LOCKED`). A sweep is one plain pass over one database + (`WorkLedger.reap_expired_leases`, all stages when none are named), so a process that serves + many deployment databases without running their handlers can sweep each in turn; it then + announces the requeued rows and runs the dead-lettered rows' terminal-failure finalizers itself. Handlers already tolerate a second attempt (D12: idempotent writes, put-if-absent objects), so a reaped attempt that had partly run is safe to repeat. Cost rows are attempt-conditional too: the diff --git a/src/rememberstack/spine/work_ledger.py b/src/rememberstack/spine/work_ledger.py index e60e5986c..0c234727e 100644 --- a/src/rememberstack/spine/work_ledger.py +++ b/src/rememberstack/spine/work_ledger.py @@ -864,9 +864,13 @@ def renew_lease(self, *, processing_id: UUID, attempt: int) -> bool: ) def reap_expired_leases( - self, *, deployment_id: UUID, stages: Collection[PipelineStage] + self, *, deployment_id: UUID, stages: Collection[PipelineStage] | None = None ) -> tuple[ExpiredLease, ...]: - """Take back running attempts on ``stages`` whose lease expired. + """One sweep: take back running attempts whose lease expired. + + ``stages`` limits the sweep (a worker sweeps the stages it serves); + ``None`` sweeps every stage, for a sweeper that serves a database + without running its handlers. Such an attempt's worker was killed or stalled. A row with attempts left returns to ``pending``, due now, so the next claim retries it; a @@ -874,14 +878,18 @@ def reap_expired_leases( requires ``attempts < max_attempts`` and requeueing it would strand it. A task that kills its worker every time therefore dead-letters after ``max_attempts`` instead of looping. Rows another reaper is taking are - skipped. The caller announces the requeued rows. + skipped. The caller announces the requeued rows and runs the + terminal-failure finalizer of each dead-lettered row's stage (for + ``convert``, marking the version failed), as ``Worker`` does. """ with self._engine.begin() as connection: rows = connection.execute( _REAP_EXPIRED_LEASES, { "deployment_id": deployment_id, - "stages": [stage.value for stage in stages], + "stages": None + if stages is None + else [stage.value for stage in stages], }, ).mappings() return tuple( @@ -2127,7 +2135,10 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: SELECT processing_id FROM processing_state WHERE deployment_id = :deployment_id - AND stage = ANY(CAST(:stages AS pipeline_stage[])) + AND ( + CAST(:stages AS pipeline_stage[]) IS NULL + OR stage = ANY(CAST(:stages AS pipeline_stage[])) + ) AND status = 'running' AND lease_until < now() FOR UPDATE SKIP LOCKED diff --git a/src/tests/workers/test_claim_leases.py b/src/tests/workers/test_claim_leases.py index 56446515c..3465d9529 100644 --- a/src/tests/workers/test_claim_leases.py +++ b/src/tests/workers/test_claim_leases.py @@ -269,6 +269,10 @@ def test_the_reaper_requeues_expired_claims_and_dead_letters_exhausted_ones( assert _row(database_engine, other_stage_id)["status"] == "running" assert _claim(ledger).processing_id == retryable_id + # A sweeper without handlers sweeps every stage of the database. + (swept,) = ledger.reap_expired_leases(deployment_id=_DEPLOYMENT_ID) + assert (swept.work.processing_id, swept.requeued) == (other_stage_id, True) + def test_the_worker_announces_requeued_rows_and_finalizes_dead_letters( database_engine: Engine, From db9fb3002594e034b79efc643947dd4da416f7b6 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 6 Nov 2026 18:08:02 +0100 Subject: [PATCH 4/7] fix(worker): free probes, orphan cleanup on upgrade, renumber to D146 Address Codex round 1 on #533: a slot probes for due routes before taking a claim token, so idle wake-ups never drain the bucket; the upgrade guide stops with `docker compose down --remove-orphans` so retired per-stage workers do not keep running. Rebased onto the merged library seams (D144): the class worker builds on the profile's `_worker`, now over several stages; this decision is D146 and the claim-lease decision is D145. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- .env.example | 2 +- compose.yaml | 2 +- decisions.md | 4 +-- plan/designs/chunk_level_extract_design.md | 6 ++-- .../e3_claim_level_normalize_fanout_design.md | 2 +- plan/designs/orchestration_design.md | 2 +- plan/designs/packaging_distribution_design.md | 6 ++-- src/rememberstack/adapters/selfhost/queue.py | 12 ++++--- src/rememberstack/profiles/selfhost.py | 2 +- .../adapters/test_selfhost_worker_classes.py | 33 ++++++++++++++++++- src/tests/profiles/test_selfhost_profile.py | 2 +- website/public/llms-full.txt | 6 ++-- .../app/docs/self-hosting/upgrades/page.mdx | 6 ++-- 13 files changed, 62 insertions(+), 23 deletions(-) diff --git a/.env.example b/.env.example index 6496d00f6..5d2ba8f26 100644 --- a/.env.example +++ b/.env.example @@ -5,7 +5,7 @@ REMEMBERSTACK_POSTGRES_DB=rememberstack # a worker needs 2 x concurrency + 3. Raise it when you add API replicas, worker # containers or concurrency. # REMEMBERSTACK_POSTGRES_MAX_CONNECTIONS=300 -# Tasks in flight per worker container (D145): worker-llm runs every stage +# Tasks in flight per worker container (D146): worker-llm runs every stage # except convert; worker-convert converts one file at a time by default. # REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY=20 # REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY=1 diff --git a/compose.yaml b/compose.yaml index 3254fefcf..bedeb134a 100644 --- a/compose.yaml +++ b/compose.yaml @@ -237,7 +237,7 @@ services: # otherwise; set a token before publishing on another address. - "${REMEMBERSTACK_SELFHOST_API_PUBLISH_ADDRESS:-127.0.0.1}:${REMEMBERSTACK_SELFHOST_API_PORT}:8000" - # Two worker classes (D145): `convert` runs one conversion at a time, so its + # Two worker classes (D146): `convert` runs one conversion at a time, so its # memory is bounded by the largest allowed input; `llm` serves every other # stage with many tasks in flight. Scale either with `--scale` or with its # concurrency. diff --git a/decisions.md b/decisions.md index e0bbd3d72..38ff2ba50 100644 --- a/decisions.md +++ b/decisions.md @@ -7455,7 +7455,7 @@ first sweep recovers them. [Orchestration §6](plan/designs/orchestration_design holds the contract; [schema §2](plan/designs/postgres_schema_design.md) the column, index and queries. -## D145. One worker process serves a class of stages, with a fixed number of tasks in flight +## D146. One worker process serves a class of stages, with a fixed number of tasks in flight **Status:** accepted. **Date:** 2026-11-06. @@ -7479,7 +7479,7 @@ conversion's memory grows with the input. drains before new uploads take the slots. One probe query finds the routes with due work. - **Delivery is unchanged:** `LISTEN/NOTIFY` wake-ups and `SELECT … FOR UPDATE SKIP LOCKED` claims (D67). A wake-up rouses one idle slot; a slot that finds work rouses one more. Claim - leases (D144) make it safe for a class process to die with many tasks in flight. + leases (D145) make it safe for a class process to die with many tasks in flight. - A process's database pool is sized from its concurrency. **Alternatives.** One process per stage with in-process concurrency keeps fourteen idle diff --git a/plan/designs/chunk_level_extract_design.md b/plan/designs/chunk_level_extract_design.md index 774e89887..b001ee29a 100644 --- a/plan/designs/chunk_level_extract_design.md +++ b/plan/designs/chunk_level_extract_design.md @@ -174,7 +174,7 @@ Connector-cycle finalization SQL must likewise wait on pending/running/failed `processing_state` aggregates by `stage` already power readiness. After this change, `extract_claims` pending/running counts approximate **chunk** backlog. -Document for operators and UMC: scale the `llm` worker class (D145) on that depth. +Document for operators and UMC: scale the `llm` worker class (D146) on that depth. No new public HTTP API is required for v1. @@ -207,7 +207,7 @@ Chunk ids are internal UUIDs; no new mount surface. ### 9.1 Auto-deploy -- Same container image, same worker entrypoint (`worker --class llm`, D145). +- Same container image, same worker entrypoint (`worker --class llm`, D146). - No new Coolify service names, secrets, or migrations of the `processing_target` enum (CHUNK already exists). Alembic may still be needed only if readiness SQL lives purely in app code (preferred). @@ -224,7 +224,7 @@ UMC must **not** manufacture extract work. It may: 1. Observe OSS `processing_state` (or a safe aggregate export) for `stage=extract_claims`, statuses pending/running. -2. Set the concurrency or replica count of the data-plane `llm` worker class (D145). +2. Set the concurrency or replica count of the data-plane `llm` worker class (D146). Chunk-level grain makes that observation **useful**. Control plane remains non- authoritative for work truth (D2/D6/D67 as used in UMC integration analysis). diff --git a/plan/designs/e3_claim_level_normalize_fanout_design.md b/plan/designs/e3_claim_level_normalize_fanout_design.md index d2094f43c..296f7f382 100644 --- a/plan/designs/e3_claim_level_normalize_fanout_design.md +++ b/plan/designs/e3_claim_level_normalize_fanout_design.md @@ -293,7 +293,7 @@ retry then drop; systemic provider/DB re-raise; mint defense; cost keys ## 9. UMC / compose Same image; `normalize_relations` runs in the `llm` worker class -(`worker --class llm`, D145). Scale that class's concurrency or containers on +(`worker --class llm`, D146). Scale that class's concurrency or containers on claim-grain pending/running. No control-plane work manufacture (D67). Single-revision deploy for all normalize workers. diff --git a/plan/designs/orchestration_design.md b/plan/designs/orchestration_design.md index 6a5eeac86..d965b005b 100644 --- a/plan/designs/orchestration_design.md +++ b/plan/designs/orchestration_design.md @@ -122,7 +122,7 @@ isolate state the two lanes share (below). Rules: predecessors (D143 lineage order). The duplicate-promotion rule above is unchanged. - **The self-host profile serves the backfill lane** from the same worker process: a worker class claims from its stages' backfill routes whenever none of their steady routes has a due - row ([packaging §3, worker classes](packaging_distribution_design.md#3-task-execution--one-model-two-delivery-shells), D145). + row ([packaging §3, worker classes](packaging_distribution_design.md#3-task-execution--one-model-two-delivery-shells), D146). - **Lane budgets are separate** (§4): backfill spend is a knob turned deliberately; apart from the shared-entity applications above, it does not draw on the steady-state budget. The two dominant backfill costs are metered per lane diff --git a/plan/designs/packaging_distribution_design.md b/plan/designs/packaging_distribution_design.md index 46cc262a9..8a87b37d6 100644 --- a/plan/designs/packaging_distribution_design.md +++ b/plan/designs/packaging_distribution_design.md @@ -135,11 +135,11 @@ are hints, never inputs to a state transition. routes of its **worker class** whose `not_before <= now()`, using `SELECT … FOR UPDATE SKIP LOCKED LIMIT n` and the schema §2 due-work index. A **slow fallback poll (~30 s)** exists only as a safety net for missed notifications and scheduled work becoming - due; crash recovery is the lease reaper (orchestration §6, D144). Application attempts/backoff + due; crash recovery is the lease reaper (orchestration §6, D145). Application attempts/backoff remain row state; a per-process rate limit is a token bucket consulted around the claim. Scaling = raise a class's concurrency, or `docker compose up --scale worker-llm=N`. - **Worker classes (D145).** One worker process serves every stage of one class, with a fixed + **Worker classes (D146).** One worker process serves every stage of one class, with a fixed number of tasks in flight (its *concurrency*), each in its own thread: | Class | Stages | Tasks in flight (starting point) | Why | @@ -150,7 +150,7 @@ are hints, never inputs to a state transition. Memory is safe by construction rather than by accounting: a class's process is sized as peak memory per task × concurrency + headroom, measured once per class. A process that still runs out of memory loses only its own in-flight tasks; their leases expire and they are retried, - and a task that kills its worker every time dead-letters after `max_attempts` (D144). + and a task that kills its worker every time dead-letters after `max_attempts` (D145). **Fair order.** A class process lists its routes as every stage's steady lane, then every stage's backfill lane, each in pipeline order **downstream first** (e.g. `label_relation` diff --git a/src/rememberstack/adapters/selfhost/queue.py b/src/rememberstack/adapters/selfhost/queue.py index db5b45100..121186528 100644 --- a/src/rememberstack/adapters/selfhost/queue.py +++ b/src/rememberstack/adapters/selfhost/queue.py @@ -96,7 +96,7 @@ class SelfHostWorkerLoop: in their own thread. The calling thread sleeps on LISTEN with a slow fallback poll; every wake-up, and every successful claim, wakes one idle slot, so idle slots look for work one at a time instead of all at - once. The calling thread also sweeps expired claims (D144) at most once + once. The calling thread also sweeps expired claims (D145) at most once per fallback-poll interval. """ @@ -212,12 +212,16 @@ def _slot( self._wake.notify_all() def _run_next(self) -> RunResult | None: - """Claim and run the first due unit of work in route order, if any.""" - if not self._bucket.try_acquire(): - return None + """Claim and run the first due unit of work in route order, if any. + + The probe comes first and costs no token, so idle slots never drain + the claim budget; each claim attempt takes one. + """ for stage, lane in self._ledger.due_routes( deployment_id=self._deployment_id, routes=self._routes ): + if not self._bucket.try_acquire(): + return None result = self._worker.run_one( deployment_id=self._deployment_id, stage=stage, diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index 9331d85a8..dabe5b1b0 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -114,7 +114,7 @@ PipelineStage.REVIEW_FACT_WINDOWS, ) -#: The worker classes (D145). ``convert`` is the one input-size-dependent, +#: The worker classes (D146). ``convert`` is the one input-size-dependent, #: CPU- and memory-heavy stage; ``llm`` is every other stage, which mostly #: waits on model and embedding calls or the database. Each class lists its #: stages downstream first: that is the order a worker drains them in. diff --git a/src/tests/adapters/test_selfhost_worker_classes.py b/src/tests/adapters/test_selfhost_worker_classes.py index 4a1846507..20526a4ed 100644 --- a/src/tests/adapters/test_selfhost_worker_classes.py +++ b/src/tests/adapters/test_selfhost_worker_classes.py @@ -1,4 +1,4 @@ -"""Real-PostgreSQL proofs for stage-class workers (D145). +"""Real-PostgreSQL proofs for stage-class workers (D146). One worker process serves every stage of its class with several tasks in flight. Downstream stages drain first, steady lanes before backfill lanes, and @@ -344,6 +344,37 @@ def test_work_that_is_listed_but_cannot_be_claimed_does_not_spin_the_slots( assert ledger.probes <= 8 +def test_idle_wake_ups_spend_no_claim_tokens(database_url: str, engine: Engine) -> None: + """Probing for work is free; only a claim takes a token from the bucket.""" + handler = _Recording() + ledger = _ledger(engine) + registry = HandlerRegistry() + for stage in _STAGES: + registry.register(stage=stage, handler=handler) + loop = SelfHostWorkerLoop( + worker=Worker(ledger=ledger, registry=registry), + ledger=ledger, + deployment_id=_DEPLOYMENT_A, + stages=_STAGES, + bucket=TokenBucket(rate_per_s=0.001, capacity=1.0), # one claim in total + database_url=_psycopg_url(database_url), + fallback_poll_s=0.1, + concurrency=2, + ) + outcomes: list[RunResultOutcome] = [] + runner = threading.Thread( + target=lambda: outcomes.extend( + result.outcome for result in loop.run_for(duration_s=1.5) + ) + ) + runner.start() + time.sleep(0.8) # several idle wake-ups pass first + _enqueue(ledger, deployment_id=_DEPLOYMENT_A, stage=_UPSTREAM) + runner.join() + + assert outcomes == [RunResultOutcome.SUCCEEDED] + + def test_two_deployments_in_two_databases_interleave_in_one_process( database_url: str, second_database_url: str, engine: Engine ) -> None: diff --git a/src/tests/profiles/test_selfhost_profile.py b/src/tests/profiles/test_selfhost_profile.py index b01e1e482..60a3c4075 100644 --- a/src/tests/profiles/test_selfhost_profile.py +++ b/src/tests/profiles/test_selfhost_profile.py @@ -92,7 +92,7 @@ def test_selfhost_composes_every_implemented_continuous_route() -> None: def test_worker_classes_split_convert_from_the_rest_downstream_first() -> None: - """D145: convert alone; every other stage in one class, downstream first.""" + """D146: convert alone; every other stage in one class, downstream first.""" assert WORKER_CLASSES["convert"] == (PipelineStage.CONVERT,) assert WORKER_CLASSES["llm"] == tuple(reversed(_SUPPORTED_WORKER_STAGES[1:])) assert DEFAULT_WORKER_CONCURRENCY == {"convert": 1, "llm": 20} diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index 96c17faf1..f400a4a2c 100644 --- a/website/public/llms-full.txt +++ b/website/public/llms-full.txt @@ -9281,11 +9281,13 @@ documents again. Keep your source files for this reason. See that is being migrated: ```bash - docker compose down + docker compose down --remove-orphans ``` `down` removes the containers and keeps the volumes, and with them the - memory. + memory. `--remove-orphans` also stops containers of services the new + `compose.yaml` no longer has, such as the per-stage workers of releases + before the two worker containers. 5. **Get the new images:** diff --git a/website/src/app/docs/self-hosting/upgrades/page.mdx b/website/src/app/docs/self-hosting/upgrades/page.mdx index 4c4e6dcfa..db7377e0f 100644 --- a/website/src/app/docs/self-hosting/upgrades/page.mdx +++ b/website/src/app/docs/self-hosting/upgrades/page.mdx @@ -78,11 +78,13 @@ documents again. Keep your source files for this reason. See that is being migrated: ```bash - docker compose down + docker compose down --remove-orphans ``` `down` removes the containers and keeps the volumes, and with them the - memory. + memory. `--remove-orphans` also stops containers of services the new + `compose.yaml` no longer has, such as the per-stage workers of releases + before the two worker containers. 5. **Get the new images:** From 3cac032ab96a7db54865ed3c9098ae0a197a0f37 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 6 Nov 2026 18:12:47 +0100 Subject: [PATCH 5/7] refactor(worker): size the worker pool through from_settings(engine_options=) Use the engine_options seam agreed with the library-seams track instead of a worker-specific keyword. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- src/rememberstack/profiles/selfhost.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index dabe5b1b0..365199917 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -1941,7 +1941,7 @@ def main(argv: list[str] | None = None) -> int: profile = SelfHostProfile.from_settings( EngineSettings.from_env(), error_telemetry=error_telemetry, - worker_concurrency=concurrency or None, + engine_options=_worker_pool(concurrency=concurrency) if concurrency else None, ) try: if args.command == "setup": @@ -1986,6 +1986,15 @@ def _initialize_error_tracking( ) +def _worker_pool(*, concurrency: int) -> dict[str, Any]: + """A worker's main pool: every in-flight task may hold two connections. + + One code path nests a read inside a transaction, and lease renewals and + the reaper need a few more, so SQLAlchemy's fixed 5 + 10 would not do. + """ + return {"pool_size": concurrency + 2, "max_overflow": concurrency} + + def _positive_int(value: str) -> int: """Parse a strictly positive integer command-line value.""" number = int(value) From 1335f787e52957d9999b892d7c77b822f823d972 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 6 Nov 2026 18:27:14 +0100 Subject: [PATCH 6/7] docs: worker classes are D145 (leases D144); point the obs-flush design at the llm class Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- .env.example | 2 +- compose.yaml | 2 +- decisions.md | 4 ++-- plan/designs/chunk_level_extract_design.md | 6 +++--- plan/designs/e3_claim_level_normalize_fanout_design.md | 2 +- plan/designs/e3_entity_obs_flush_fanout_design.md | 2 +- plan/designs/orchestration_design.md | 2 +- plan/designs/packaging_distribution_design.md | 6 +++--- src/rememberstack/adapters/selfhost/queue.py | 2 +- src/rememberstack/profiles/selfhost.py | 4 ++-- src/tests/adapters/test_selfhost_worker_classes.py | 2 +- src/tests/profiles/test_selfhost_profile.py | 2 +- 12 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.env.example b/.env.example index 5d2ba8f26..6496d00f6 100644 --- a/.env.example +++ b/.env.example @@ -5,7 +5,7 @@ REMEMBERSTACK_POSTGRES_DB=rememberstack # a worker needs 2 x concurrency + 3. Raise it when you add API replicas, worker # containers or concurrency. # REMEMBERSTACK_POSTGRES_MAX_CONNECTIONS=300 -# Tasks in flight per worker container (D146): worker-llm runs every stage +# Tasks in flight per worker container (D145): worker-llm runs every stage # except convert; worker-convert converts one file at a time by default. # REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY=20 # REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY=1 diff --git a/compose.yaml b/compose.yaml index bedeb134a..3254fefcf 100644 --- a/compose.yaml +++ b/compose.yaml @@ -237,7 +237,7 @@ services: # otherwise; set a token before publishing on another address. - "${REMEMBERSTACK_SELFHOST_API_PUBLISH_ADDRESS:-127.0.0.1}:${REMEMBERSTACK_SELFHOST_API_PORT}:8000" - # Two worker classes (D146): `convert` runs one conversion at a time, so its + # Two worker classes (D145): `convert` runs one conversion at a time, so its # memory is bounded by the largest allowed input; `llm` serves every other # stage with many tasks in flight. Scale either with `--scale` or with its # concurrency. diff --git a/decisions.md b/decisions.md index 38ff2ba50..e0bbd3d72 100644 --- a/decisions.md +++ b/decisions.md @@ -7455,7 +7455,7 @@ first sweep recovers them. [Orchestration §6](plan/designs/orchestration_design holds the contract; [schema §2](plan/designs/postgres_schema_design.md) the column, index and queries. -## D146. One worker process serves a class of stages, with a fixed number of tasks in flight +## D145. One worker process serves a class of stages, with a fixed number of tasks in flight **Status:** accepted. **Date:** 2026-11-06. @@ -7479,7 +7479,7 @@ conversion's memory grows with the input. drains before new uploads take the slots. One probe query finds the routes with due work. - **Delivery is unchanged:** `LISTEN/NOTIFY` wake-ups and `SELECT … FOR UPDATE SKIP LOCKED` claims (D67). A wake-up rouses one idle slot; a slot that finds work rouses one more. Claim - leases (D145) make it safe for a class process to die with many tasks in flight. + leases (D144) make it safe for a class process to die with many tasks in flight. - A process's database pool is sized from its concurrency. **Alternatives.** One process per stage with in-process concurrency keeps fourteen idle diff --git a/plan/designs/chunk_level_extract_design.md b/plan/designs/chunk_level_extract_design.md index b001ee29a..774e89887 100644 --- a/plan/designs/chunk_level_extract_design.md +++ b/plan/designs/chunk_level_extract_design.md @@ -174,7 +174,7 @@ Connector-cycle finalization SQL must likewise wait on pending/running/failed `processing_state` aggregates by `stage` already power readiness. After this change, `extract_claims` pending/running counts approximate **chunk** backlog. -Document for operators and UMC: scale the `llm` worker class (D146) on that depth. +Document for operators and UMC: scale the `llm` worker class (D145) on that depth. No new public HTTP API is required for v1. @@ -207,7 +207,7 @@ Chunk ids are internal UUIDs; no new mount surface. ### 9.1 Auto-deploy -- Same container image, same worker entrypoint (`worker --class llm`, D146). +- Same container image, same worker entrypoint (`worker --class llm`, D145). - No new Coolify service names, secrets, or migrations of the `processing_target` enum (CHUNK already exists). Alembic may still be needed only if readiness SQL lives purely in app code (preferred). @@ -224,7 +224,7 @@ UMC must **not** manufacture extract work. It may: 1. Observe OSS `processing_state` (or a safe aggregate export) for `stage=extract_claims`, statuses pending/running. -2. Set the concurrency or replica count of the data-plane `llm` worker class (D146). +2. Set the concurrency or replica count of the data-plane `llm` worker class (D145). Chunk-level grain makes that observation **useful**. Control plane remains non- authoritative for work truth (D2/D6/D67 as used in UMC integration analysis). diff --git a/plan/designs/e3_claim_level_normalize_fanout_design.md b/plan/designs/e3_claim_level_normalize_fanout_design.md index 296f7f382..d2094f43c 100644 --- a/plan/designs/e3_claim_level_normalize_fanout_design.md +++ b/plan/designs/e3_claim_level_normalize_fanout_design.md @@ -293,7 +293,7 @@ retry then drop; systemic provider/DB re-raise; mint defense; cost keys ## 9. UMC / compose Same image; `normalize_relations` runs in the `llm` worker class -(`worker --class llm`, D146). Scale that class's concurrency or containers on +(`worker --class llm`, D145). Scale that class's concurrency or containers on claim-grain pending/running. No control-plane work manufacture (D67). Single-revision deploy for all normalize workers. diff --git a/plan/designs/e3_entity_obs_flush_fanout_design.md b/plan/designs/e3_entity_obs_flush_fanout_design.md index b3331ed0f..e9f8511d7 100644 --- a/plan/designs/e3_entity_obs_flush_fanout_design.md +++ b/plan/designs/e3_entity_obs_flush_fanout_design.md @@ -280,7 +280,7 @@ E1/E2 zero-chunk paths): after the component-version bump they must either: ### 5.9 Workers and indexes -- Stage name unchanged; scale `worker-adjudicate-observations`. +- Stage name unchanged; it runs in the `llm` worker class (D145): scale that class's concurrency or containers. - Handler dispatches: entity unit (`target_kind=entity` + fan-out version) vs legacy document_version + pre-fanout version. - Indexes: membership by version; processing partial index on entity target_kind diff --git a/plan/designs/orchestration_design.md b/plan/designs/orchestration_design.md index d965b005b..6a5eeac86 100644 --- a/plan/designs/orchestration_design.md +++ b/plan/designs/orchestration_design.md @@ -122,7 +122,7 @@ isolate state the two lanes share (below). Rules: predecessors (D143 lineage order). The duplicate-promotion rule above is unchanged. - **The self-host profile serves the backfill lane** from the same worker process: a worker class claims from its stages' backfill routes whenever none of their steady routes has a due - row ([packaging §3, worker classes](packaging_distribution_design.md#3-task-execution--one-model-two-delivery-shells), D146). + row ([packaging §3, worker classes](packaging_distribution_design.md#3-task-execution--one-model-two-delivery-shells), D145). - **Lane budgets are separate** (§4): backfill spend is a knob turned deliberately; apart from the shared-entity applications above, it does not draw on the steady-state budget. The two dominant backfill costs are metered per lane diff --git a/plan/designs/packaging_distribution_design.md b/plan/designs/packaging_distribution_design.md index 8a87b37d6..46cc262a9 100644 --- a/plan/designs/packaging_distribution_design.md +++ b/plan/designs/packaging_distribution_design.md @@ -135,11 +135,11 @@ are hints, never inputs to a state transition. routes of its **worker class** whose `not_before <= now()`, using `SELECT … FOR UPDATE SKIP LOCKED LIMIT n` and the schema §2 due-work index. A **slow fallback poll (~30 s)** exists only as a safety net for missed notifications and scheduled work becoming - due; crash recovery is the lease reaper (orchestration §6, D145). Application attempts/backoff + due; crash recovery is the lease reaper (orchestration §6, D144). Application attempts/backoff remain row state; a per-process rate limit is a token bucket consulted around the claim. Scaling = raise a class's concurrency, or `docker compose up --scale worker-llm=N`. - **Worker classes (D146).** One worker process serves every stage of one class, with a fixed + **Worker classes (D145).** One worker process serves every stage of one class, with a fixed number of tasks in flight (its *concurrency*), each in its own thread: | Class | Stages | Tasks in flight (starting point) | Why | @@ -150,7 +150,7 @@ are hints, never inputs to a state transition. Memory is safe by construction rather than by accounting: a class's process is sized as peak memory per task × concurrency + headroom, measured once per class. A process that still runs out of memory loses only its own in-flight tasks; their leases expire and they are retried, - and a task that kills its worker every time dead-letters after `max_attempts` (D145). + and a task that kills its worker every time dead-letters after `max_attempts` (D144). **Fair order.** A class process lists its routes as every stage's steady lane, then every stage's backfill lane, each in pipeline order **downstream first** (e.g. `label_relation` diff --git a/src/rememberstack/adapters/selfhost/queue.py b/src/rememberstack/adapters/selfhost/queue.py index 121186528..e062b645f 100644 --- a/src/rememberstack/adapters/selfhost/queue.py +++ b/src/rememberstack/adapters/selfhost/queue.py @@ -96,7 +96,7 @@ class SelfHostWorkerLoop: in their own thread. The calling thread sleeps on LISTEN with a slow fallback poll; every wake-up, and every successful claim, wakes one idle slot, so idle slots look for work one at a time instead of all at - once. The calling thread also sweeps expired claims (D145) at most once + once. The calling thread also sweeps expired claims (D144) at most once per fallback-poll interval. """ diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index 365199917..264564c4e 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -114,7 +114,7 @@ PipelineStage.REVIEW_FACT_WINDOWS, ) -#: The worker classes (D146). ``convert`` is the one input-size-dependent, +#: The worker classes (D145). ``convert`` is the one input-size-dependent, #: CPU- and memory-heavy stage; ``llm`` is every other stage, which mostly #: waits on model and embedding calls or the database. Each class lists its #: stages downstream first: that is the order a worker drains them in. @@ -1486,7 +1486,7 @@ def run_meter_receipts(self, *, once: bool = False, limit: int = 100) -> None: time.sleep(self._settings.meter_receipt_poll_s) def worker_loop(self, *, worker_class: str, concurrency: int) -> SelfHostWorkerLoop: - """Build one worker class's LISTEN/NOTIFY loop over all of its stages (D146).""" + """Build one worker class's LISTEN/NOTIFY loop over all of its stages (D145).""" from rememberstack.adapters.selfhost import SelfHostWorkerLoop from rememberstack.adapters.selfhost import TokenBucket from rememberstack.spine import WorkLedger diff --git a/src/tests/adapters/test_selfhost_worker_classes.py b/src/tests/adapters/test_selfhost_worker_classes.py index 20526a4ed..9fe948991 100644 --- a/src/tests/adapters/test_selfhost_worker_classes.py +++ b/src/tests/adapters/test_selfhost_worker_classes.py @@ -1,4 +1,4 @@ -"""Real-PostgreSQL proofs for stage-class workers (D146). +"""Real-PostgreSQL proofs for stage-class workers (D145). One worker process serves every stage of its class with several tasks in flight. Downstream stages drain first, steady lanes before backfill lanes, and diff --git a/src/tests/profiles/test_selfhost_profile.py b/src/tests/profiles/test_selfhost_profile.py index 60a3c4075..b01e1e482 100644 --- a/src/tests/profiles/test_selfhost_profile.py +++ b/src/tests/profiles/test_selfhost_profile.py @@ -92,7 +92,7 @@ def test_selfhost_composes_every_implemented_continuous_route() -> None: def test_worker_classes_split_convert_from_the_rest_downstream_first() -> None: - """D146: convert alone; every other stage in one class, downstream first.""" + """D145: convert alone; every other stage in one class, downstream first.""" assert WORKER_CLASSES["convert"] == (PipelineStage.CONVERT,) assert WORKER_CLASSES["llm"] == tuple(reversed(_SUPPORTED_WORKER_STAGES[1:])) assert DEFAULT_WORKER_CONCURRENCY == {"convert": 1, "llm": 20} From 7ff63bbbfce2d116124b351f4cd6c30d76931d3b Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 6 Nov 2026 19:25:57 +0100 Subject: [PATCH 7/7] docs: worker classes are D146, leases D145 (final numbering) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- .env.example | 2 +- compose.yaml | 2 +- decisions.md | 4 ++-- plan/designs/chunk_level_extract_design.md | 6 +++--- plan/designs/e3_claim_level_normalize_fanout_design.md | 2 +- plan/designs/e3_entity_obs_flush_fanout_design.md | 2 +- plan/designs/orchestration_design.md | 2 +- plan/designs/packaging_distribution_design.md | 6 +++--- src/rememberstack/adapters/selfhost/queue.py | 2 +- src/rememberstack/profiles/selfhost.py | 4 ++-- src/tests/adapters/test_selfhost_worker_classes.py | 2 +- src/tests/profiles/test_selfhost_profile.py | 2 +- 12 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.env.example b/.env.example index 6496d00f6..5d2ba8f26 100644 --- a/.env.example +++ b/.env.example @@ -5,7 +5,7 @@ REMEMBERSTACK_POSTGRES_DB=rememberstack # a worker needs 2 x concurrency + 3. Raise it when you add API replicas, worker # containers or concurrency. # REMEMBERSTACK_POSTGRES_MAX_CONNECTIONS=300 -# Tasks in flight per worker container (D145): worker-llm runs every stage +# Tasks in flight per worker container (D146): worker-llm runs every stage # except convert; worker-convert converts one file at a time by default. # REMEMBERSTACK_SELFHOST_LLM_CONCURRENCY=20 # REMEMBERSTACK_SELFHOST_CONVERT_CONCURRENCY=1 diff --git a/compose.yaml b/compose.yaml index 3254fefcf..bedeb134a 100644 --- a/compose.yaml +++ b/compose.yaml @@ -237,7 +237,7 @@ services: # otherwise; set a token before publishing on another address. - "${REMEMBERSTACK_SELFHOST_API_PUBLISH_ADDRESS:-127.0.0.1}:${REMEMBERSTACK_SELFHOST_API_PORT}:8000" - # Two worker classes (D145): `convert` runs one conversion at a time, so its + # Two worker classes (D146): `convert` runs one conversion at a time, so its # memory is bounded by the largest allowed input; `llm` serves every other # stage with many tasks in flight. Scale either with `--scale` or with its # concurrency. diff --git a/decisions.md b/decisions.md index e0bbd3d72..38ff2ba50 100644 --- a/decisions.md +++ b/decisions.md @@ -7455,7 +7455,7 @@ first sweep recovers them. [Orchestration §6](plan/designs/orchestration_design holds the contract; [schema §2](plan/designs/postgres_schema_design.md) the column, index and queries. -## D145. One worker process serves a class of stages, with a fixed number of tasks in flight +## D146. One worker process serves a class of stages, with a fixed number of tasks in flight **Status:** accepted. **Date:** 2026-11-06. @@ -7479,7 +7479,7 @@ conversion's memory grows with the input. drains before new uploads take the slots. One probe query finds the routes with due work. - **Delivery is unchanged:** `LISTEN/NOTIFY` wake-ups and `SELECT … FOR UPDATE SKIP LOCKED` claims (D67). A wake-up rouses one idle slot; a slot that finds work rouses one more. Claim - leases (D144) make it safe for a class process to die with many tasks in flight. + leases (D145) make it safe for a class process to die with many tasks in flight. - A process's database pool is sized from its concurrency. **Alternatives.** One process per stage with in-process concurrency keeps fourteen idle diff --git a/plan/designs/chunk_level_extract_design.md b/plan/designs/chunk_level_extract_design.md index 774e89887..b001ee29a 100644 --- a/plan/designs/chunk_level_extract_design.md +++ b/plan/designs/chunk_level_extract_design.md @@ -174,7 +174,7 @@ Connector-cycle finalization SQL must likewise wait on pending/running/failed `processing_state` aggregates by `stage` already power readiness. After this change, `extract_claims` pending/running counts approximate **chunk** backlog. -Document for operators and UMC: scale the `llm` worker class (D145) on that depth. +Document for operators and UMC: scale the `llm` worker class (D146) on that depth. No new public HTTP API is required for v1. @@ -207,7 +207,7 @@ Chunk ids are internal UUIDs; no new mount surface. ### 9.1 Auto-deploy -- Same container image, same worker entrypoint (`worker --class llm`, D145). +- Same container image, same worker entrypoint (`worker --class llm`, D146). - No new Coolify service names, secrets, or migrations of the `processing_target` enum (CHUNK already exists). Alembic may still be needed only if readiness SQL lives purely in app code (preferred). @@ -224,7 +224,7 @@ UMC must **not** manufacture extract work. It may: 1. Observe OSS `processing_state` (or a safe aggregate export) for `stage=extract_claims`, statuses pending/running. -2. Set the concurrency or replica count of the data-plane `llm` worker class (D145). +2. Set the concurrency or replica count of the data-plane `llm` worker class (D146). Chunk-level grain makes that observation **useful**. Control plane remains non- authoritative for work truth (D2/D6/D67 as used in UMC integration analysis). diff --git a/plan/designs/e3_claim_level_normalize_fanout_design.md b/plan/designs/e3_claim_level_normalize_fanout_design.md index d2094f43c..296f7f382 100644 --- a/plan/designs/e3_claim_level_normalize_fanout_design.md +++ b/plan/designs/e3_claim_level_normalize_fanout_design.md @@ -293,7 +293,7 @@ retry then drop; systemic provider/DB re-raise; mint defense; cost keys ## 9. UMC / compose Same image; `normalize_relations` runs in the `llm` worker class -(`worker --class llm`, D145). Scale that class's concurrency or containers on +(`worker --class llm`, D146). Scale that class's concurrency or containers on claim-grain pending/running. No control-plane work manufacture (D67). Single-revision deploy for all normalize workers. diff --git a/plan/designs/e3_entity_obs_flush_fanout_design.md b/plan/designs/e3_entity_obs_flush_fanout_design.md index e9f8511d7..74ff450e6 100644 --- a/plan/designs/e3_entity_obs_flush_fanout_design.md +++ b/plan/designs/e3_entity_obs_flush_fanout_design.md @@ -280,7 +280,7 @@ E1/E2 zero-chunk paths): after the component-version bump they must either: ### 5.9 Workers and indexes -- Stage name unchanged; it runs in the `llm` worker class (D145): scale that class's concurrency or containers. +- Stage name unchanged; it runs in the `llm` worker class (D146): scale that class's concurrency or containers. - Handler dispatches: entity unit (`target_kind=entity` + fan-out version) vs legacy document_version + pre-fanout version. - Indexes: membership by version; processing partial index on entity target_kind diff --git a/plan/designs/orchestration_design.md b/plan/designs/orchestration_design.md index 6a5eeac86..d965b005b 100644 --- a/plan/designs/orchestration_design.md +++ b/plan/designs/orchestration_design.md @@ -122,7 +122,7 @@ isolate state the two lanes share (below). Rules: predecessors (D143 lineage order). The duplicate-promotion rule above is unchanged. - **The self-host profile serves the backfill lane** from the same worker process: a worker class claims from its stages' backfill routes whenever none of their steady routes has a due - row ([packaging §3, worker classes](packaging_distribution_design.md#3-task-execution--one-model-two-delivery-shells), D145). + row ([packaging §3, worker classes](packaging_distribution_design.md#3-task-execution--one-model-two-delivery-shells), D146). - **Lane budgets are separate** (§4): backfill spend is a knob turned deliberately; apart from the shared-entity applications above, it does not draw on the steady-state budget. The two dominant backfill costs are metered per lane diff --git a/plan/designs/packaging_distribution_design.md b/plan/designs/packaging_distribution_design.md index 46cc262a9..8a87b37d6 100644 --- a/plan/designs/packaging_distribution_design.md +++ b/plan/designs/packaging_distribution_design.md @@ -135,11 +135,11 @@ are hints, never inputs to a state transition. routes of its **worker class** whose `not_before <= now()`, using `SELECT … FOR UPDATE SKIP LOCKED LIMIT n` and the schema §2 due-work index. A **slow fallback poll (~30 s)** exists only as a safety net for missed notifications and scheduled work becoming - due; crash recovery is the lease reaper (orchestration §6, D144). Application attempts/backoff + due; crash recovery is the lease reaper (orchestration §6, D145). Application attempts/backoff remain row state; a per-process rate limit is a token bucket consulted around the claim. Scaling = raise a class's concurrency, or `docker compose up --scale worker-llm=N`. - **Worker classes (D145).** One worker process serves every stage of one class, with a fixed + **Worker classes (D146).** One worker process serves every stage of one class, with a fixed number of tasks in flight (its *concurrency*), each in its own thread: | Class | Stages | Tasks in flight (starting point) | Why | @@ -150,7 +150,7 @@ are hints, never inputs to a state transition. Memory is safe by construction rather than by accounting: a class's process is sized as peak memory per task × concurrency + headroom, measured once per class. A process that still runs out of memory loses only its own in-flight tasks; their leases expire and they are retried, - and a task that kills its worker every time dead-letters after `max_attempts` (D144). + and a task that kills its worker every time dead-letters after `max_attempts` (D145). **Fair order.** A class process lists its routes as every stage's steady lane, then every stage's backfill lane, each in pipeline order **downstream first** (e.g. `label_relation` diff --git a/src/rememberstack/adapters/selfhost/queue.py b/src/rememberstack/adapters/selfhost/queue.py index e062b645f..121186528 100644 --- a/src/rememberstack/adapters/selfhost/queue.py +++ b/src/rememberstack/adapters/selfhost/queue.py @@ -96,7 +96,7 @@ class SelfHostWorkerLoop: in their own thread. The calling thread sleeps on LISTEN with a slow fallback poll; every wake-up, and every successful claim, wakes one idle slot, so idle slots look for work one at a time instead of all at - once. The calling thread also sweeps expired claims (D144) at most once + once. The calling thread also sweeps expired claims (D145) at most once per fallback-poll interval. """ diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index 264564c4e..365199917 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -114,7 +114,7 @@ PipelineStage.REVIEW_FACT_WINDOWS, ) -#: The worker classes (D145). ``convert`` is the one input-size-dependent, +#: The worker classes (D146). ``convert`` is the one input-size-dependent, #: CPU- and memory-heavy stage; ``llm`` is every other stage, which mostly #: waits on model and embedding calls or the database. Each class lists its #: stages downstream first: that is the order a worker drains them in. @@ -1486,7 +1486,7 @@ def run_meter_receipts(self, *, once: bool = False, limit: int = 100) -> None: time.sleep(self._settings.meter_receipt_poll_s) def worker_loop(self, *, worker_class: str, concurrency: int) -> SelfHostWorkerLoop: - """Build one worker class's LISTEN/NOTIFY loop over all of its stages (D145).""" + """Build one worker class's LISTEN/NOTIFY loop over all of its stages (D146).""" from rememberstack.adapters.selfhost import SelfHostWorkerLoop from rememberstack.adapters.selfhost import TokenBucket from rememberstack.spine import WorkLedger diff --git a/src/tests/adapters/test_selfhost_worker_classes.py b/src/tests/adapters/test_selfhost_worker_classes.py index 9fe948991..20526a4ed 100644 --- a/src/tests/adapters/test_selfhost_worker_classes.py +++ b/src/tests/adapters/test_selfhost_worker_classes.py @@ -1,4 +1,4 @@ -"""Real-PostgreSQL proofs for stage-class workers (D145). +"""Real-PostgreSQL proofs for stage-class workers (D146). One worker process serves every stage of its class with several tasks in flight. Downstream stages drain first, steady lanes before backfill lanes, and diff --git a/src/tests/profiles/test_selfhost_profile.py b/src/tests/profiles/test_selfhost_profile.py index b01e1e482..60a3c4075 100644 --- a/src/tests/profiles/test_selfhost_profile.py +++ b/src/tests/profiles/test_selfhost_profile.py @@ -92,7 +92,7 @@ def test_selfhost_composes_every_implemented_continuous_route() -> None: def test_worker_classes_split_convert_from_the_rest_downstream_first() -> None: - """D145: convert alone; every other stage in one class, downstream first.""" + """D146: convert alone; every other stage in one class, downstream first.""" assert WORKER_CLASSES["convert"] == (PipelineStage.CONVERT,) assert WORKER_CLASSES["llm"] == tuple(reversed(_SUPPORTED_WORKER_STAGES[1:])) assert DEFAULT_WORKER_CONCURRENCY == {"convert": 1, "llm": 20}