Add host-wide worker limits and preferred GPU hosts #18

Merged
nimmo merged 7 commits from feature/host-worker-policy into dev 2026-10-07 16:25:12 +01:00
Owner

Workers currently claim queued jobs without considering host GPU capacity or preferring an available GPU host. This adds a shared host policy with one combined tagging/vectorization job per host by default, independent CPU/per-kind budgets, allowed job kinds, and GPU priority with fallback when a preferred host is busy, ineligible or stale.

Capacity reads and claims are atomic on the main server, including remote optimistic conflict retries; network requests never hold an open server transaction between replies. A state/host/kind covering index keeps scheduler lookups from scanning historical jobs. Same-host policy disagreement fails explicitly. Embeddings may run alongside ripping, tagging, purge and visual discovery; scans, moves and destructive deduplication retain exclusion.

Both NixOS modules expose workerPolicy, and Fedora services can supply equivalent JSON through REVIEW_V2_WORKER_POLICY. REMOTE-WORKERS.md includes Nova/Lyra examples, fallback semantics and rollout constraints. CHANGELOG highlights the new default GPU cap and higher/null overrides for multi-GPU hosts. The branch also brings accepted 2.4.0 release corrections back into dev before advancing to 2.5.0-dev2.

Validation: the original zero-GPU-cap regression failed before implementation. The query-plan regression failed before adding the covering index. Final CPU build/install checks passed 206 Node tests and 60 Python tests; both NixOS module evaluations and branch/version checks passed. Coverage includes real remote/local shared caps, competing remote workers, cancellation, busy/conflict recovery, preferred-host fallback, legacy upgrades, and an independent SQLite writer proving locks are released between remote claim requests.

Deployment remains operator-owned: live services and in-flight jobs were not changed. Upgrade all workers and stop a host's workers before changing its policy. Resident encoder memory is outside job-count limits; sustained memory/throughput and post-reboot deployment acceptance remain open.

Workers currently claim queued jobs without considering host GPU capacity or preferring an available GPU host. This adds a shared host policy with one combined tagging/vectorization job per host by default, independent CPU/per-kind budgets, allowed job kinds, and GPU priority with fallback when a preferred host is busy, ineligible or stale. Capacity reads and claims are atomic on the main server, including remote optimistic conflict retries; network requests never hold an open server transaction between replies. A state/host/kind covering index keeps scheduler lookups from scanning historical jobs. Same-host policy disagreement fails explicitly. Embeddings may run alongside ripping, tagging, purge and visual discovery; scans, moves and destructive deduplication retain exclusion. Both NixOS modules expose workerPolicy, and Fedora services can supply equivalent JSON through REVIEW_V2_WORKER_POLICY. REMOTE-WORKERS.md includes Nova/Lyra examples, fallback semantics and rollout constraints. CHANGELOG highlights the new default GPU cap and higher/null overrides for multi-GPU hosts. The branch also brings accepted 2.4.0 release corrections back into dev before advancing to 2.5.0-dev2. Validation: the original zero-GPU-cap regression failed before implementation. The query-plan regression failed before adding the covering index. Final CPU build/install checks passed 206 Node tests and 60 Python tests; both NixOS module evaluations and branch/version checks passed. Coverage includes real remote/local shared caps, competing remote workers, cancellation, busy/conflict recovery, preferred-host fallback, legacy upgrades, and an independent SQLite writer proving locks are released between remote claim requests. Deployment remains operator-owned: live services and in-flight jobs were not changed. Upgrade all workers and stop a host's workers before changing its policy. Resident encoder memory is outside job-count limits; sustained memory/throughput and post-reboot deployment acceptance remain open.
Prepare 2.4.0-rc.1 for remote-worker acceptance
All checks were successful
Branch and package checks / check (push) Successful in 42s
04ad6d1393
Preserve remote SQLite busy codes and record RC2 host recovery tests
All checks were successful
Branch and package checks / check (push) Successful in 46s
38055a956d
Fix visual dedup shutdown recovery for 2.4.0-rc.3
All checks were successful
Branch and package checks / check (push) Successful in 43s
7758390c08
Release 2.4.0 with accepted remote-worker validation limits
All checks were successful
Branch and package checks / check (push) Successful in 46s
Build and Push Attic Cache / build (pull_request) Successful in 15s
Branch and package checks / check (pull_request) Successful in 13s
AI pull-request review / review (pull_request) Successful in 3m3s
44b242e097
Add host-wide worker budgets and GPU preference with fallback
All checks were successful
AI pull-request review / review (pull_request) Successful in 2m48s
Build and Push Attic Cache / build (pull_request) Successful in 18s
Branch and package checks / check (pull_request) Successful in 12s
7915cb6503
Author
Owner

