Skip to content

server: separate legacy and experimental parallel jobs runtimes - #715

Merged
0xShug0 merged 12 commits into
0xShug0:mainfrom
mirek190:agent/common-slot-framework-20260927
Oct 4, 2026
Merged

0xShug0 merged 12 commits into
0xShug0:mainfrom
mirek190:agent/common-slot-framework-20260927

Conversation

@mirek190

@mirek190 mirek190 commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds an experimental server runtime selected only by --parallel-jobs, keeping the original server and CLI path separate. Following the maintainer's latest feedback, the current focus is startup isolation and normal inference/cold initialization. Lifecycle expectations are specified, while incomplete coverage is explicitly reported.

# Original implementation
audiocpp_server --config server.json

# Experimental implementation; prints tested/untested scope at startup
audiocpp_server --config server.json --parallel-jobs
Startup Slots field Result
Flag absent Absent Original ServerState and HTTP listener
Flag absent Any explicit value, including 1/null Configuration error; dynamic registration HTTP 400
Flag present Absent Separate ParallelServerState, capacity one
Flag present Integer 1-16 Same parallel runtime, limited by advertised model capacity

Slot count does not select or switch the implementation. Flagged capacity one uses the new pool/FIFO lifecycle. Admission tables remain empty: catalogue model adapters and admission remain in #706. Controlled 1/2/4-slot fixtures do not enable real checkpoints at those counts.

One authoritative behavior contract

Parallel Server Behavior Contract is the single authority for expected behavior, validation scope and known limits. It includes:

  • Unloaded/loading/ready/reconfiguring/unloading/shutting-down states, and queued versus admitted-initializing/executing/streaming requests.
  • Operation/state matrices for inference, registration/reconfiguration, targeted/bulk unload, eviction, status and shutdown.
  • The requested two-model matrix, both arrival orders, spare/full capacity, same/different models, and overlapping bulk selections.
  • Failure boundaries, recovery, timeout, disconnect and shutdown matrices with linked regressions and direct/partial/untested evidence annotations.
  • Validation by area, including the exact model/backend/count scope and known missing evidence.

The adapter guide now links to the contract instead of duplicating server lifecycle rules. Historical reports are labelled as revision-scoped evidence. The validation procedure references contract cells and preserves M1-M6/output-quality requirements; shared coverage is collected once rather than repeated for every model.

Validation area Current scope
Concurrent inference Partially tested: controlled independent sessions/FIFO at 1/2/4; real CUDA/Vulkan capacity-one cold/warm/reload only
Cold loading Partially tested: controlled publication, failure/retry and guarded cold-vs-warm progress; representative capacity-one checkpoints
Reconfiguration Partially tested: controlled ordering, resize, invalid metadata/capability preservation and retry; changed-checkpoint multi-slot GPU staging not validated
Unloading/eviction Partially tested: controlled lazy-load barriers, overlapping bulk selections, limits 1/2 and slow retirement; exhaustive device/fault recovery missing
Disconnects Partially tested: controlled dropped callbacks/write failure and loopback stalled I/O; prompt queued cancellation and real streaming adapter recovery missing
Shutdown Partially tested: default listener joins finite handlers/callbacks and cancels socket I/O; queued/cold-load/management shutdown, hung GPU and custom listeners untested

Unsupported-capacity fix and startup warning

Follow-up c28d3715 fixes the maintainer's slots=5 regression on the opt-in path. An unsupported replacement returns HTTP 400 while retaining the working pool, configuration, count and residency. The manager lease releases, subsequent inference works, and valid resizing still succeeds.

For unchanged session inputs, validate against the live pool's advertised capacity without creating another session. Changed task/options/checkpoint require a private primary capability probe before teardown, reusing immutable loaded assets where possible. A failed probe preserves old state. A changed checkpoint may require temporary duplicate weights and an additional primary construction; GPU staging-memory coverage remains unverified. No eviction is performed merely to probe replacement capacity. A load/clone failure after successful validation and configuration commit still leaves the complete new registration unloaded for retry.

Startup warning explicitly identifies the experimental path, controlled CPU/representative CUDA/Vulkan capacity-one coverage, incomplete lifecycle coverage, unvalidated catalogue multi-slot/real concurrent stream/batch/Metal execution, and the absence of backend cancellation. Default startup prints no parallel warning.

Separation and ownership

Against recorded upstream 2892ed3e, protected original runtime headers, busy guard, HTTP/frontend files, session interface, CLI, existing model implementations and ggml have no diff. Original runtime.cpp adds only explicit-slots rejection for dynamic registration. No CUDA/Vulkan kernel or model change is included.

The parallel runtime owns its registry/pools/leases; the default parallel listener owns, reaps and joins HTTP workers before runtime destruction. JSON parser synchronization is startup-only opt-in. Tensor-source and resource-cache synchronization require explicit options; no existing model loader is opted in implicitly. Custom listeners retain the existing interface and must independently drain before returning.

Previous audit 366e7520 added stable first-registration publication, metadata-safe policy reads, atomic publication of overlapping bulk barriers, null-primary rejection, staged UI folder replacement and owned HTTP workers. Its results remain historical evidence, not complete catalogue admission.

Validation

Follow-up local Windows/MSVC checks on c28d3715, RTX 3090, CUDA 12.4 / Vulkan SDK 1.4.350.0:

Check Result
New unsupported-capacity test against previous runtime Fails: working registration changed/destroyed
Controlled rejection at existing capacities 1/2/4 Nine rejection cases pass; pool/config/count retained; valid resize afterward
CPU framework/framing/ownership CTests 14/14 pass
Windows AddressSanitizer CTests 11/11 pass
CUDA CLI/server build with native management Pass
Vulkan CLI/server build with native management Pass
Real checkpoint capacity rejection and reuse 12/12 pass across three checkpoints, both backends, legacy/parallel; 36 inference responses
Experimental startup warning Four cases pass: flagged present, legacy absent, CUDA/Vulkan
Protected-source boundary and whitespace Pass
Behavior-contract test anchors/table structure Pass

Real checkpoint follow-up uses Piper TTS, Canary ASR and Nemotron diarization. Each runs cold/warm, rejects slots=5, retains exact status, and returns an identical subsequent warm output/meaningful metadata after removing only top-level execution timing. This checks rejection/reuse at capacity one; it is not a multi-slot, performance or graceful-process-shutdown benchmark.

On parent 366e7520, all 11 remote checks completed successfully, including Linux/macOS/Windows builds/lifecycle and Linux ASan/TSan. Its local record includes 96 matched upstream/legacy/flagged checkpoint responses and 40 repeated lifecycle/HTTP ownership executions. CI on this new follow-up revision is tracked separately and remains pending until completed.

Known limits: busy timeout bounds admission, not backend execution; queued disconnects are not immediately canceled; shutdown waits for finite workers and can hang on backend/init/management waits; bulk unload is snapshot-based/non-atomic; logical unloaded status is not proof that physical allocations are freed; cold-load guards intentionally serialize guarded loads; independent sessions do not guarantee GPU overlap. Allocation/thread-construction fault paths are source-audited where no injection exists. New failed/unsupported registrations can remain unloaded until corrected; the preservation fix protects existing working registrations.

Adapter guide ? Future model validation procedure ? Historical self-audit.

