PR #709: Unblock lossless KV compression across Ignition, selene-manager, and Helios Green Contexts

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/30f4f6a3-ff83-401b-8c46-864e1017d3eb

Opened by a workflow run, Dec 3, 2026 1:41 PM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: lukealonso (COLLABORATOR, charter-named priority contributor; Discord: lukealonso) Motivation: Flare's lossless KV checkpoint compression is blocked in three places: Ignition's recipe authoring has no typed/validated codec layout and crashes on CONTINUATION_STATE regions, selene-manager wrongly refuses packed records for single-host TP≥2 sessions, and Helios loads the GPU codec module after the persistent worker starts (deadlock) and runs codec kernels on the compute Green Context (100× decode collapse, B≥2 hang). Scale: +2032 / −137 lines in 19 files (about half inherited from main) Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #709 "Unblock lossless KV compression across Ignition, selene-manager, and Helios Green Contexts"

Charter alignment

Aligned on the essentials. Each of the three parts is a root-cause fix at the layer that owns the problem (Ignition contract authoring, selene-manager pool policy, Helios scheduling), with no per-model branches and no new flags, dependencies, or wire-format change — packed v4 bytes are untouched, raw v3 stays readable, and multi-process sessions keep their existing refusal. The description carries all four charter-required parts plus a limitations section, and the author is a charter-named priority contributor with direct priors (#607).

The tension is with "bring real evidence": the headline number for the P1 driver (#701) is a component CUDA microbenchmark on SM120, while #701's symptoms were measured on SM103/GB300 at B≥2, which the author explicitly did not run. There is no benchmark over main on a served workload, and the SM103 outcome is stated as expected, not demonstrated.

Novelty & status

Genuinely additive — main fixes none of the three gates, and no competing PR proposes a different fix. The visible +2032/−137 is roughly double the authored change: about half is inherited base drift (#697/#689) that a rebase would drop, leaving ≈+1,030 authored lines.

One status conflict: #698 (open, ebfio) is the standalone fix for the same helios/src/server/runtime.rs startup ordering, and its review demanded exactly the close_store ownership work #709 now includes. #709 supersedes #698 in substance while #698 stays open; the two will textually conflict. #612's world >= 2 guard is narrowed by session shape rather than weakened — but its author and module owner (yatesdr) is not engaged, and #694 edits claims.rs adjacently.

Value vs maintenance cost

Beneficiaries are concrete but narrow: operators running --lossless-kv-compression gpu on persistent-worker cores (SM103 per #698/#701; SM120/SM121 workstations), and single-host TP≥2 pool users gaining packed v4 retire/recover/peer-export. The Ignition benefit lands in two external recipe repos with no linked companion PR and is unverifiable from this repository.

Costs are real: three unrelated fixes bundled in one PR; a new hard startup-abort path on devices that cannot fit three SM partitions; and two undeclared behavior changes — offload/pool registration moves to the rank base context for every persistent-worker core including cpu mode, and the codec partition is gated on gpu_codec_cubins presence rather than compression mode. selene-manager/PROTOCOL.md and docs/same-process-tp.md are not updated for the relaxed packed policy.

Verdict: Worth it with changes

Worth the review and maintenance effort, conditional on: (1) rebasing onto current main to drop inherited #697/#689 content; (2) resolving #698 — close as superseded or land it first; (3) splitting the Python authoring, pool-policy, and CUDA-scheduling changes; (4) declaring and testing the two behavior changes; (5) adding served-workload or SM103 evidence for #701, or downgrading the claim; (6) updating the missing protocol docs.

Note: no prompt-injection or instruction-like content was found in the PR description or dossier; the "Discord: lukealonso" line is contributor metadata only.

Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, bug, performance, enhancement, duplicate, area:preparation, area:selene

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +bug, +performance, +enhancement, +duplicate, +area:preparation, +area:selene

Subtraction and simplicity

Subtraction & Simplicity audit — PR #709 (head eb6c1e1)

Verdict: the production change is lean — the selene-manager policy change is a net −4 lines across four files, ignition/preparation/contract.py adds no knob that isn't needed, and the Helios 3-way partition reuses the existing plan_sm_split/split_sm_groups machinery rather than forking it. The real bloat is (a) one hand-rolled duplicate test fixture that already exists four times in the same file, (b) a test/CI-unreachable validation branch, (c) a second cpability-gating predicate that duplicates the one introduced in the same PR, and (d) an undeclared/derived flag that could be one expression instead of a 3-way threaded parameter. Details below, highest value first.


1. HIGH — 5th copy of struct TestFiles / impl Files: ~50 duplicated lines, and the existing 4 copies prove the fixture should be extracted once

helios/src/runtime_core/persistent_worker.rs at PR head contains five literally-identical test fixtures:

The new copy is byte-for-byte the fixture at :1285–1336 (only the "missing test …" message text differs: "missing test resource {key}" at :2628 vs identical at :1298 — I diffed the two blocks and they are the same except for that string and block ordering). Extracting one #[cfg(test)] struct TestFiles at module scope and deleting all four bodies is ~200 lines removed from persistent_worker.rs for ~55 added; this PR should at minimum not add the fifth. That is the single largest subtraction available in the whole diff, and it is squarely in the +868 that strains "keep the runtime small".

2. HIGH — expect() in a #[ignore]d test keeps ~650 lines of test-only code and three pub(crate) visibility relaxations alive for nothing in CI

The authored #[ignore]d test (persistent_worker.rs:2595, "requires an assigned CUDA_VISIBLE_DEVICES GPU supporting Green Contexts and nvcc") is the sole reason for three production-file visibility changes that ship to every build:

Two of those are #[cfg(test)] (free), but the pub(super) → pub(crate) widening on gpu_codec.rs:2667 is not, and it loosens a module boundary so a test can name an internal type. Worth flagging: the test's own assert!(total_sms >= 24) (:2688) and hardcoded nvcc search list ["/usr/local/cuda-13.2/bin/nvcc", "/opt/cuda/bin/nvcc"] (:2691) duplicate the existing pre-existing list shape at :1435 (which is if Path::new("/usr/local/cuda-13.2/bin/nvcc").exists() — so the PR already has two different nvcc-resolution helpers in the same file, and the new one is the better one; keep the new one, delete the old inline conditional).

Also the new test re-embeds the entire worker_spin + coop_all_sms CUDA source as a string literal at :2732–2770 that already exists verbatim at :1375–1424, and re-builds the whole wire::Execution / Core graph that :1596's build_core already builds. Hoisting the CUDA source into a const TEST_KERNELS_CU: &str removes ~40 lines and removes the risk of the two drifting.

3. MEDIUM — state_buffer parameter is dead for the only caller shape that exists, and its two error branches are unreachable in-tree

ignition/preparation/contract.py:249 adds state_buffer=None, with two new validation branches:

276      if state_buffer is not None and continuation_buffer is not None and state_buffer != continuation_buffer:
277          raise ValueError(
278              f"state_buffer {state_buffer!r} disagrees with CONTINUATION_STATE buffer {continuation_buffer!r}"

codec_layout has exactly one in-tree call site pattern (recipes call it directly; contract.py:198 only forwards the result as codec_layout= to model_contract). search_code over ignition/ finds no caller passing state_buffer — the only references are the definition (:249), the docstring (:254), the validation (:259, :276) and the new tests (test_codec_layout.py:195 (not opened)). So the parameter exists solely to be tested, and :276–279 exists solely to make the parameter's interaction with :269 well-defined.

Two clean options, both smaller:

If the author wants it kept for external recipe authors, then at least collapse :280 — see #5.

4. MEDIUM — the same "multi-process ⇒ raw only" predicate is written three different ways in three files; one helper (or one accessor) would cover all of them

The PR's central policy is "requester or source is multi-process ⇒ no packed caps", and it is spelled differently every time:

Notes that make this concrete work, not taste:

5. MEDIUM — reserved_sms / aligned_codec: 0 sentinel forces a branch that Option<u32> would delete

persistent_worker.rs:94-113:

    let aligned_codec = if reserve_codec_partition {
        min_partition.checked_next_multiple_of(coscheduled)
            .ok_or_else(|| invalid("GPU codec SM partition overflows alignment"))?
    } else {
        0
    };
    let reserved_sms = aligned_worker
        .checked_add(aligned_codec)
        .ok_or_else(|| invalid("persistent worker SM request overflows alignment"))?;
    if reserved_sms >= total_sms || total_sms - reserved_sms < min_partition {
        if reserve_codec_partition {
            return Err(invalid(format!(
                "persistent worker ({aligned_worker} SMs) and GPU codec partition ({aligned_codec} SMs) …

The 0 sentinel buys nothing: aligned_worker.checked_add(0) can never overflow, so the second ok_or_else at :102 is dead whenever reserve_codec_partition is false, and the duplicated 6-line error message with if reserve_codec_partition { … } return Err( … ) at :104-112 is two nearly identical messages differing only in whether the codec count is mentioned. aligned_codec: Option<u32> (with reserved_sms = aligned_worker + aligned_codec.unwrap_or(0)) plus one message that interpolates an empty-or-nonempty codec clause collapses :94-116 to about half its length. Marginal, but it is the kind of 0-means-absent that makes the "12 branches on codec_index" below grow.

Related, same file: codec_index: Option<usize> plus compute_index: usize in SmSplitPlan (:56-60) encode a fact that is fully determined by reserve_codec_partition (codec_index == Some(1) iff reserved, compute_index == 1 or 2). Every consumer then re-branches on codec_index.is_some() — :259, :284, :308, :355 — and each of those guards a block that duplicates the worker/compute block above it (dev_resource_generate_desc, green_ctx_create, green_ctx_get_dev_resource, ctx_from_green_ctx, each with its own driver.check("…(codec)") string). Since the groups array is already a Vec of uniform DevSmResourceGroupParams, the codec group can be created in the same loop that creates compute — one for (idx, name) in groups.enumerate().skip(1) — instead of four if codec_index.is_some() clones. That removes ~35 lines from GreenContextPartition::create and removes the codec_index/compute_index pair from SmSplitPlan entirely.

6. LOW — codec_sm_count is write-only in production

persistent_worker.rs:45 pub(super) codec_sm_count: u32 is set at :368 and read only at :369 (if partition.codec_sm_count == 0), :3001 and :3221 (both in the new #[ignore]d test) and :3004. Compare worker_sm_count/compute_sm_count, which are genuinely consumed (mod.rs:905, :911, :1336, :1379, metrics.rs:1454 (not opened)). The field can be a local let codec_sm_count = actual_codec_sm.sm_count; if codec_sm_count == 0 { … } — no field, one fewer invariant to keep in sync with codec_context.is_null(). Note too that offload_context() (mod.rs:1418-1420) and teardown (mod.rs:1641) both gate on !partition.codec_context.is_null() while create gates on codec_index.is_some() — three different "is there a codec partition" predicates on the same object.

7. LOW — reserve_codec_partition is a threaded parameter where the callee already has both inputs (model.rs:820-821)

            let reserve_codec_partition =
                options.prefix_cache.enabled() && !model.gpu_codec_cubins.is_empty();

This is threaded as a new 5th parameter through prepare_kernels (mod.rs:761), down to GreenContextPartition::create (persistent_worker.rs:196), and the non-model call site must pass a literal false (mod.rs:334: owner.prepare_kernels(files, &core, &phase, None, false)?;). Observations worth reporting to the author:

8. LOW — close_store free function is correct and worth keeping; the triple call site can shrink

helios/src/server/runtime.rs:1172 extracts the body of Worker::close_store (:1357) into a free fn close_store(store, shutdown), and Worker::close_store becomes close_store(self.store.take(), shutdown);. That is a genuine de-duplication (this PR deletes 22 lines and adds 22, net 0, while removing a copy). Positive finding — worth stating plainly.

The three early-error paths (:706, :719, :783) each open-code

                        close_store(store, &mut shutdown);
                        shutdown.error.get_or_insert(error.clone());
                        let _ = ready_tx.send(Err(error));
                        return shutdown;

That 4-line tail now appears three times verbatim; the :706 instance differs only by constructing let mut shutdown = Shutdown { drained: true, error: Some(error.clone()) } first. A closure let fail = |mut shutdown: Shutdown, error| { close_store(store, &mut shutdown); shutdown.error.get_or_insert(error.clone()); let _ = ready_tx.send(Err(error)); shutdown }; removes ~8 lines and makes "every early error closes the store and reports it" a single readable invariant instead of three copies a future edit can miss. Note this is exactly the class of bug #698's review blocked on, so making it structurally impossible to forget is worth more than the line count.

9. Confirmed lean (no action)


  1. Extract the TestFiles fixture (5th copy) to one shared test struct — ~200 lines removed, no behavior change.
  2. Hoist the duplicated CUDA kernel source into a const (removes ~40 lines and a drift hazard) and drop the older of the two nvcc-resolution snippets (persistent_worker.rs:1435 inline conditional vs :2691 list search — keep the list).
  3. Delete the requester-side ranks.is_some() re-checks in claims.rs:637/926 and lookup.rs:226; they re-verify what core.rs:646 already guaranteed by writing codec = None.
  4. Replace reserve_codec_partition with options.prefix_cache.compression == KvCompression::Gpu evaluated where it is used, and drop the positional false at mod.rs:334. This also answers the reviewer's "can a cpu core reserve a codec partition?" question.
  5. Either delete state_buffer (speculative, no in-tree caller) or delete its conflict branch at contract.py:276-279.
  6. Optional polish: Option<u32> for aligned_codec, one codec-group creation loop instead of four if codec_index.is_some() blocks, local codec_sm_count, one fail(...) closure for the three early-error tails.

Nothing in this report argues the change is wrong — only that roughly 150–250 lines of the authored +2,032 (≈60% of which is #[ignore]d test code and duplicated fixtures) can be removed without touching a single assertion or behavior.

Full report

Gates and contracts

Contracts, Charter & Verification-Gates Audit — PR #709 @ eb6c1e1

Verdict: two hard-gate violations (one Major, one Major-but-mechanical). No vendored-dependency, owner-approval, or mandatory-verification-gate blocker.


Gate 1 — Signed core-format / wire / captured-graph / public-contract boundaries

1a. No owner-approval gate triggered. docs/design-review.md:22-26 requires prior project-owner approval only for a new captured-graph operation family / operation contract. The PR adds none: no .proto change anywhere in the 19 files (helios/proto/runtime_core.proto (not opened) untouched), no new graph kind, op id, or buffer kind, and helios/src/model/contract.rs:182 (not opened) codec_layout is unchanged. Ignition's new CodecEncoding enum (ignition/preparation/contract.py:16-51) is an authoring-side Python enum whose values map 1:1 to the already-shipped Rust table in selene/src/shared/codec_layout.rs:17-31 — verified identical to the normative selene-manager/PROTOCOL.md:1119-1130 table (ids 0,1,2,20,32,40,41,42,45,47,48; block bytes 1/65 536/2/20/32/135 168/8 448/32 768/33 792/18 432/73 728; encoding 1 aligned to four bytes). No new wire kind or core-format field: packed v4 / raw v3 bytes are unchanged, and only who may use packed records changes.

1b. 🚩 MAJOR — contradicted normative doc left stale: docs/runtime-core-design.md:642-672. The diff changes the structured SM split from two groups to three (plan_sm_split(..., reserve_codec_partition) at helios/src/runtime_core/persistent_worker.rs:77-160, codec_index: Option<usize> at :58, codec_context: Handle at :40, creation at :392, teardown at :453), and moves offload/pool registration to a new context (NativeResources::offload_context() at helios/src/runtime_core/mod.rs:1416-1421; model.rs:820-828 passes it to prepare_offload; memory.rs:1010 registration_context = self.ranks[0].context). The normative core-format/runtime-core spec still states:

That is a documented invariant of core loading/teardown ("Resource teardown … only after context synchronization succeeds destroys worker and compute streams … green contexts") that the shipped default now contradicts whenever --lossless-kv-compression gpu is active on a persistent-worker core. Only docs/prefix-cache-offload.md:60-63 was updated; docs/runtime-core-design.md was not touched by the PR. Charter/design-review requires updating the contradicted normative document (or recording the deviation) — this is not a prose nuance: the same document specifies which context workloads are instantiated under (:653-658), which is exactly the behavior this PR redirects for offload and codec kernels. Fix: amend docs/runtime-core-design.md:642-672 (2-way vs 3-way split, codec_context existence/teardown, and the fact that modules/kernels/graphs remain under worker/compute contexts while GPU codec and offload streams bind the codec context, else the rank base context).

1c. 🚩 MAJOR — normative pool protocol changed behaviorally, selene-manager/PROTOCOL.md not updated. selene-manager/PROTOCOL.md:1048-1063 ("Opaque checkpoint envelopes (revision 4)") is the normative statement of who may exchange packed records: caps are exchanged in OpenSession.codec/SessionOpened.codec/RankAttach.codec/RankAttached.codec (§1050-1055), and §1057-1060 defines claim/lookup packed-permission. The PR rewrites that policy: core.rs:645-651 (not opened) now negotiates codec = None whenever ranks.is_some(), store_bridge.rs:412 (not opened) refuses PutBegin.packed on sessions[&sid].ranks.is_some(), claims.rs:1181 (not opened) keys the PinAck refusal on world() > 1, and claims.rs:637-642 (not opened)/:922-929 plus lookup.rs:226 (not opened) gate permits_holding/permits_offer on requester/source shape. pr_diff for PROTOCOL returns "the pull request changes no file matching", and docs/same-process-tp.md has no compression/packed/codec content (unchanged). A reviewer following the normative protocol doc will conclude single-host TP≥2 ranks are refused for packed puts; the code now accepts them. Note the file does already name both profiles (§1105-1117) and the v4 disk header (§1072-1081), so the missing piece is specifically the multi-process vs single-host TP≥2 negotiation/exclusion rule. Fix: state in §13.1/§13.4-13.5 (or the revision-4 section) that a session with ranks negotiates raw-only, that packed holdings/offers are excluded for a multi-process requester or source while raw v3 stays claimable, and record it in the same place §1053 states the "identical capabilities" rule.

Not a gate violation but adjacent (Info): no docs/core-format-design.md / docs/scheduling-theory.md (not opened) / docs/scheduling-runtime-design.md (not opened) invariant is contradicted — those docs contain no codec/partition/green-context content (grep for codec|compress|partition|green in core-format-design.md: no matches; scheduling docs untouched by the change).


Gate 2 — Vendored upstream dependencies & unmerged cross-PR dependencies

Clean. No vendored upstream file is locally forked: no helios/native/*.c (e.g. roce_proxy.c (not opened)) in the changed-file list, no Cargo.toml (not opened)/Cargo.lock change in any of the 19 files, and no new crate or external source. The one external-input-looking addition is legitimate and in-repo: the #[ignore]d test at helios/src/runtime_core/persistent_worker.rs:2596 compiles ignition/preparation/kv_codec_gpu.cu from this repository. No dependency on an unmerged external PR: the only external references are two recipe repositories named in prose ("companion recipe PRs in local-inference-lab/hyperflare-recipes"), which are outside-repo beneficiaries, not build or test dependencies — nothing in the diff or tests requires them. The #698/#701 overlap with an open PR is a duplication/collision issue for maintainers (already in the dossier), not a vendored-file or pin violation.


Gate 3 — Mandatory verification evidence & failing tests

No falsified or failing evidence; one narrow evidence gap (Info/Major-lite, disclosed).


Gate 4 — Material scope / claim contradictions

No fabricated evidence. Every headline artifact in the description is present in the diff at the cited locations: tests/preparation/test_codec_layout.py (not opened) (+150, incl. the CodecEncoding table test at :75-87 and default_field_encoding test at :209), the three TP≥2 pool tests at selene-manager/tests/packed.rs:1780 (not opened)/1857/2015, the #[ignore]d 3-way Green Context CUDA test at persistent_worker.rs:2596 (with the offload_context() == codec_context assertion at :3004 and the #698 comment at :3008), and early_startup_close_store_preserves_drain_and_slab_retention_contract at helios/src/server/runtime/phase_tests.rs:2367. The close_store free function and method exist exactly where described (helios/src/server/runtime.rs:1172 and :1357, invoked at :706, :719, :783, :821) and offload::open at :683 now precedes RankExecutor::new at :699. No thousands-of-lines unrelated tooling.

Two scope observations (Info, per charter AGENTS.md:171-199 "keep each PR focused on one coherent outcome"):

  1. The visible +2032/−137 is roughly double the authored change because the branch base predates merged main work (PR #697 preserve_message_anchor, PR #689 typed-error test) that appears in helios/src/server/runtime.rs, event_tests.rs (not opened) and most of phase_tests.rs. Rebasing drops the inherited half — hygiene, not a gate.
  2. Three independent outcomes are bundled (Ignition authoring, Selene pool policy, Helios CUDA scheduling). Not a hard violation, but the pool-policy part is the one that alters an already-merged safety posture (#612) and would review far faster on its own.

Also for maintainers (not a gate): #698 is the same startup-ordering fix and stays open; its review demanded the close_store ownership work this PR now contains, so the two will conflict textually and one must be closed as superseded.


Bottom line

Merging should be blocked on the two normative-doc updates (Gate 1) only; neither requires a design change to the implementation.

Full report · Notes

Code correctness

Deep Code Correctness, Invariants & Hot-Path Performance Audit — PR #709 @ eb6c1e1

Verdict: no Blocker and no Major defect found. The three riskiest claims in the PR (inverted packed-capability guards, a still-broken single-host TP≥2 world() check, and a context/ordering hazard introduced by moving offload::open before RankExecutor::new) are all disproved by the callee definitions, with citations below. What remains are six Minor defects, five of which are real but bounded, and one host-dependent flaky test.

18 files / ~2,240 changed lines across 3 subsystems, so the audit was partitioned into three disjoint slices (helios, ignition, selene-manager) run concurrently, then the open leads from each slice were verified by me directly against the files at eb6c1e1.


Negative results — hypotheses disproved in code (do not re-derive)

N1. permits_holding(None, …) / permits_offer(None, …) mean raw-only, not "allow all" — the new selene-manager guards are correct, not inverted

selene/src/shared/packed.rs:50-67:

pub fn permits<'a>(caps: Option<&CodecCaps>, profiles: impl IntoIterator<Item = &'a Vec<u8>>) -> bool {
    caps.is_some_and(|c| {
        c.envelope_revision == REVISION
            && !c.receive_profiles.is_empty()
            && profiles.into_iter().all(|p| c.receive_profiles.contains(p))
    })
}
pub fn permits_holding(caps: Option<&CodecCaps>, packed: bool, profiles: &[Vec<u8>]) -> bool {
    (!packed && profiles.is_empty()) || permits(caps, profiles)
}

caps = None ⇒ permits == false ⇒ permits_holding(None, true, _) == false and permits_offer(None, _) == false. So claims.rs:640-642 and lookup.rs:226-228 passing None genuinely excludes every packed record (including all-literal v4, since permits_offer only needs the literal-filtered profile list to pass permits), and raw v3 records still pass via the !packed && profiles.is_empty() arm. Intent matches implementation.

N2. claim.mp.req.layout.world() is a process count, so single-host TP≥2 packed PinAck really is now allowed

selene/src/shared/slice.rs:88-105 — Layout::world() is self.ranks.len() of the slice layout, which is collapsed for single-process sessions:

For single-process TP=2 (ranks == None, descriptor.ranks.len() == 2): req.layout.world() == 1 and src.layout.world() == 1, so the new guard at claims.rs:1181 (if any_packed && (claim.mp.req.layout.world() > 1 || claim.mp.src.layout.world() > 1)) evaluates false and the packed PinAck is accepted — the claimed fix. For true multi-process TP=2 (ranks = Some, world 2) it is rejected. core.rs:646-653 mirrors this and still revision-filters offered_codec for the reconnect comparison at core.rs:667 (old_sess.offered_codec == offered_codec && … && old_sess.ranks == ranks), so reconnect compatibility is unaffected.

N3. Moving offload::open before RankExecutor::new introduces no context hazard

offload::open (helios/src/offload/mod.rs:137-146) delegates to flare_selene::offload::open, whose transfer threads call RankWorker::open (helios/src/offload/transfer.rs:397-408). Stream::open_lowest_priority (helios/src/cuda.rs:785-786) calls Self::bind, which does cuCtxSetCurrent(codec_context) and does not restore the previous context — so the model thread is left on the codec context after offload::open returns. This is harmless here because every subsequent consumer in RankExecutor::new re-binds explicitly: Stream::bind (cuda.rs:740-756) and Stream::open (cuda.rs:758-764), used by transport.rs:623-624; else GraphExecutor::finish_startup issues cuLaunchKernel bound to the stream's context. The deadlock fix is also correctly placed: the worker launch happens in GraphExecutor::finish_startup → control.start(), still strictly after the store is opened.

helios/src/cuda.rs:445-471 registers with HOST_REGISTER_PORTABLE:

const HOST_REGISTER_PORTABLE: c_uint = 0x1;
…
driver.check("cuCtxSetCurrent", (driver.set_context)(context as Handle))?;
driver.check(
    "cuMemHostRegister_v2",
    (driver.host_register)(address as Handle, nbytes, HOST_REGISTER_PORTABLE),
)?;

memory.rs:1010 now passes self.ranks[0].context (primary) as registration_context while model.rs:966-969 passes rank.offload_context() (codec green context) to the transfer streams (transfer.rs:408). PORTABLE makes the registration visible to every context in the process, which is exactly the requirement — the two contexts differ, so non-portable registration would have been the bug; it isn't.

N5. Other probes that came back clean


Findings

1. Minor — the new codec Green Context never receives the core's Context settings

helios/src/runtime_core/mod.rs:780-785:

let (worker_context, compute_context) =
    (partition.worker_context, partition.compute_context);
self.green_partition = Some(partition);
apply_context_settings(&driver, worker_context, &core.context)?;
apply_context_settings(&driver, compute_context, &core.context)?;

Callee apply_context_settings (helios/src/runtime_core/mod.rs:1675-1695) applies core.context.limits via cuCtxSetLimit and core.context.cache via cuCtxSetCacheConfig. codec_context now exists (helios/src/runtime_core/persistent_worker.rs:388-396, cuCtxFromGreenCtx(codec)) and from this PR onward runs every GPU codec kernel and every offload DMA stream (mod.rs:1416-1421 → transfer.rs:408), yet it is omitted from both calls. CUDA context limits and cache config are per-context, and green-context-derived contexts are distinct contexts. Counterexample: a core whose Context.cache selects a preference the codec kernels are tuned for, served with --lossless-kv-compression gpu on a persistent-worker GPU: the same kv_codec_gpu kernels run with the declared setting on a non-persistent-worker core and with driver defaults on a persistent-worker core — a mode-dependent divergence in kernel-visible context state. Fix: inside the if let Some(worker) arm, apply_context_settings(&driver, partition.codec_context, &core.context)?; guarded by !partition.codec_context.is_null(), before self.green_partition = Some(partition).

2. Minor — the 3-way split hard-fails where the pre-existing 2-way split succeeds, with no fallback

helios/src/runtime_core/persistent_worker.rs:94-113:

let aligned_codec = if reserve_codec_partition {
    min_partition
        .checked_next_multiple_of(coscheduled)
        .ok_or_else(|| invalid("GPU codec SM partition overflows alignment"))?
} else { 0 };
let reserved_sms = aligned_worker.checked_add(aligned_codec)…;
if reserved_sms >= total_sms || total_sms - reserved_sms < min_partition {
    if reserve_codec_partition {
        return Err(invalid(format!(
            "… leave insufficient structured compute SMs; use --lossless-kv-compression cpu"
        )));
    }

(The arithmetic itself is sound — no underflow, aligned_codec ≥ min_partition ≥ 2 > 0, and groups 0/1 are explicit sm_count while the last uses sm_count = 0 + CU_DEV_SM_RESOURCE_GROUP_BACKFILL at :135-141, so ranges cannot overlap. (188, 8, 8, 8) → worker 8, codec 8, compute 172 reproduces the PR's example exactly.) Counterexamples where plan_sm_split(dev, r, false) returns Ok but (…, true) errors:

The only remedy offered is a global downgrade to --lossless-kv-compression cpu, so upgrading an existing gpu deployment on a small-partition device loses GPU compression entirely, even though the degrade path already exists: offload_context() (mod.rs:1416-1421) falls back to self.context whenever codec_context.is_null(). Fix: on reserve_codec_partition failure, retry plan_sm_split(device_sm_info, requested_worker_sms, false) and record that no codec partition was reserved, so offload_context() degrades to the base context; keep the hard error only for the genuinely unsatisfiable 2-way case.

3. Minor — _validate_codec_encoding rejects numpy integer scalars

ignition/preparation/contract.py:209-210 and :215-218:

if isinstance(value, bool) or not isinstance(value, int):
    raise ValueError(f"codec encoding for {label} must be an integer CodecEncoding")
…
if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
    raise ValueError(f"codec field offset for {label} must be a nonnegative integer")

numpy.int64 / numpy.uint32 — the natural output of recipe dtype/table lookups and of tensor.shape products — fail the isinstance(..., int) test even though CodecEncoding(value) and int(...) would accept them, so a legitimate recipe is rejected at export with a misleading "must be an integer" message. Fix: keep the bool rejection, then accept numbers.Integral (or operator.index(value) in a try) for value, offset, and length.

4. Minor — the duplicate-buffer guard rejects a legitimate page buffer named state_pool

ignition/preparation/contract.py:280, 299-304:

row_buffer = state_buffer or continuation_buffer or "state_pool"
…
seen_buffers = {row_buffer}
for region in page_regions:
    view = region["storage"]
    name = view["buffer"]
    if name in seen_buffers:
        raise ValueError(f"duplicate codec layout buffer {name!r}")

Seeding seen_buffers with row_buffer conflates "the row buffer is named state_pool" with "this page region duplicates the row buffer". Because state_buffer or continuation_buffer or "state_pool" falls back to the literal, the guard fires for a recipe that declares no CONTINUATION_STATE region at all and declares a paged KV plane whose view is named state_pool — the shape history_region(buffers, "state_pool", tensor, kind=…) (contract.py:329) produces. Pre-PR code emitted a field for it and Selene built two valid plans: selene/src/shared/codec_layout.rs:52-61 accepts any field.buffer matching g.row.name or a plane name, and build_plan is invoked separately for g.planes and for [g.row] (codec_layout.rs:108), so the name may legitimately appear in both. Counterexample: codec_layout(pool, [history_region(bufs, "state_pool", kv_tensor, kind=PAGED_KEY_VALUE)], bufs, field_encoding=default_field_encoding) → ValueError: duplicate codec layout buffer 'state_pool', where it previously returned a valid layout. Fix: start with seen_buffers = set() and reject only a duplicate between two page regions; if name == row_buffer is meant to be an error, gate it on an actual CONTINUATION_STATE entry or an explicit state_buffer having been supplied.

5. Minor — new validation is unreachable on two paths, so the documented contract silently does not hold

ignition/preparation/contract.py:256-260:

row_regions = getattr(pool.layout, "regions", ())
if field_encoding is None or not row_regions:
    return None
if state_buffer is not None and (not isinstance(state_buffer, str) or not state_buffer):
    raise ValueError("state_buffer must be a nonempty string")

(a) The state_buffer type check does not depend on row_regions, yet sits after the early return: codec_layout(pool_with_no_regions, [], {}, field_encoding=f, state_buffer="") returns None rather than raising. (b) row_bytes (contract.py:281, bounds check at :289-290) is defined by no producer in this repository — the only definitions anywhere are the SimpleNamespace fixtures inside the new test file (tests/preparation/test_codec_layout.py:12, 98, 145, 177, 203); the real row extent lives Helios-side (row.unit_bytes). So the check is dead for every in-repo caller and the four tests that appear to cover it pass trivially. Fix: move the state_buffer validation above the early return; either wire row_bytes to a real attribute or drop the check and the corresponding test claim.

6. Minor — get_answer re-derives the multi-process predicate with only the requester side

selene-manager/src/pool/claims.rs:922-929:

let caps = (claim.mp.req.layout.world() == 1)
    .then(|| {
        self.sessions
            .get(&claim.requester_sid)
            .filter(|s| s.ranks.is_none())
            .and_then(|s| s.codec.as_ref())
    })
    .flatten();

This is a third, narrower formulation of the rule than claim_begin (claims.rs:637-642, !requester_mp && !source_mp) and lookup.rs:217-228 (session.ranks.is_none() && !source_mp). It omits the source term. It is not exploitable today only because get_answer is gated on claim.manager.is_some() (claims.rs:914) and a manager-sourced claim is always given MpSide::whole(..) (claims.rs:878, world 1) — i.e. the correctness rests on an invariant held in a different function. Counterexample if that invariant ever changes: requester single-process TP=2 with valid v4 caps, source a multi-process TP=2 instance ⇒ caps = Some(..), permits_offer passes, and a packed offer from a per-rank-assembled source is leased into claim.records[…].packed at claims.rs:937-939. Fix: extract fn packed_caps(&self, requester_sid: u64, source_mp: bool) -> Option<&CodecCaps> and call it from all three sites, passing source = claim.mp.src.layout.world() > 1 here. (Same root cause as the three-way duplication; one helper removes the drift.)

7. Minor — the new CUDA test hardcodes a device VA, the exact fragility the PR blames for other failures

helios/src/runtime_core/persistent_worker.rs:2891 inside cuda_green_context_three_way_gpu_codec_runs_concurrently_with_persistent_worker_and_cooperative_compute:

let host_va = 0xc20_0000_0000u64;
…
    address: Some(host_va),
    memory: Memory::MappedHost,

The PR body attributes the pre-existing persistent_worker::tests::cuda_* failures to fixed device VAs (0x800_0000_0000, used at persistent_worker.rs:1357, 2114, 2466) colliding with CUDA UVA placement on its 16-GPU host, and those tests use 0xc00_0000_0000 for the host allocation (:1358, 2115, 2467). The new test merely picks a different constant (0xc20_…), so its stated "1 passed" evidence is host-configuration dependent and it will fail on the same class of host. Fix: obtain the mapped-host range through the runtime's own allocator (address: None) and relocate the stop_flag/metrics references, or reserve the VA with cuMemAddressReserve instead of a literal.


What was positively verified as correct

No instructions-addressed-to-the-agent or prompt-injection attempts were present in the material read.

Full report

Final review

Recommendation: Changes Requested

The three fixes are real root-cause fixes and the riskiest inverse-guard hypotheses are all disproved by the callee definitions (packed::permits(None) == false, MpSide::world() == 1 for single-host TP≥2, descriptor still used after the new guard). One verified code defect remains — the new codec Green Context never receives the core's recorded CUDA context limits/cache configuration while the two sibling green contexts do — plus two normative documents that the PR leaves contradicting or incomplete about behavior it changes. No blocker, no hot-path regression, no wire/format change.

Merge Risk

Level: Medium

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

  1. The new codec context never receives the core's recorded CUDA context limits and cache configuration. helios/src/runtime_core/mod.rs:767-786 applies apply_context_settings to the primary context (:768) and to partition.worker_context (:783) and partition.compute_context (:784) only; codec_context is created at persistent_worker.rs:388-396 and from this PR onward runs every GPU codec kernel and every offload DMA stream (mod.rs:1410-1421 → model.rs:969). The repo's own model is that these settings are not inherited by green contexts — hence the two explicit calls — and the pre-existing test asserts exactly that for the worker/compute pair (persistent_worker.rs:2218-2243, comment "verify recorded CUDA context limits propagate into both Green Contexts", asserting CU_LIMIT_STACK_SIZE on both). Result: the same kv_codec_gpu kernels run with the core's declared limits/cache config on a non-persistent-worker core and with driver defaults on a persistent-worker core under gpu compression — a core-shape-dependent divergence in kernel-visible context state. Fix: inside the if let Some(worker) arm, before self.green_partition = Some(partition), add if !partition.codec_context.is_null() { apply_context_settings(&driver, partition.codec_context, &core.context)?; }, and extend the assertion in the existing green-context test to the codec context (the new #[ignore]d test can assert it too).
  2. docs/runtime-core-design.md:642-672 now contradicts the shipped load/teardown path and was not updated. The normative core-loading spec still says SMs are partitioned "into two explicit structured SM resource groups" (:648-651), that the recorded limits/cache are applied "to the primary context and both green contexts" (:651-652), and that teardown destroys "worker and compute streams, executables, modules, mappings, green contexts" (:668-672). The implementation is now 2-or-3 groups with a codec_context, and the third context is the one whose teardown is newly special-cased (mod.rs:1641) — exactly the invariant a future teardown edit would need to know. Only docs/prefix-cache-offload.md was changed. Fix: update that section for the 2-way vs 3-way split, codec_context existence/teardown, and which contexts host offload and codec work.
  3. selene-manager/PROTOCOL.md does not state the new multi-process raw-only rule. §13.x at PROTOCOL.md:1050-1060 still only says every process of an instance offers identical capabilities and that "Instance holdings may be raw or packed", with no statement that a session with ranks negotiates raw-only (core.rs:641-651), that packed PutBegin is refused for it (store_bridge.rs:412), or that packed holdings/offers are excluded for a multi-process requester or source (claims.rs:637-642, :922-929, lookup.rs:217-228) while raw v3 stays claimable. AGENTS.md:233 makes this file the governing doc for Selene-manager changes. Fix: add the negotiation and exclusion rule beside the revision-4 envelope section, and state that single-host TP≥2 (single-process, world == 1) remains packed-capable.

Subtract / Simplify

  1. helios/src/runtime_core/persistent_worker.rs:2615 adds another full copy of the struct TestFiles / impl Files fixture already present earlier in the same file (e.g. :1285); hoist one #[cfg(test)] fixture instead of adding a fifth.
  2. helios/src/runtime_core/model.rs:820-821: reserve_codec_partition = options.prefix_cache.enabled() && !model.gpu_codec_cubins.is_empty() reduces to options.prefix_cache.compression == KvCompression::Gpu (verified: gpu_codec_cubins is non-empty only under KvCompression::Gpu, model.rs:629-658, and enabled() is implied). Writing it directly removes the positional false at mod.rs:334 and removes the ambiguity the review raised about cpu-mode cores.
  3. selene-manager: the requester-side conjuncts at claims.rs:640 (!requester_mp) and lookup.rs:226 (session.ranks.is_none()) re-verify the invariant core.rs:646 already establishes (codec = None when ranks.is_some()); only the source side needs a gate. Collapsing all three sites (claims.rs:637-642, claims.rs:922-929, lookup.rs:217-228) into one fn packed_caps(&self, sid: u64, source_mp: bool) also removes the third, divergent formulation in get_answer.
  4. persistent_worker.rs:94-113: the aligned_codec = 0 sentinel makes aligned_worker.checked_add(0) dead when reserve_codec_partition is false and duplicates the six-line error message; Option<u32> plus one interpolated message halves that block.

Nits

Dropped on verification

Full report · Notes

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (97%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.