Automated code review

Reviewed commit: f14503d9ba4818405963ffdb1bd785d4c2b11c9e

Verdict: Requires further work

Resolve the blocking or important findings and investigate failed deterministic checks before merging.

Overall assessment

The pull request introduces host-wide worker policies for GPU and CPU job limits, per-kind restrictions, and GPU priority with fallback semantics. It adds a worker_presence table to track live worker capacity and policy, modifies the job claiming logic to respect these new constraints atomically within SQLite transactions, and updates NixOS modules to expose the configuration. The changes include schema upgrades, remote worker support for the new policy environment variable, and comprehensive test coverage for local and remote scenarios.

Blocking findings

None.

Important findings

  • Potential race condition in eligibleJobKinds with stale presence data (src/worker-policy.ts:68; medium confidence)
    The function eligibleJobKinds queries worker_presence to check for higher-priority hosts. It filters by seen_at >= now - PRESENCE_TTL_MS. However, if a host crashes without deregistering, its presence row remains until TTL expiry. The logic checks worker.available_slots <= 0 to skip busy hosts, but relies on the gpuPriority comparison. If a high-priority host is stale (crashed), it might still be considered 'available' if available_slots > 0 in the stale record, potentially blocking lower-priority hosts from claiming GPU jobs unnecessarily.
    Impact: GPU jobs may be delayed or unclaimed if a high-priority host crashes but its presence row hasn't expired yet, leading to reduced throughput on GPU resources.
    Suggested fix: Ensure that stale presence rows are treated as having 0 available slots or explicitly excluded from priority checks. The current code checks worker.available_slots <= 0, but if the stale record has slots > 0, it will block others. Consider adding a check for staleness before comparing priorities.

Suggestions

  • Hardcoded TTL value in worker-policy.ts (src/worker-policy.ts:6; medium confidence)
    The constant PRESENCE_TTL_MS = 30_000 is defined in the source file. While documented in REMOTE-WORKERS.md, hardcoding it in multiple places (if used elsewhere) or without a clear configuration option might make tuning difficult for operators with different network latencies.
    Impact: Operators may need to modify source code or rely on documentation to tune presence expiration, which is less flexible than a runtime configuration.
    Suggested fix: Consider exposing PRESENCE_TTL_MS as an environment variable or configuration option if it needs to be tuned per deployment.

  • Complexity in claimJob transaction with JSON injection (src/worker.ts:175; medium confidence)
    The claimJob function now uses eligibleJobKinds to get a list of kinds and injects them into the SQL query via json_each(?). This adds complexity to the transaction and relies on SQLite's JSON functions. If eligibleJobKinds returns an empty array, the query might behave unexpectedly or fail.
    Impact: Potential for unexpected behavior if no jobs are eligible, though tests cover this. The reliance on JSON functions adds a slight performance overhead compared to simple IN clauses.
    Suggested fix: Ensure robust handling of empty kinds arrays in the SQL query. Consider logging or alerting if no jobs are ever eligible due to policy misconfiguration.

Tests and validation

  • package-checks: success

Questions

  • How does the system handle a scenario where a worker's presence row is updated but the worker process dies immediately after, leaving stale data until TTL expiry? Does the fallback logic correctly identify this as 'busy' or 'stale'?
  • Are there any known issues with the json_each function in older SQLite versions that might be used by some deployments?
  • What is the expected behavior if maxJobsByKind is set to 0 for a specific kind? Does it effectively disable that kind on the host?

Review limitations

  • The review is based on provided diffs and documentation; live deployment testing was not performed.
  • Performance implications of the new covering index and worker_presence table under high concurrency were not benchmarked.
  • Security implications of the worker key granting full database access were noted in documentation but not deeply analyzed for potential escalation paths.