@mirek190

mirek190 commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated the testing procedure in this PR: parallel model validation.

It now defines per-backend/task/checkpoint tests at every advertised slot count, original/candidate single-slot references, cold/warm and mixed-request parity, repeated operation, lifecycle recovery, and measured throughput/memory.

It also adds the ownership/state-transition scenarios raised by the maintainer: disconnects, queued reconfiguration, partial loading, management/timeout boundaries, cross-model contention and shutdown, with controlled interleavings and applicable sanitizer evidence.

The document separates completed coverage from required/pending checks. This commit changes documentation only; it does not claim that the expanded matrix has run or enable additional models. Model implementation and admission continue in #706.

@0xShug0

0xShug0 commented Sep 27, 2026

Copy link
Copy Markdown
Owner

@0xShug0

Suggestion for a full test procedure for testing models for a multi slot implementation to pass tests?

Can be something like that ? #706 (comment)

I don’t have a good suggestion right now. I usually just come up with some random ideas from a quick skim and only think about comprehensive testing once the PR is next in line for review.

#706 is still too large for me to review. I’m pretty tight on disk space right now, and testing all the models means I need to constantly delete and redownload things. Some of the fixes and optimizations are unrelated to multi-slot and also benefit normal single-session use. Could you extract those into a separate PR (or two PRs based on whether they are community models) based on main?

@mirek190 mirek190 closed this Sep 27, 2026
@mirek190 mirek190 reopened this Sep 27, 2026
@mirek190

Copy link
Copy Markdown
Contributor Author

@0xShug0
Suggestion for a full test procedure for testing models for a multi slot implementation to pass tests?
Can be something like that ? #706 (comment)

I don’t have a good suggestion right now. I usually just come up with some random ideas from a quick skim and only think about comprehensive testing once the PR is next in line for review.

#706 is still too large for me to review. I’m pretty tight on disk space right now, and testing all the models means I need to constantly delete and redownload things. Some of the fixes and optimizations are unrelated to multi-slot and also benefit normal single-session use. Could you extract those into a separate PR (or two PRs based on whether they are community models) based on main?

Sure

@mirek190

Copy link
Copy Markdown
Contributor Author

Simplified the model validation procedure and updated the PR description, session contract, framework report and server README.

  • F1-F6 are shared framework checks collected once per applicable revision/backend and referenced by models.
  • M1-M6 are per-model quality, slot-count, history, recovery, memory and applicable-mode checks.
  • Memory is sampled in the existing quality runs; provenance is recorded in a reusable manifest. CPU checkpoint tests depend on whether CPU behavior is affected. Independent-server benchmarks are optional performance evidence.
  • Exact outputs/meaningful metadata, equivalent cache histories, three fresh starts at every advertised count and ten mixed warm waves per start at the largest count remain required. Precision/overlap settings and known AuK/Apollo failures are unchanged.
  • Model and shared framework verdicts are separate; both required gates must pass for admission. Missing shared evidence remains pending and blocks admission.

Documentation only: no new runtime changes/admission or validation passes are claimed, and historical results are not automatically reclassified.

@0xShug0

0xShug0 commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner

@mirek190 Thanks for the update! BTW I’m doing some framework refactoring right now, so there may be some back-and-forth on the contracts. You can hold off on splitting the PR until later (maybe tomorrow).

@mirek190

Copy link
Copy Markdown
Contributor Author

@mirek190 Thanks for the update! BTW I’m doing some framework refactoring right now, so there may be some back-and-forth on the contracts. You can hold off on splitting the PR until later (maybe tomorrow).

So you DO ;)
Nice
Waiting for your changes!

@0xShug0

0xShug0 commented Sep 29, 2026

Copy link
Copy Markdown
Owner

@mirek190 Check out the new things on README.

@mirek190

mirek190 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@mirek190 Check out the new things on README.

ok I see
https://huggingface.co/spaces/audio-cpp/Audio-Model-Architecture-Atlas

The Architecture Atlas is a static architecture guide, not a model test suite.
It on contains runnable inference tests, benchmarks, or slot-validation results.

So my testing guide is fine?
I could add model by model in alphabetical order (or 10 in bath). to the slot server implementation.
Not implemented models will be work with a one slot ( like a legacy implementation in serial so will be fully backwards compatible )
What do you think ?

@0xShug0

0xShug0 commented Sep 29, 2026

Copy link
Copy Markdown
Owner

Yes, Atlas is a learning resource. I just merged #734. There may be another pass today, and after that I’ll take a look at the testing guide and get back to you.

@mirek190

mirek190 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Sure no a problem.

So ... can you merge this PR ?
Then we can adding models one after another.
Not implemented models will be work in legacy mode without any changes.

@0xShug0

0xShug0 commented Sep 29, 2026

Copy link
Copy Markdown
Owner

okay let me test this PR later today.

@mirek190

Copy link
Copy Markdown
Contributor Author

okay let me test this PR later today.

waiting ;)

@0xShug0

0xShug0 commented Sep 30, 2026

Copy link
Copy Markdown
Owner

@mirek190 Hold on... I found a family of related issues. I'll let Codex organize the findings into a report instead of relying on my messy notes.

@0xShug0

0xShug0 commented Sep 30, 2026

Copy link
Copy Markdown
Owner

I found five causes of single-slot regressions. The earlier overdue-request rejection issue is fixed, but request ordering, unloading, and cross-model locking still need work.

Tested PR head 0588ec27db604da1cdcf7c7e4921367aef303fd5 against its base 77491a33c589c53ff18add050095cf35647c8213, using matching RelWithDebInfo builds on an Apple M4 Pro, 24 GiB unified memory, Metal, four inference threads. slots was omitted: every model had one slot. Production code was unchanged, and all runs collected server logs with --log. The results below are from local testing; raw logs are not attached.

Times below distinguish HTTP response latency from model execution time. Scheduling failure counts are observed results on this machine; exact failing rounds can vary.

1. Management overtakes requests that were already waiting

What changed from main: The base uses the same execution guard for inference and management. The PR explicitly blocks inference admission whenever management is waiting. A queued request is not bound to the model configuration under which it was accepted.

This produces two related failures:

Reconfiguration changes the model underneath a queued request.

  1. Register Piper with server model ID shared. This is an arbitrary ID chosen by the test.
  2. Start a speech request with "model": "shared"; queue another 40 ms later.
  3. After another 20 ms, call /v1/models/load with "id": "shared" and Canary ASR's family, task, and checkpoint. This replaces Piper under the same server ID.

Base serves both WAVs, then reconfigures. The PR reconfigures first, and the queued speech request fails with HTTP 500: Canary ASR requires audio input. The first request's WAV is identical between builds.

Unload is followed by a reload from older queued work.

Warm the model, start inference, queue a second request, then submit unload. Send no further inference requests. Base runs the waiter before unloading in this test; the PR unloads first, then the waiter reloads the model. Both requests and unload return 200, but the PR ends with the model loaded.

This reproduced on Piper in 3/3 rounds. A NeuTTS follow-up measured the cost using "Good morning. Your train leaves at nine.", seed 42, default generation settings, and 100 ms between submissions:

Three-round result Base PR
Warm control: model execution 1052.20 ms 1052.04 ms
Queued request: HTTP latency 1996.24 ms 6932.11 ms
Queued request: model execution 1054.29 ms 1079.91 ms
Model loads across three rounds 3 6
Still loaded after all requests and unload finish 0/3 3/3
Process physical footprint after three idle seconds 1241.03 MiB 2734.45 MiB
Footprint after a second explicit unload 1241.03 MiB 1264.29 MiB

The extra latency comes mainly from reloading, not slower inference. Memory is current macOS process physical footprint, including unified-memory allocations. The second unload releases about 1470 MiB on the PR: this is retained model state, not evidence of an unreachable-memory leak.

All NeuTTS requests produced complete 3.48-second audio. Warm-control and active-request WAVs match across builds. The PR's queued WAV matches its fresh-session output; base uses an already-warmed session, so that pair has different session histories.

Code: request admission predicate.

2. Later requests can delay older waiters enough to cause timeouts

What changed from main: Base's mutex wakes one waiter on this platform. The PR broadcasts on release, and awakened callers compete again without an admission queue. Neither implementation promises FIFO; the regression here is measured latency and deadline failures.

Reproduce: Warm a model, start a longer request, queue one short request, then submit later short requests 2 ms apart. No management operations are involved.

Workload Oldest request's wait budget Base timeouts PR timeouts
Piper, eight later requests 350 ms 0/5 3/5
Piper, sixteen later requests, A/B then B/A 350 ms 0/10 5/10
Canary ASR, eight later requests, A/B then B/A 650 ms 0/10 2/10
Nemotron diarization, eight later requests 60 ms 0/5 4/5

The first two submission gaps are 25 ms for Piper/Canary and 2 ms for diarization. Successful outputs match.

With Piper's wait budget raised to 30 seconds, all requests succeed, but the oldest waiter's mean HTTP latency rises from 228.80 to 299.24 ms (+30.8%). Median model execution stays 56.468 versus 56.453 ms, and WAVs are byte-identical. This is scheduling overhead rather than slower model compute.

A related management-only test also changes observed ordering: while Piper runs, queue replacement with Canary, then selection of Piper 25 ms later. Both calls return 200, but the PR ends on Canary in 3/20 rounds versus 0/20 on base. Overlapping management calls have no documented last-submitted-wins guarantee, so this is an ordering caveat, not a separate contract violation or root cause.

Code: release wake-up.

3. Bulk unload delays releasing unrelated idle models

What changed from main: Base skips a first load whose session is not yet published. The PR waits for that load in registration order before releasing later models.

Reproduce: Register lazy NeuTTS first and Piper second. Warm Piper, start NeuTTS's first load, then call /v1/tasks/unload_all_models 25 ms later.

Base releases Piper immediately. The PR leaves Piper loaded behind the roughly 4.75-second NeuTTS load. This repeated in reverse build order; read-only status polling still showed Piper loaded after four seconds. Piper's weight buffer alone is about 59.70 MiB.

The base bulk request took 1.01 ms in the confirmation run; the PR took 4768.94 ms. The concern is delayed release of idle Piper, not that waiting for NeuTTS makes bulk completion slower.

Code: bulk drain loop.

4. A model being destroyed can cause rejection or unnecessary eviction

What changed from main: Base stops counting a resident when its session pointer is cleared. The PR counts it until session and model destruction finish. During that interval, the unloading model also holds an exclusive lease, so eviction treats it as busy.

Reproduce: Warm NeuTTS and unload it. Submit a request for another model when the existing ggml_metal_free: deallocating log appears. The client observes real teardown; there are no injected server delays.

  • With max_loaded_models=1, Piper and Canary requests succeed on base in 3/3 rounds each. The PR rejects both targets in 3/3 rounds with max_loaded_models=1 and every loaded model is busy; retry later. Retrying Canary after unload completes succeeds.
  • With max_loaded_models=2, warm NeuTTS and Canary, unload only NeuTTS, then request Piper during teardown. The PR counts the retiring NeuTTS and evicts idle Canary. Base keeps Canary.

For the second case, over three rounds:

Measurement Base PR
Canary remains loaded after the switch 3/3 0/3
Next Canary request: HTTP latency 57.27 ms 370.92 ms
Same request: ASR execution 56.86 ms 59.19 ms
Canary weight imports across three rounds 3 6

The lost warm session explains the 6.48x response latency. Canary transcripts and Piper WAVs match across builds. max_loaded_models=2 is a resident-model limit; each model still has one execution slot.

Scope: The incoming request arrived about 4.3-5.5 ms before unload completed. This proves a narrow overlap case, not its frequency in ordinary traffic. Waiting for the unload response avoids it.

Code: resident accounting and eviction, unload sequence.

5. Bulk unload holds the global registry lock while waiting on one model

What changed from main: The PR's bulk snapshot holds models_mutex_ while acquiring each model's metadata lock. Reconfiguration holds that metadata lock through teardown and embedded-spec reads. Requests for unrelated models also need models_mutex_, so they wait too. Base does not hold this global lock across the wait.

Reproduce: Load NeuTTS and warm Piper. Reconfigure NeuTTS between offline and streaming modes. At its teardown log, submit bulk unload; after the bulk request's body-ready log plus 10 ms, submit Piper's voice-list query and a short speech request. Repeat without bulk unload as a control. Resident limits and the free-memory guard are disabled.

Three-round mean Base, bulk unload PR, bulk unload Base, no bulk PR, no bulk
Piper voice-list HTTP latency 0.59 ms 1503.51 ms 0.62 ms 0.57 ms
Piper speech HTTP latency 110.73 ms 1591.81 ms 76.44 ms 76.36 ms
Piper model execution 79.44 ms 88.26 ms 75.72 ms 75.68 ms

The voice query performs no inference. In every PR bulk round it stays blocked until NeuTTS releases its metadata lock, then completes within about 0.3 ms of the next load-phase marker. Removing bulk unload removes the delay. Voice-list responses and compared Piper WAVs match.

Bulk unload can change Piper's session history between builds, so the inference-free query and no-bulk controls are the stronger evidence. This lock delay occurs in the initial snapshot, before the drain loop in finding 3.

Code: bulk snapshot, reconfiguration lock.

Previous issue and other checks

The earlier overdue-request rejection issue is fixed: with unload waiting, Canary rejects an overdue request with HTTP 503 in 0.588 ms on the PR versus 0.641 ms on base.

Error recovery, invalid-path recovery, streaming disconnect/reuse, native batches, ordinary eviction, and live PCM timeout/recovery were also compared. Five focused framework/server unit tests passed. An active-request shutdown crash reproduced on both revisions and is excluded from the PR findings.

Test inputs

The reproduction sequences are described under each finding. Local test clients were used to control request timing; those clients are not included in this report.

Model files used:

  • Piper-TTS-GGUF/piper-en-us-lessac-medium-orig.gguf
  • Canary-180M-Flash-GGUF/canary-180m-flash-q8_0.gguf
  • NeuTTS-2E-GGUF/neutts-2e-orig.gguf
  • Nemotron-3-Diarization-GGUF/nemotron-3-diarization-q8_0.gguf

ASR/diarization inputs were the repository's assets/asr_validation/librispeech/librispeech_test_clean_6930-75918-0000.wav and librispeech_test_clean_6930-75918-0001.wav, approximately 3.5 and 14.2 seconds. Run base and PR separately to avoid GPU interference.

