Commit Graph
1 Commits
Author SHA1 Message Date
b7168dcb39 feat: job engine (#2718)
* feat(jobs): pure core for the server-side job engine — types, expression evaluator, graph validation

Phase 1 of the generic job engine (own PR). Header-only and unit-tested with
no server dependency:
- job_types.h: Job/StepRecord/Case model with JSON round-tripping.
- job_expr.h: ${ref} resolution + the when/branch evaluator (references,
  literals, comparisons, boolean logic, basic arithmetic; no arbitrary code).
- job_graph.h: step-graph validation — unique ids, known ops, forward-only
  jump targets (forward-only ⇒ acyclic ⇒ no loops).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* docs(jobs): reference for the recipe expression language

Document the when/branch condition grammar and ${ref} resolution: paths,
type-preserving vs interpolating params, literals, operator precedence,
truthiness, comparison/arithmetic semantics, errors, the non-short-circuit
caveat, and worked examples. EBNF included.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* feat(jobs): engine, read-only ops, and server wiring (Phase 2)

Add the generic job engine on top of the Phase 1 pure core: a single
persistent worker runs one client-posted job at a time, passing data
forward through the job context, evaluating forward-only branches, and
persisting every transition to <cache_dir>/jobs.json (atomic temp+rename,
50-job cap). A restart marks in-flight jobs interrupted but resumable from
their cursor.

- OpHandler/OpRegistry plus read-only ops (system_info, system_stats,
  models, sleep), built from injected providers so job_ops does not depend
  on the whole Server.
- JobManager lifecycle: create/list/get/pause/interrupt/resume/remove.
- Seven quad-prefixed HTTP handlers; path-param routes registered manually
  across /api/v0,/api/v1,/v0,/v1.
- test/server_jobs.py drives the full lifecycle end-to-end with an isolated
  lemond (no model load), including kill-and-restart persistence recovery.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* feat(jobs): log the job lifecycle

INFO on create/run/complete/pause/interrupt/resume/delete and startup
recovery; WARN with the failure reason on on_fail continue/goto and on
persist/load errors; ERROR on job failure; DEBUG for per-step
running/completed/skipped. Category 'Jobs'.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* feat(jobs): exclusive ops + Router slot gate (Phase 3)

Add the load/unload/chat exclusive ops and a Router-level exclusive gate
keyed by owner thread so a running job queues all normal load/inference
traffic behind it, plus cancel-of-in-flight-load.

- Router: exclusive_active_/exclusive_owner_/exclusive_cv_ under load_mutex_;
  begin_exclusive/end_exclusive and wait_for_slot_clearance inserted at
  load_model, unload_model, execute_inference, execute_streaming.
- WrappedServer::set_load_cancel_flag + wait_for_ready abort-and-kill;
  load_model threads a cancel flag and skips the nuclear retry on cancel.
- OpProviders/OpRegistry gain load/unload/chat callbacks and begin/end
  exclusive; JobManager holds the slot for any job with an exclusive step,
  releasing it exactly once via a guard on every exit path.
- server_jobs.py: real load->chat->unload job (asserts timings/usage),
  queue-behind-job timing test, interrupt-mid-job clean-release test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* feat(jobs): unload resident model when an exclusive job is interrupted

An interrupted exclusive job abandons its run and could leave a model
loaded. Reconcile by unloading (router unload-all) while the worker still
owns the slot, before releasing the gate. Test asserts /health reports no
model loaded after interrupt.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* test(jobs): bench-shaped sweep E2E (Phase 4)

Post the AutoOpt methodology as a job: two configs, each unload->load(args)
->timed chat->unload, extract timings into context, then branch on the
measured tps to pick a winner. Proves the engine runs the real bench recipe
end-to-end with no engine changes. Also asserts no model left resident.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* docs(jobs): job system reference, API entry, and AGENTS endpoints (Phase 5)

Add docs/dev/job-system.md (concepts, ops, recipe schema, control flow,
lifecycle, exclusivity/queuing, persistence, API, bench example); a Job
Engine API section in docs/api/lemonade.md; and the jobs endpoints in
AGENTS.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* style(jobs): remove code comments; documentation lives in docs/

Strip all comments from the job-engine sources and tests, and remove the
comments added to the shared router/wrapped_server/server files. The
concepts they described are documented in docs/dev/job-system.md and
docs/dev/job-expression-language.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): address job-engine code review