Diff coverage

  • AMD-WORKERS.md: reviewed — included in a context-limited batch
  • CHANGELOG.md: reviewed — included in a context-limited batch
  • REMOTE-WORKERS.md: reviewed — included in a context-limited batch
  • REQUIREMENTS-TRACE.md: reviewed — included in a context-limited batch
  • REQUIREMENTS.md: reviewed — included in a context-limited batch
  • VERSION: reviewed — included in a context-limited batch
  • acceptance/lyra-rc3-2026-10-05.md: reviewed — included in a context-limited batch
  • acceptance/release-2.4.0.md: reviewed — included in a context-limited batch
  • acceptance/remote-worker-rc2-2026-10-05.md: reviewed — included in a context-limited batch
  • nix/redview-v2.nix: reviewed — included in a context-limited batch
  • nix/remote-worker.nix: reviewed — included in a context-limited batch
  • nix/tests/remote-worker-module.nix: reviewed — included in a context-limited batch
  • nix/tests/v2-module.nix: reviewed — included in a context-limited batch
  • nix/worker-policy-options.nix: reviewed — included in a context-limited batch
  • package.json: reviewed — included in a context-limited batch
  • schema.sql: reviewed — included in a context-limited batch
  • src/remote-db.ts: reviewed — included in a context-limited batch
  • src/remote-worker-thread.ts: reviewed — included in a context-limited batch
  • src/schema-upgrade.ts: reviewed — included in a context-limited batch
  • src/similar.ts: reviewed — included in a context-limited batch
  • src/worker-policy.ts: reviewed — included in a context-limited batch
  • src/worker.ts: reviewed — included in a context-limited batch
  • tests/host-worker-policy.test.mjs: reviewed — included in a context-limited batch
  • tests/remote-worker.test.mjs: reviewed — included in a context-limited batch
  • tests/schema-guard.test.mjs: reviewed — included in a context-limited batch
  • tests/similar-dedup.test.mjs: reviewed — included in a context-limited batch
  • tests/visual-job-concurrency.test.mjs: reviewed — included in a context-limited batch
Review metadata
  • Reviewer: forgejo-ai-review v1
  • Model: qwen3.6:35b-a3b-q8_0
  • Guidance loaded: .forgejo/ai-review.md, .forgejo/ai-review.yml, AGENTS.md, README.md
  • Commits considered: 7
  • Previous automated review: updated
  • Findings: 3