Issues with the test plan

The proposed plan already covers scheduling, queued reconfiguration, eviction, memory reuse, and one-slot compatibility. It needs clearer expected behavior and A/B pass criteria. The items below are recommended additions to the test plan.

  • Request ownership (F2): The plan should define what happens to a queued request when the model is reconfigured: does it use the original configuration, or get explicitly rejected? The test should verify that behavior, including which model actually handles the request.
  • Unload completion (F2/M4/M5): The plan should require checking loaded state and retained memory after unload and all older queued requests finish. This would catch finding 1, where unload succeeds but an older request reloads the model and leaves it resident.
  • Queue behavior (F1): The plan should require staggered request arrivals and an A/B comparison of older-request latency and timeout rates. This makes "without starvation" measurable and catches delays even when requests eventually succeed.
  • Cross-model impact (F5): The plan should require measuring whether operations on one model delay requests or memory release for another, or unnecessarily evict a warm model. The existing no-deadlock and safety checks would not catch those regressions.
  • Teardown transitions (F5): The plan should test requests for another model while unload is still destroying resources, with resident-model limits enabled. It should compare rejection and eviction behavior against base; testing only after unload completes misses finding 4.
  • Default-path acceptance: The current plan treats performance separately from admission_ready. It should also require single-slot A/B results for shared-framework changes, covering latency, failures, reloads, and retained memory. Any regression should be reviewed explicitly, including for models that have not opted into multiple slots.

The plan describes required tests, not completed validation. The PR should provide results for these shared-server checks before expanding model opt-in; valid output alone would miss most of the findings in this report.

Suggested direction

Main's original single-slot design is simple and easier to reason about: inference and management share one per-model execution lock. The PR replaces that path with more scheduling rules and lifecycle states, even for users who only need one slot. The results above show why preserving the slot count alone does not preserve behavior.

I suggest keeping the existing main execution path untouched and the default path and adding multi-slot execution as a separate, opt-in path. Users should only enter the new scheduler when they explicitly enable multiple slots. Any independently needed correctness fixes to the original path should be reviewed and tested separately, rather than bundled into the scheduling redesign.

That separation limits regressions for existing users, but the multi-slot path still needs thorough testing. The causes found here involve request ownership, admission order, unloading, resident accounting, and shared locks. Those mechanisms also apply with multiple slots; extra capacity does not remove the risks. This report measures the single-slot failures, so the corresponding multi-slot outcomes still need validation.

Before expanding model support, test these transitions with multiple slots occupied, queued requests, overlapping management operations, and unrelated models active. Check which model handles each request, queue latency and failures, final loaded state, memory release, and unnecessary reloads or evictions. The goal is to establish predictable server behavior under overlap, not just demonstrate that several requests can produce correct output at once.

Keep omitted slots and explicit slots=1 on the original BusyGuard and direct session path. Require explicit multi-slot opt-in, preserve legacy bulk-unload residency and response behavior, and reject changes between execution paths without unloading the existing model. Add guard regression coverage and update the existing cross-platform CI targets and lifecycle documentation.
@mirek190

Copy link
Copy Markdown
Contributor Author

OK

FULLY legacy execution remains the default and slot = 1

Now I will fix problems

@mirek190 mirek190 changed the title server: add common parallel-session slots and lifecycle guards server: add opt-in parallel-session framework with FIFO lifecycle guards Sep 30, 2026
@mirek190

Copy link
Copy Markdown
Contributor Author

Commit: 52936ec7.

Implemented the fixes for the five causes reported in this review. The earlier legacy-default compatibility change remains: omitted slots / one slot use the original guard and direct session; the new scheduler is explicitly selected with multiple slots.

Finding Fix Checked behavior
Management overtakes queued inference Requests and management share FIFO admission; a request holds its configuration/session lease before preparation Older speech finishes on Piper before same-ID replacement with Canary. Older queued work finishes before unload and cannot reload afterward
Later callers delay older waiters Assign ownership under the queue mutex and notify the individual waiter; prevent fast-path/eviction barging Oldest request precedes 16 staggered later callers, with/without management; overlapping managers preserve observed enqueue order; timeout/cancellation counters drain
Bulk unload retains an unrelated idle model behind a first load Reserve barriers for all selected parallel models, unload ready idle pools, then drain blocked models An idle model is destroyed while another model's unpublished first load remains blocked
A retiring model causes rejection or unnecessary eviction Clear logical residency / loaded status / capacity before slow destruction starts Incoming loads succeed under resident limit 1; limit 2 preserves the unrelated warm keeper. Physical free-memory checks remain active
Global registry lock spans metadata waits Snapshot stable pointers/immutable registered IDs and release the registry lock before metadata/admission/filesystem work Blocked metadata during bulk/status work does not stop an unrelated targeted voice lookup

Deferred streaming and native-batch callbacks retain the same lease used for validation, including disconnect/error cleanup. FIFO is defined by entry into per-model admission, not network arrival timestamps or completion order between concurrent slots. Unload completion still waits for resource destruction; clearing logical residency does not claim physical memory is already free.

Local validation Result
Exact publication source: Windows CPU server build / focused CTests 9/9 pass
CUDA integrated adapter build / focused CTests 5/5 pass
Vulkan integrated adapter build / focused CTests 5/5 pass
Supplemental MSVC ASan ownership/lifecycle suite 4/4 pass
Real Piper/Canary CUDA + Vulkan case groups 32/32 pass
Real Piper/Canary CPU legacy case groups 6/6 pass

Controlled actual-handler cases run at two/four slots, and guard utility cases include one/two/four. The GPU checks include default/explicit one-slot pre-fix parity, two/four-slot parity, unload/reload, queued unload and queued Piper-to-Canary replacement. All configured parallel slots appear in execution traces. Audio bytes, transcripts and meaningful metadata match; timing alone is excluded.

The real GPU tests combine this common framework with existing #706 adapters. They do not populate this PR's empty admission tables or certify all models/modes. The supplemental ASan suite includes one unpublished local ownership test; the new actual-handler regression and existing guard tests are in the published Linux ASan/TSan CI jobs.

Limits: Metal/Linux runtime and remote sanitizer checks are pending for this revision; the original Metal teardown/timing cases need a platform-specific retest. The full F1-F6/M1-M6 gate is not declared complete. Longer Piper fixtures independently hit its fixed graph arena in both pre-fix one-slot and candidate builds; this diagnostic is retained, and that separate model issue is not changed here.

The PR description, session contract and validation procedure now describe FIFO/configuration binding, logical retirement and nonblocking registry snapshots. Evidence and scope.

@mirek190

mirek190 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

CI follow-up is now pushed in 77e8c5e and 0e2c6ec.

  1. Compile integration: merged upstream 9a02e613 and converted its new /v1/tasks/batch handler to the common request lease and leased session. The initial failure was a compile error; no TSan checks had run.
  2. Real parser race: once compilation succeeded, Linux TSan detected concurrent writes to cJSON's global error position. The engine wrapper now protects only the cJSON parse call; tree conversion/deletion remain independent. Added an eight-thread regression mixing valid/invalid JSON and round trips, in addition to the deferred batch/replacement ownership tests at 1/2/4 slots.
  3. Toolchain warning: the GCC 13 run also warned about legacy timed-mutex unlocks. This matches GCC's documented missing-interceptor issue and r14-905 fix. The TSan job now uses GCC 14/libstdc++; production BusyGuard is unchanged. No tests, sanitizer checks or diagnostics are suppressed.