- GET /jobs no longer 405s: exclude jobs from the POST GET-fallback
- delete of an active job defers erase until the worker finishes cleanup
  (reconcile unload), so exclusive jobs never leak a resident model
- chat interrupt is now a genuine in-flight HTTP abort (curl XFERINFO)
  threaded via chat_op -> Router::chat_completion -> forward_request
- interrupt cleanup unloads only models the job loaded: exclusive session
  snapshots the loaded set at begin and reconcile unloads (current - snapshot),
  leaving pre-existing and pinned models
- load gate uses one combined predicate wait on load_cv_ so an exclusive
  session that begins mid-wait cannot be bypassed; begin/end_exclusive notify it
- nuclear retry sets the load cancel flag so interrupt aborts backend startup
- expression validation runs the full parser (syntax-only) to reject
  malformed when/branch expressions at creation, deferring ref/type errors
- id_counter restored to max parsed suffix on load; pending steps marked
  skipped at completion; step ids reject 'inputs' and '.'
- CI builds and runs JobExprTest/JobGraphTest and server_jobs.py

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): per-request chat cancel + drain in-flight loads before exclusive snapshot

Two concurrency defects found by adversarial review of the review-fix commit:

- The chat cancel flag lived on a shared per-server member, so a concurrent
  non-job chat to the same model adopted the job's flag (aborted on interrupt)
  and the RAII reset raced an HTTP thread reading the non-atomic pointer. Move
  it to a per-thread (thread_local) pointer: each request thread carries its
  own, no sharing, no race.
- begin_exclusive set the gate but did not drain an in-flight concurrent load,
  so a model that finished loading just after the job claimed the slot was
  missing from the snapshot and got evicted by the interrupt reconcile. Wait
  for is_loading_ to clear before returning so the snapshot is complete.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): windows-safe persist, pinned-model reconcile, load-cancel cleanup, CI

- persist jobs.json via atomic_replace_file (MoveFileExW on Windows,
  rename on POSIX, copy+remove cross-device fallback)
- reconcile-unload now evicts job-introduced models even if pinned;
  only pre-job snapshot models are preserved
- clear load_cancel pointer after every load via RAII guard
- run server_jobs.py in the Linux PR CI job
- tests: multi-write persistence, pinned-model delete/interrupt cleanup,
  preexisting-pinned survival

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): eliminate load-cancel use-after-free; verify persist write

Adversarial review of the round-2 fixes found:
- LoadCancelGuard (function scope) wrote set_load_cancel_flag(nullptr) into a
  WrappedServer already freed during exception unwinding on every load-failure
  path (file-not-found, cancelled, retry failure) — a UAF write on a hot error
  path. Clear the flag inline while each server is still alive, right after its
  load attempt; drop the guard.
- persist_locked promoted the temp without checking the ofstream, so a partial
  write (disk full) could atomically replace a good jobs.json with truncated
  JSON. Verify the stream succeeded before replacing; drop the temp otherwise.
- atomic_replace_file did not propagate the copy-fallback error_code.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* Remove source section from job-system.md

Removed source section from job-system documentation.

* docs(jobs): document extending the engine with new-modality ops

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): round-4 review — durable delete, immediate queued control, full exclusivity, scoped cleanup, cap, progress

- load op: drop the late-cancel global unload; snapshot reconciliation cleans up
- active-job DELETE persists a tombstone before the ack; restarts drop
  tombstoned jobs and they are invisible to GET/list immediately
- pause/interrupt on a queued job dequeues and persists the new status
  immediately instead of waiting for the worker
- begin_exclusive drains in-flight requests after closing the gate; tokenize,
  slots, get_slots, and set_model_pinned now check the same gate
- the exclusive snapshot records pin state and reconcile restores it on
  surviving pre-job models; the docs state the preserve-if-still-resident
  guarantee explicitly (evicted models are not reloaded)
- POST jobs returns 429 when the 50-job store has nothing terminal to evict
- summary progress counts handled failures (on_fail continue/goto) as processed

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): adversarial-review follow-ups — eviction-engine gate respect, cancellable drain, tombstone scrub, test hardening