<!-- forgejo-ai-review:v1 --> ## Automated code review Reviewed commit: `f14503d9ba4818405963ffdb1bd785d4c2b11c9e` ## Verdict: Requires further work Resolve the blocking or important findings and investigate failed deterministic checks before merging. ### Overall assessment The pull request introduces host-wide worker policies for GPU and CPU job limits, per-kind restrictions, and GPU priority with fallback semantics. It adds a `worker_presence` table to track live worker capacity and policy, modifies the job claiming logic to respect these new constraints atomically within SQLite transactions, and updates NixOS modules to expose the configuration. The changes include schema upgrades, remote worker support for the new policy environment variable, and comprehensive test coverage for local and remote scenarios. ### Blocking findings None. ### Important findings - **Potential race condition in `eligibleJobKinds` with stale presence data** (src/worker-policy.ts:68; medium confidence) The function `eligibleJobKinds` queries `worker_presence` to check for higher-priority hosts. It filters by `seen_at >= now - PRESENCE_TTL_MS`. However, if a host crashes without deregistering, its presence row remains until TTL expiry. The logic checks `worker.available_slots <= 0` to skip busy hosts, but relies on the `gpuPriority` comparison. If a high-priority host is stale (crashed), it might still be considered 'available' if `available_slots > 0` in the stale record, potentially blocking lower-priority hosts from claiming GPU jobs unnecessarily. Impact: GPU jobs may be delayed or unclaimed if a high-priority host crashes but its presence row hasn't expired yet, leading to reduced throughput on GPU resources. Suggested fix: Ensure that stale presence rows are treated as having 0 available slots or explicitly excluded from priority checks. The current code checks `worker.available_slots <= 0`, but if the stale record has slots > 0, it will block others. Consider adding a check for staleness before comparing priorities. ### Suggestions - **Hardcoded TTL value in `worker-policy.ts`** (src/worker-policy.ts:6; medium confidence) The constant `PRESENCE_TTL_MS = 30_000` is defined in the source file. While documented in `REMOTE-WORKERS.md`, hardcoding it in multiple places (if used elsewhere) or without a clear configuration option might make tuning difficult for operators with different network latencies. Impact: Operators may need to modify source code or rely on documentation to tune presence expiration, which is less flexible than a runtime configuration. Suggested fix: Consider exposing `PRESENCE_TTL_MS` as an environment variable or configuration option if it needs to be tuned per deployment. - **Complexity in `claimJob` transaction with JSON injection** (src/worker.ts:175; medium confidence) The `claimJob` function now uses `eligibleJobKinds` to get a list of kinds and injects them into the SQL query via `json_each(?)`. This adds complexity to the transaction and relies on SQLite's JSON functions. If `eligibleJobKinds` returns an empty array, the query might behave unexpectedly or fail. Impact: Potential for unexpected behavior if no jobs are eligible, though tests cover this. The reliance on JSON functions adds a slight performance overhead compared to simple IN clauses. Suggested fix: Ensure robust handling of empty `kinds` arrays in the SQL query. Consider logging or alerting if no jobs are ever eligible due to policy misconfiguration. ### Tests and validation - package-checks: **success** ### Questions - How does the system handle a scenario where a worker's presence row is updated but the worker process dies immediately after, leaving stale data until TTL expiry? Does the fallback logic correctly identify this as 'busy' or 'stale'? - Are there any known issues with the `json_each` function in older SQLite versions that might be used by some deployments? - What is the expected behavior if `maxJobsByKind` is set to 0 for a specific kind? Does it effectively disable that kind on the host? ### Review limitations - The review is based on provided diffs and documentation; live deployment testing was not performed. - Performance implications of the new covering index and `worker_presence` table under high concurrency were not benchmarked. - Security implications of the worker key granting full database access were noted in documentation but not deeply analyzed for potential escalation paths. ### Diff coverage - `AMD-WORKERS.md`: **reviewed** — included in a context-limited batch - `CHANGELOG.md`: **reviewed** — included in a context-limited batch - `REMOTE-WORKERS.md`: **reviewed** — included in a context-limited batch - `REQUIREMENTS-TRACE.md`: **reviewed** — included in a context-limited batch - `REQUIREMENTS.md`: **reviewed** — included in a context-limited batch - `VERSION`: **reviewed** — included in a context-limited batch - `acceptance/lyra-rc3-2026-10-05.md`: **reviewed** — included in a context-limited batch - `acceptance/release-2.4.0.md`: **reviewed** — included in a context-limited batch - `acceptance/remote-worker-rc2-2026-10-05.md`: **reviewed** — included in a context-limited batch - `nix/redview-v2.nix`: **reviewed** — included in a context-limited batch - `nix/remote-worker.nix`: **reviewed** — included in a context-limited batch - `nix/tests/remote-worker-module.nix`: **reviewed** — included in a context-limited batch - `nix/tests/v2-module.nix`: **reviewed** — included in a context-limited batch - `nix/worker-policy-options.nix`: **reviewed** — included in a context-limited batch - `package.json`: **reviewed** — included in a context-limited batch - `schema.sql`: **reviewed** — included in a context-limited batch - `src/remote-db.ts`: **reviewed** — included in a context-limited batch - `src/remote-worker-thread.ts`: **reviewed** — included in a context-limited batch - `src/schema-upgrade.ts`: **reviewed** — included in a context-limited batch - `src/similar.ts`: **reviewed** — included in a context-limited batch - `src/worker-policy.ts`: **reviewed** — included in a context-limited batch - `src/worker.ts`: **reviewed** — included in a context-limited batch - `tests/host-worker-policy.test.mjs`: **reviewed** — included in a context-limited batch - `tests/remote-worker.test.mjs`: **reviewed** — included in a context-limited batch - `tests/schema-guard.test.mjs`: **reviewed** — included in a context-limited batch - `tests/similar-dedup.test.mjs`: **reviewed** — included in a context-limited batch - `tests/visual-job-concurrency.test.mjs`: **reviewed** — included in a context-limited batch <details><summary>Review metadata</summary> - Reviewer: forgejo-ai-review v1 - Model: qwen3.6:35b-a3b-q8_0 - Guidance loaded: .forgejo/ai-review.md, .forgejo/ai-review.yml, AGENTS.md, README.md - Commits considered: 7 - Previous automated review: updated - Findings: 3 </details>
Index scheduler capacity reads and address MR review evidence
All checks were successful
Build and Push Attic Cache / build (pull_request) Successful in 12s
Branch and package checks / check (pull_request) Successful in 7s
AI pull-request review / review (pull_request) Successful in 3m0s
f14503d9ba
Author
Owner