Latest revision: local Windows checks Result
CPU server build + focused framework CTests 9/9 pass
MSVC ASan guard/lifecycle tests 3/3 pass

Confirmed: all 11 CI checks pass on 0e2c6ec0. The cross-platform/sanitizer run passes Linux/macOS/Windows lifecycle checks and both Linux ASan/TSan suites (9/9 tests each). CPU and Vulkan build workflows also pass. Previous GPU/checkpoint evidence is tied to its recorded revision; no model arithmetic or GPU kernels changed in these fixes.

@mirek190

mirek190 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Maintainer workload reproduction after the fixes: CUDA and Vulkan

Completed 416 recorded test groups comparing clean upstream 9a02e613 against fixed PR revision 0e2c6ec0, on Windows / RTX 3090, with matching RelWithDebInfo builds, four inference threads, omitted slots (one slot), native model management and server logging enabled. Servers ran separately, alternating A/B and B/A order.

The checkpoints and ASR/diarization fixtures match the maintainer's report: Piper Lessac medium original, Canary 180M Flash Q8, NeuTTS 2E original and Nemotron 3 diarization Q8; the 3.5/14.2-second LibriSpeech inputs. TTS uses "Good morning. Your train leaves at nine.", seed 42 and default generation settings. Longer Piper requests repeat that sentence twice because the original longer text was not published.

Warm model execution

Median milliseconds, nine warm samples per model/revision/backend across three fresh servers. Upstream → fixed PR; this is model execution time, separate from HTTP latency.

Model CUDA: upstream → fixed (ms) Vulkan: upstream → fixed (ms)
Piper 28.09 → 27.51 18.16 → 18.39
Canary 32.51 → 32.72 38.93 → 38.59
NeuTTS 1,027.92 → 1,048.95 855.69 → 847.94
Nemotron diarization 14.06 → 13.81 15.78 → 15.47

Measured warm execution changes range from 2.09% faster to 2.05% slower. These are measurements, not a claim of a statistically established speedup.

Scheduling and lifecycle latency

Mean HTTP latency in milliseconds. Lifecycle cases use three fresh rounds; the 16-later-request Piper workload uses ten rounds with a 30-second oldest-request budget. Upstream → fixed PR.

Workload CUDA: upstream → fixed (ms) Vulkan: upstream → fixed (ms)
Queued Piper before replacement 73.40 → 86.41 62.15 → 67.94
Queued Piper before unload 83.19 → 80.92 62.75 → 70.51
Queued NeuTTS before unload 1,957.14 → 2,016.52 1,723.33 → 1,624.76
Oldest Piper, 16 later requests, 30 s budget 94.69 → 94.19 80.09 → 76.19
Bulk unload during first NeuTTS load 3.69 → 3.99 32.58 → 37.88
Next Canary after limit-2 retirement 48.98 → 44.43 40.71 → 41.46
Voice query during bulk/reconfiguration 1.16 → 1.04 1.09 → 1.29
Piper speech during bulk/reconfiguration 118.83 → 120.11 163.29 → 172.36
Overdue rejection while unload waits 0.92 → 1.00 3.14 → 0.88

Behavior and output checks

  • No unexpected reload after queued unload, wrong-model request failure, retirement-time rejection or unnecessary keeper eviction was observed in either revision/backend.
  • All 20 management-order rounds per revision/backend ended on the last-submitted model. This is observed behavior; the legacy guard does not promise FIFO ordering.
  • The fixed PR had 0/80 fairness timeouts across both backends. Upstream had 1/80, in CUDA diarization with the 60 ms budget. All other tested 60/350/650/30,000 ms budget cases completed without timeouts.
  • Every recorded lifecycle round reached its intended natural overlap. Retirement probes trigger on a ≥32 MiB NVML GPU-memory decrease during NeuTTS unload and record whether unload remains pending. Cross-model probes observe the bulk HTTP body-ready marker and submit queries 10 ms later, with a matching no-bulk control.
  • Piper, Canary and diarization outputs match exactly for aligned cold/warm histories, excluding only top-level execution timing. NeuTTS Vulkan also matches exactly for aligned histories. NeuTTS CUDA diagnostics differ by at most one PCM16 unit, with 110–113 dB SNR; this is below the measured variation between repeated upstream renders. Exact CUDA NeuTTS byte parity is not claimed.

The old multi-second scheduling/registry stalls did not reproduce in these Windows runs. Some HTTP means remain higher: CUDA queued Piper replacement is 73.40 → 86.41 ms, with fixed samples of 108.39, 73.92 and 76.92 ms. No-bulk voice-query controls also contain individual ~15.7 ms samples. These outliers are retained; their cause was not profiled, and three-round means should not be interpreted as precise speedup estimates.

Scope and reproducibility limits

Bulk first-load timing uses matched rounds 1/2/3; initial round zero for both revisions/backends is retained but excluded because checkpoint hashing overlapped the initial CUDA baseline. Correctness records remain available. Both compared source trees were clean and unmodified.

@mirek190

mirek190 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

OK .... I think should be ok now.
What do you think @0xShug0 ?

@0xShug0

0xShug0 commented Sep 30, 2026 •

Copy link
Copy Markdown
Owner

@mirek190 Thanks for the quick turnaround! I will test the multi slot path later this week (small tests before the weekend, then comprehensive testing over the weekend).

@mirek190

mirek190 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Sure

The new code (fixes) is fully compatible backward now so those changes are not affecting a legacy (base) implementation - after ddb8c4d commits.

@mirek190

mirek190 commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

any progress with merging ;) ?

@0xShug0

0xShug0 commented Oct 2, 2026

Copy link
Copy Markdown
Owner

@mirek190 Not safe. I already found a perf regression in the single slot case caused by json lock. No need to fix this now as there could be simialr issues in the touched shared code. I’m thinking about separating this more cleanly so we no longer need to worry about these risks.

@mirek190

mirek190 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

OK ...

I suggest to a server --parallel-jobs as an enable flag, keeping "slots" as the per-model count:

# Original server execution and lifecycle
audiocpp_server.exe --config server.json

# Enable experimental parallel framework
audiocpp_server.exe --config server.json --parallel-jobs

The intended behavior would be:

Startup Implementation
Without --parallel-jobs Original handlers, session ownership, locking, loading and unloading paths
With --parallel-jobs New framework; each model’s "slots" selects its capacity

This is a stronger separation than the current approach, where "slots": 1 selects legacy execution inside a server that still contains some shared framework changes. The default path should avoid the new pool, leases, scheduler and lifecycle logic.

Keeping activation separate from slot count also lets different models use different capacities. CLI would remain unchanged.

The tradeoff is maintaining two execution paths and testing both. We should keep the parallel logic isolated to limit duplicated code.

Do you agree?

Original implementation not touched and a new one triggered by a parameter. Then we can nicely implementing slowly everything not breaking anything from original implementation.
In the future we can easily replace original implementation with matured code.

If you agree I prepare change to it.

@mirek190

mirek190 commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

...so @0xShug0 do it as I in the last post or give up?