- the idle-eviction/downsize engine suspends during exclusive sessions, and
  evict_if_committed rescues a model that got (re-)pinned or caught by an
  exclusive session after its EVICTING mark — fixes the reconcile-repin TOCTOU
- begin_exclusive(cancel) polls the job's cancel flag while draining, so
  interrupt/delete/shutdown abort the acquisition instead of blocking behind a
  long-running stream; an aborted acquisition marks the job interrupted and
  never runs a stale-snapshot reconcile
- the job cap counts only live jobs (a tombstoned active job no longer 429s
  creation), and startup scrubs tombstoned payloads from jobs.json
- tests: pin-restore of a surviving pre-job model is now asserted end-to-end;
  the durable-delete test asserts the tombstone on disk before the crash;
  the drain test tolerates client-read lag; real-backend tests self-install
  the cpu backend once and seed it into each test cache so they run in CI

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): close the store before the startup scrub; pin-only loads update in place

- load_from_disk closes jobs.json before the tombstone-scrub persist, so the
  Windows replace does not hit a sharing violation on the startup it targets
- 'pinned' no longer participates in the option-change reload diff: it never
  reaches the subprocess command line, so a pin-only load updates the pin in
  place instead of evicting and reloading the model
- the pin-restore test asserts PID stability so it fails if the pre-job model
  is reloaded rather than surviving; the one-time backend install records
  failed attempts and handles request timeouts instead of retrying per test

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): keep the stored pin option in sync with the pin flag

set_pinned now updates recipe_options_ alongside the pinned_ flag (guarded by
state_mutex_, since recipe_options_ is no longer immutable after publish), so
/health no longer self-contradicts after an in-place pin update and a *_bin
hot-swap reload cannot resurrect a cleared pin from stale stored options. Also
fixes the same pre-existing mismatch in the set_model_pinned endpoint.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): job model ownership survives pause/resume; delete-while-paused reconciles

The exclusive snapshot is now per-job and captured once, the first time the
job acquires the slot — a pause/resume cycle no longer re-baselines it, so a
model the job loaded before pausing is still recognized as job-introduced and
cleaned up on a later interrupt or delete. Deleting a paused or interrupted
job routes through the worker for the same snapshot reconcile instead of being
erased without cleanup. Jobs that end completed/failed commit their model
side-effects (snapshot discarded). Reconcile is keyed by job id and is a no-op
for jobs that never held the slot.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): don't leak the pinned key into recipe_options on unpinned loads

set_pinned records the option only for a genuine pin and erases it otherwise —
an absent key already means unpinned, so the flag/options consistency for the
*_bin hot-swap is preserved while auto-load keeps its request-scoped-field
contract (server_endpoints test_013, test_ollama test_015a).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): instance-scoped job model ownership; restore adopts external residency

Reconcile no longer treats every post-snapshot model as job-owned. Ownership
is explicit and scoped to the specific residency the job created: the load op
records the backend instance (pid) it produced, the unload op relinquishes
ownership, and reconcile unloads a resident model only when it is that same
instance — so external loads of any model, including the same name while the
job is paused or interrupted and the gate is open, are never touched by job
cleanup. Pre-job snapshot membership still takes precedence (residents
preserved, pin state restored).

Interrupt cleanup records each owned instance's options and pin before
unloading, and resume reloads them (cancellable) before re-running from the
cursor, so a step that depends on an earlier completed load — e.g. a chat
interrupted mid-generation — finds its model again. If an external client
re-loaded the same model meanwhile, the restore adopts that residency instead
of replacing it and the model stops being job-owned. A failed restore logs and
lets the dependent step fail with its normal on_fail semantics.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(jobs): reconstruct job model state from completed steps on post-restart resume

Ownership and captured restore state are in-memory, so a hard restart lost
them: a job recovered as interrupted would resume its pending step without the
model an earlier completed load had established. Resume now also receives a
manifest reconstructed from the job's persisted record — completed load and
unload steps in execution order (forward-only, so list order), with parameters
resolved against the persisted context. In-memory captured entries take
precedence when present; manifest leftovers are loaded, or adopted if an
external client already loaded the model.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Z9WMqprhqjWEDuv1gnGaH

* fix(ci): MacOS whisper mutex added

* fix: sleep timer drift

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Florian Reinle <[email protected]>
2026-07-17 19:38:03 +00:00