Assessed the automated review of 7915cb6 and pushed corrections in f14503d (2.5.0-dev2).

The assertion that an immediate SQLite transaction remains open across remote network requests is not valid. RemoteDb.transaction accumulates statements through rolled-back previews; createCommandExecutor commits or rolls back each request before replying. The final server request replays and validates the capacity reads with the claim. Moving those reads outside the transaction would allow workers to exceed host budgets. The new focused test uses an independent SQLite writer between requests, checks server.inTransaction is false after each reply, and inserts another GPU job after a preview: the claim encounters a conflict, retries, and leaves the queued GPU job unclaimed.

The general read-cost concern was useful: EXPLAIN QUERY PLAN confirmed the running-job lookup scanned historical jobs. Added a covering (state, worker_host, kind) index in fresh schemas and upgrades, after legacy worker columns are added. The focused query-plan test failed before the index and passes now. Legacy and repeated-upgrade regressions pass too. Existing busy-database and optimistic-conflict handling remains intact.

The default GPU-cap documentation suggestion is addressed with a prominent CHANGELOG upgrade note explaining one combined tag/vector job per host and the higher/null overrides for multi-GPU operators. The fixed 30-second presence TTL is a documented deployment choice, not a demonstrated defect; no additional tuning option is added in this correction. Existing migrations already check columns before ALTER TABLE, and the new index uses IF NOT EXISTS.

Answers to the review questions: policy/priority changes require restarting the host's workers together; in-flight jobs are not preempted. publishWorkerPresence prunes expired rows on every publication, while stale rows are also excluded from eligibility reads; no separate cleanup job is needed. json_each receives at most the ten recognized job kinds, and the current unique active-job-per-kind rule bounds the queued/running set. The new state-leading index also avoids scanning history for these scheduler lookups.

Final local CPU package build/install checks passed 206 Node tests and 60 Python tests. Both NixOS module evaluations passed for the policy implementation; their configuration is unchanged by this correction. Production contention/throughput acceptance remains open. No live services or jobs were changed, and this MR remains unmerged pending fresh checks/review.

Assessed the automated review of 7915cb6 and pushed corrections in f14503d (2.5.0-dev2). The assertion that an immediate SQLite transaction remains open across remote network requests is not valid. RemoteDb.transaction accumulates statements through rolled-back previews; createCommandExecutor commits or rolls back each request before replying. The final server request replays and validates the capacity reads with the claim. Moving those reads outside the transaction would allow workers to exceed host budgets. The new focused test uses an independent SQLite writer between requests, checks server.inTransaction is false after each reply, and inserts another GPU job after a preview: the claim encounters a conflict, retries, and leaves the queued GPU job unclaimed. The general read-cost concern was useful: EXPLAIN QUERY PLAN confirmed the running-job lookup scanned historical jobs. Added a covering (state, worker_host, kind) index in fresh schemas and upgrades, after legacy worker columns are added. The focused query-plan test failed before the index and passes now. Legacy and repeated-upgrade regressions pass too. Existing busy-database and optimistic-conflict handling remains intact. The default GPU-cap documentation suggestion is addressed with a prominent CHANGELOG upgrade note explaining one combined tag/vector job per host and the higher/null overrides for multi-GPU operators. The fixed 30-second presence TTL is a documented deployment choice, not a demonstrated defect; no additional tuning option is added in this correction. Existing migrations already check columns before ALTER TABLE, and the new index uses IF NOT EXISTS. Answers to the review questions: policy/priority changes require restarting the host's workers together; in-flight jobs are not preempted. publishWorkerPresence prunes expired rows on every publication, while stale rows are also excluded from eligibility reads; no separate cleanup job is needed. json_each receives at most the ten recognized job kinds, and the current unique active-job-per-kind rule bounds the queued/running set. The new state-leading index also avoids scanning history for these scheduler lookups. Final local CPU package build/install checks passed 206 Node tests and 60 Python tests. Both NixOS module evaluations passed for the policy implementation; their configuration is unchanged by this correction. Production contention/throughput acceptance remains open. No live services or jobs were changed, and this MR remains unmerged pending fresh checks/review.
nimmo deleted branch feature/host-worker-policy 2026-10-07 16:25:13 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
nimmo/redview!18
No description provided.