@0xShug0

0xShug0 commented Oct 2, 2026

Copy link
Copy Markdown
Owner

...so @0xShug0 do it as I in the last post or give up?

Let me make a proposal.

@0xShug0

0xShug0 commented Oct 3, 2026 •

Copy link
Copy Markdown
Owner

Stage 1: Legacy and Multi-Slot Separation Proposal v1.

Let me know if you have any comments, and let’s iterate on this. The opt-in additions that touch shared code are the risky part and need to be handled carefully. The duplication is worth it for separation, especially since audio.cpp was integrated into Unsloth just a few hours ago (where they use a single-model server). We don’t want any surprises on the legacy path.

Separate legacy and multi-slot paths from main HEAD

Starting point

Start from current upstream main HEAD. Every action below describes a change relative to that starting tree.

This document defines only the separation boundary: which existing files stay unchanged, which runtime logic is duplicated, and which shared functions require explicit opt-in.

“Leave unchanged” means no changes to the entire file related to main. “Modify” lists the additions allowed in that file. “Add” means create a new file. Existing behavior means the behavior of that main HEAD.

If main advances during development, incorporate its changes into both runtime copies where applicable. All file-change instructions remain relative to current main, not a fixed historical commit.

Required behavior

# Existing execution and lifecycle
audiocpp_server --config server.json

# Explicitly enable the new multi-slot implementation
audiocpp_server --config server.json --parallel-jobs
Startup Result
Flag absent, slots absent Existing server implementation
Flag absent, any explicit slots field Configuration error, including slots=1 or null
Flag present, slots absent New implementation, capacity 1 per model
Flag present, slots supplied New implementation, validated per-model capacity

The flag selects the implementation once, before creating the server. Slot count never selects the implementation. One-slot models in an enabled process use the new implementation.

The inference CLI retains its existing behavior.

The explicit slots rejection is the one intentional change to legacy input validation. "Unchanged" applies to existing requests/configurations without that new field.

1. Leave these files unchanged

Files Action
app/server/runtime.h Leave unchanged
app/server/busy_guard.h Leave unchanged
app/server/http.h, app/server/http.cpp Leave unchanged
app/server/frontend.h, app/server/frontend.cpp Leave unchanged
app/cli/* Leave unchanged
Existing model implementation files Leave unchanged in this infrastructure change
external/ggml/* Leave unchanged

2. Modify these existing files

Files Allowed changes relative to main HEAD
app/server/runtime.cpp Add only rejection of an explicit slots field in dynamic model registration; see section 4
app/server/main.cpp Add the startup flag, initialize opted-in framework policies, and construct the selected server class
app/server/config.h, app/server/config.cpp Add parallel-aware configuration parsing; reject slots in default mode and validate it in enabled mode
include/engine/framework/assets/tensor_source.h, src/framework/assets/tensor_source.cpp Add an explicit source-synchronization construction option; leave existing callers on main's behavior
include/engine/framework/assets/resource_bundle.h, src/framework/assets/resource_bundle.cpp Forward the source option and distinguish policies in the source cache
include/engine/framework/io/json.h, src/framework/io/json.cpp Add startup-only opt-in parser synchronization; leave default parsing behavior unchanged
CMakeLists.txt Compile the new parallel runtime alongside the existing runtime

The original runtime's execution, ownership, locks, loading, unloading, streaming, batch, eviction and shutdown bodies stay unchanged. The registration rejection is the only permitted addition in runtime.cpp.

3. Separate the runtime files

Duplicate from main, then develop the copies

New file Initial contents and subsequent changes
app/server/parallel_runtime.h Copy main's runtime.h; rename the class to ParallelServerState; add parallel-only state
app/server/parallel_runtime.cpp Copy main's runtime.cpp; rename class references and its header include; implement parallel behavior here

Copy the files before adding the legacy registration rejection. Update constructor/destructor names and qualified references in the copies. Keep duplicated translation-unit helpers internal, or give externally linked helpers distinct names.

Both classes implement the existing HTTP-handler and frontend-context interfaces. Construct only one server state in a process. Each class owns its registry, model state, locks and background workers.

Copy every entry point, including forward_to_core, live_ingest_limits, and the UI/management handlers. Frontend forwarding must return to the selected instance. Keep the transport and its existing interfaces unchanged.

Keep these responsibilities in the copied runtime, so implementing multi-slot behavior does not require editing the original runtime:

Logic Where it belongs
Registration and loading parallel_runtime.h/.cpp
Request admission and execution parallel_runtime.h/.cpp
Streaming, live input and batch parallel_runtime.h/.cpp
Reconfiguration, unloading and bulk management parallel_runtime.h/.cpp
Eviction, memory policy and idle unloading parallel_runtime.h/.cpp
Status and shutdown parallel_runtime.h/.cpp

Do not call the new lifecycle from the original runtime. Share existing stateless utilities where appropriate; keep ownership and lifecycle decisions in the selected runtime.

Keep multi-slot helpers on the parallel side

New file Allowed callers
app/server/model_slots.h Parallel runtime only
include/engine/framework/runtime/parallel_session.h Parallel runtime and explicitly opted-in model code
include/engine/framework/runtime/session_pool.h Parallel runtime only

Reference these helpers from the new runtime. Do not replace the original BusyGuard or change the existing session interface requirements.

These are locations for multi-slot logic, not instructions to implement the helpers in this separation change. Shared-weight caching, if introduced separately, must also have an explicit parallel caller.

Existing models remain untouched in this separation change. Subsequent model opt-ins must leave their existing construction/execution path intact. Even capacity 1 belongs to the parallel runtime when the flag is enabled; it must not delegate lifecycle operations back to ServerState.

4. Wire startup and registration

Select once at startup

In main.cpp, parse --parallel-jobs into a boolean defaulting to false, before model-configuration validation.

  • False: validate using legacy configuration rules and construct ServerState.
  • True: validate using parallel rules, enable the required framework policies, and construct ParallelServerState.

Pass the existing configuration, request base and UI anchor to the selected class. Reuse the existing listener-startup block and its arguments. The selected state remains alive until serving stops. No model registration or reconfiguration switches the runtime.

Use a local generic lambda accepting auto & state for the existing listener-startup block. Inside the enabled branch construct a stack-owned ParallelServerState and call the lambda; in the other branch construct a stack-owned ServerState and call it. This preserves concrete construction/destruction and access to make_frontend_listener without changing either existing interface or adding a common runtime base class. Listener destruction precedes state destruction.

Parse slots only when enabled

Preserve load_server_config(path) as the default-mode entry point. Add load_server_config(path, bool parallel_jobs) for explicit startup selection; the original signature delegates with false. Keep existing field parsing and validation unchanged except for the new slots rule. Dynamic registration uses the selected runtime's own model_config_from_json helper.

In default mode, reject the presence of a slots field before applying defaults. Read the field only in the parallel-aware parser.

Add a default-1 capacity field to ServerModelConfig, read only by the parallel runtime. Startup parsing is in config.cpp; dynamic model_config_from_json is a translation-unit helper in runtime.cpp, so extend its copied version in parallel_runtime.cpp. Keep the original helper unchanged. Capacity validation and reconfiguration decisions belong to the enabled path.

Keep the selected parser mode consistent for startup configuration and dynamic registration. Legacy UI payloads and saved configurations must not gain synthetic slots fields.

Reject slots in legacy dynamic registration

In ServerState::handle_model_load, immediately after the existing JSON parse and before configuration conversion or state changes, add:

if (body.find("slots") != nullptr) {
    return error_response(400,
        "slots requires --parallel-jobs at server startup",
        "invalid_request_error");
}

This is the only addition to the original runtime.cpp. It also covers frontend-forwarded requests reaching that handler. Do not parse the body again. With slots absent, continue through the unchanged main implementation.

The parallel registration handler uses the parallel-aware parser instead of this rejection.

5. Opt into tensor-source synchronization

No separate tensor-source implementation file is needed.

Add a construction option:

struct TensorSourceOptions {
    bool synchronized_access = false;
};

Add options-taking overloads for:

  • open_tensor_source(path, options)
  • open_tensor_source(path, tensor_prefix, options)
  • ResourceBundle::open_tensor_source(id, options)

Preserve existing overloads and their behavior. Store the selected policy immutably in each GGUF/Safetensors source before publication.

Use this policy to gate new synchronization in storage-owning methods such as release_storage, require_tensor_data, set_backend_tensor and require_i64_scalar. With the policy disabled, preserve main's locking, conversion, upload and storage-release behavior.

Include the policy in the bundle's source-cache identity. A request for synchronized storage must not receive an unsynchronized cached source. Prefix/folded views retain the underlying source and its lock; they do not create independent synchronization around shared storage.

Apply the policy to both caches: the resource-ID cache and canonical-path cache. Add an options overload for open_indexed_tensor_source and pass the option to every shard. Prefix, folded and composite wrappers must retain that same source policy.

Any new synchronization of ResourceBundle's mutable cache maps must also be behind an explicit bundle-level opt-in. Do not add unconditional cache locks to existing callers.

Each model opt-in must explicitly pass the option before sharing assets among sessions. Adding factory overloads alone does not enable synchronization. Existing model loaders and the inference CLI keep their existing calls.

6. Opt into JSON synchronization

Preserve the parser behavior of the starting main HEAD. Introduce synchronization only for the enabled server process.

Add engine::io::json::enable_serialized_json_parsing(). Call it in parallel startup before constructing the runtime or starting any concurrent parser users. The policy defaults off, becomes immutable before concurrent use, and has no runtime toggle.

When enabled, json::parse takes the parser mutex around cJSON_ParseWithLengthOpts. Keep conversion, validation, errors and deletion unchanged. When disabled, use main's existing parsing path.

Audit direct cJSON parsing callers too. All concurrent callers sharing the same cJSON globals must follow the enabled policy. A mutex around only selected requests is insufficient.

The enabled parser policy applies to the whole process, including model loaders. Activate it only in parallel startup. Default startup and the inference CLI leave it disabled.

The default server and inference CLI do not enable this policy. This avoids adding global parser-lock contention to them. If main already contains a parser correctness fix, preserve that fix; do not replace it with an older implementation.

7. Final file boundary

Relative to current main, files listed as unchanged have no diff. Modified files contain only the stated startup selection, slots rejection and opt-in additions. Parallel execution and lifecycle changes belong in the new files. Future fixes to shared main behavior must be carried into both copies without routing the legacy runtime through parallel helpers.

@mirek190 mirek190 changed the title server: add opt-in parallel-session framework with FIFO lifecycle guards server: separate legacy and opt-in parallel jobs runtimes Oct 3, 2026
@mirek190

mirek190 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Done

@0xShug0

0xShug0 commented Oct 3, 2026

Copy link
Copy Markdown
Owner

@mirek190 Thanks for the update. The separation looks good. I'll test multi-slot support. Please also do a self-audit, focusing on state transitions, ownership, and lock scope, e.g., what happens when an operation fails partway through, where requests can wait, and whether work on one model can block another. Keep any fixes scoped to the new path if you spot any issues.

@mirek190

mirek190 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor Author

fixes in 366e7520, focusing on failure transitions, ownership and lock scope.

Production fixes apply only to --parallel-jobs. Default startup retains the original runtime and HTTP listener. No model implementation, inference CLI or CUDA/Vulkan kernel was changed by this commit.

Area What changed
Reconfiguration failure Replacement metadata is validated privately before unloading working sessions. Validation failure preserves the live model. A backend/pool failure after replacement leaves a complete, unloaded configuration that can retry. Config/weight selectors now participate in reload detection.
Concurrent registration A new entry is published under an already acquired exclusive lease before its first load. Same-ID registrations share one stable entry, and residency accounting sees it. Registry vector storage is reserved before index publication to avoid a dangling index if allocation fails.
Live-ingest policy Registry lookup is synchronized; the registry mutex is released before taking the model metadata lock and copying its policy.
Overlapping bulk unloads A short mutex makes publication of each bulk selection's barriers indivisible, preventing circular waits between reversed selections. It is released before waiting or teardown. Duplicate selected models are drained once. Normal inference does not take this mutex.
Partial construction A null primary session is rejected before dereferencing it. Failed pool construction destroys private sessions before model weights and releases the request lease.
Native UI folder replacement Construct the new installer before committing either the public models-root path or installer pointer, keeping them consistent on construction failure.
HTTP worker lifetime The flagged default listener now owns, reaps and joins request workers. Shutdown/listener failure cancels socket I/O and drains active handlers and deferred callbacks before runtime destruction. Nonblocking sockets and cancellation polling cover stalled headers, live ingest and clients that stop reading responses. The original HTTP translation unit stays unchanged.

The new listener starts from the legacy framing implementation in a separate translation unit to preserve the separation boundary. Both listeners run the same framing checks. One stale fixture assertion was updated to expect the complete non-live chunked payload that upstream already buffers; assertion failures now report the error and drain the test listener.

Local validation on the tree committed as 366e7520 (Windows/MSVC, RTX 3090):

Check Result
CPU framework/framing/ownership CTests 14/14 pass
Windows AddressSanitizer CTests 11/11 pass
Repeated lifecycle and HTTP ownership regressions 20 consecutive passes each; 40 executions
CUDA CLI/server build with native model management Pass
Vulkan CLI/server build with native model management Pass
Matched upstream/legacy/flagged-omitted/flagged-one checkpoint requests 96/96 exact output/metadata matches after removing top-level execution timing
Native UI models-root change, invalid-folder rejection, state retention and reset Pass on both builds
Protected-source boundary against recorded upstream 2892ed3e; whitespace check Pass

Controlled real-handler tests cover 1, 2 and 4 slots: load/null-session/partial-clone failures, preparation/inference failure, replacement failure/retry, same-ID registration, dropped deferred callbacks, reversed/duplicate bulk selections, atomic barrier publication, metadata contention and unrelated warm-model progress during guarded cold loading. Loopback tests cover shutdown during active handlers/deferred callbacks, stalled headers/live ingest and a non-reading response client.

The GPU checkpoint pass uses Piper TTS, Canary ASR and Nemotron diarization, with cold, two warm requests and unload/reload on CUDA and Vulkan. It validates representative capacity-one integration; it is not catalogue multi-slot admission or a performance benchmark. Installer-constructor allocation failure was source-audited, not fault-injected.

Intentional waits remain: memory/residency guards serialize cold loads, and the flagged JSON parser mutex briefly serializes parsing. Unrelated warm models remain runnable. Busy timeout is an admission policy, not an end-to-end cancellation deadline; an in-flight or hung GPU call cannot be forcibly preempted and can delay shutdown. Custom frontend listeners must drain their own workers before returning.

The workflow now includes the two new transport regressions in cross-platform lifecycle and Linux ASan/TSan jobs. Remote CI is running/queued on this commit, separately from the local results above. Admission tables remain empty; model adapters/admission stay in #706.

Detailed self-audit: transitions, ownership and wait locations.

@mirek190

mirek190 commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Added some fixes

@0xShug0

0xShug0 commented Oct 3, 2026 •

Copy link
Copy Markdown
Owner

Thanks @mirek190. Could you add one Parallel Server Behavior Contract document? It should define the expected behavior for a given case. The current expectations are spread across several docs and comments.

Please derive the cases systematically:

  1. Define states: unloaded, loading, ready, reconfiguring, unloading, and shutting down. Distinguish queued requests from admitted requests waiting for initialization, executing requests, and active streams.
  2. Cross operations with states: for inference, registration/reconfiguration, unload, bulk unload, eviction, status queries, and shutdown, define what happens in every applicable state.
  3. Cover operation interactions: request/request, request/management, and management/management. Include both arrival orders, spare versus full capacity, same versus different models, and overlapping bulk selections.
  4. Cover failure boundaries: before changing live state, after replacing configuration, during partial loading, during execution, and during teardown. Include timeout and client disconnect.

We should have clearly defined behavior matrices in the doc. One example:

Starting situation Request to A Request to B Reconfigure A Unload A Unload A and B
A unloaded; B ready          
A loading; B ready          
A running with free slots; B ready          
A full with queued requests; B ready          
A reconfiguring; B running          
A unloading slowly; B ready          
A and B both loading or running          
Another bulk operation already targets A/B          

For each cell, briefly state what runs or waits, the response, and the resulting model state. Add a linked test.

The other matrices should cover failure recovery, timeout, disconnect, shutdown etc.

This should be the single authoritative document.

Over all I think this is becoming a rabbit hole, and we're partly reinventing the wheel with scheduling and lifecycle management. I'd suggest focusing on testing one or two aspects in this PR, perhaps just the happy paths.

And mark this feature as experimental. When the user launches the server with this feature enabled, show a clear warning stating which behaviors have been tested and which haven't. I expect some users will try this feature, so it’s important to set the right expectations.

The behavior contract doc should document validation by area: concurrent inference, cold loading, reconfiguration, unloading/eviction, disconnects, and shutdown. Label each tested, partially tested, or untested, with the tested scope. Known issues should be listed explicitly. We can expand the supported workflows incrementally.

BTW one issue found in the current PR: unsupported capacity destroys working registration. For example, changing to unsupported slots=5 unloads the model, retains five slots, and subsequent inference fails.

@mirek190 mirek190 changed the title server: separate legacy and opt-in parallel jobs runtimes server: separate legacy and experimental parallel jobs runtimes Oct 3, 2026
@mirek190

mirek190 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed the latest feedback in c28d3715.

One authoritative behavior document: Parallel Server Behavior Contract.

It defines the six lifecycle states and distinguishes queued requests, admitted requests waiting for initialization, executing requests and active streams/deferred batches. The matrices cover operations against states, the requested two-model situations, both arrival orders, spare/full capacity, same/different models and overlapping bulk selections. Separate matrices cover failure recovery, timeout, disconnect and shutdown. Cells link to regressions where available and explicitly distinguish direct coverage, partial coverage and untested cases; a nearby test is not presented as proof of an untested combination.

Documentation consolidation:

Document Responsibility
Behavior contract Expected server behavior, matrices, tested scope and known limits; the authoritative starting point
Adapter guide (parallel_sessions.md) Adapter interfaces and implementation ownership; duplicated server lifecycle sections replaced with contract links
Validation procedure Future model admission and quality checks, referencing the contract/shared evidence
Historical reports Revision-scoped results, explicitly labelled historical and linked to the current contract

The adapter guide shrank from 1,650 to 979 words (41% shorter) and from 213 to 137 lines. The total documentation is larger because the requested state/operation matrices are new; the consolidation removes competing descriptions of server behavior and keeps each document's purpose distinct. The model quality requirements are unchanged, and shared tests are collected once per relevant scope rather than repeated for every model.

Experimental scope: startup with --parallel-jobs now prints a warning describing tested and untested behavior and points to the contract. The PR focus is startup isolation and normal inference/cold initialization. Reconfiguration, unloading/eviction, disconnect and shutdown are explicitly labelled partially tested with their actual scope. Catalogue multi-slot admission, real concurrent GPU streams/batches, Metal checkpoint execution and hard backend cancellation are not claimed. Admission tables remain empty.

The unsupported-capacity bug is fixed: changing a working registration to unsupported slots=5 returns HTTP 400 while retaining the old pool, configuration, slot count and residency. Subsequent inference and a valid resize work. Capacity-only changes use the live advertised capability; changed session inputs use a private primary probe before teardown. Changed-checkpoint multi-slot probes may need temporary extra memory and remain unvalidated on GPUs. Production changes stay on the opt-in path; the original runtime/HTTP listener, model code, CLI and kernels are unchanged.

Follow-up local check Result
New regression against previous runtime Fails with working registration changed/destroyed
Unsupported replacement at fixture capacities 1/2/4 Nine rejection cases pass, retain pool/config/count and recover through valid resize
CPU framework/framing/ownership CTests 14/14 pass
Windows AddressSanitizer CTests 11/11 pass
CUDA and Vulkan CLI/server builds Pass
Real checkpoint rejection/reuse 12/12 cases pass; 36 inference responses
Startup warning, flagged versus legacy on both backends Four cases pass
Protected-source boundary, whitespace and contract links/table structure Pass

The checkpoint follow-up uses Piper TTS, Canary ASR and Nemotron diarization on CUDA/Vulkan, each on legacy and flagged capacity-one servers. After rejection, status is unchanged and the next warm output/meaningful metadata matches exactly after excluding only execution timing. This does not establish higher-slot model admission or graceful process shutdown.

All 11 remote checks passed on the previous audit revision 366e7520. CI on this follow-up revision is running and is tracked separately. Remaining gaps include prompt queued-request cancellation, shutdown during queued/cold-loading/management work, hung backend cancellation and custom frontend listener ownership; these are listed explicitly in the contract.

Better now? ;)

@0xShug0
0xShug0 merged commit e3e1bc7 into 0xShug0:main Oct 4, 2026
11 checks passed
@0xShug0

0xShug0 commented Oct 4, 2026

Copy link
Copy Markdown
Owner

@mirek190 Thanks! PR merged 🎉 . Stage 2 can proceed in two directions, depending on what you want to work on:

  1. Continue improving multi-slot support to complete the behavior and test matrices.
  2. Opt in models individually.

For model opt-ins, the general order should be:

  1. Models that are easy to opt in and have a low risk of behavioral changes.
  2. Models that require additional changes to support multi-slot operation.

You can submit the models in (1) together. For (2), submitting one model per PR is preferred. Any existing correctness fixes should also be separated from the changes required to enable multi-slot support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants