Skip to content

[Minor] Improve the code style in TokenizerManager - #767

Merged
merrymercy merged 5 commits into
mainfrom
simplify-tokenizer
Jul 27, 2024
Merged

merrymercy merged 5 commits into
mainfrom
simplify-tokenizer

Conversation

@merrymercy

Copy link
Copy Markdown
Collaborator

No description provided.

@merrymercy
merrymercy merged commit 0736b27 into main Jul 27, 2024
@merrymercy
merrymercy deleted the simplify-tokenizer branch July 27, 2024 12:05
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
amote-i pushed a commit to amote-i/sglang that referenced this pull request Dec 8, 2025
* Update torch

* Update Dockerfile.npu
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…ost copy that was still in flight

SERVING RETURNED WRONG ANSWERS. On the full-feature boot, 9 of 10 SALTED greedy
"The capital of France is" probes came back degenerate -- ' France is France is
France is', and one that echoed the salt hex back. Salted means every probe was
a fresh prefix, so this was never a cache-key problem; the same prompt also
answered correctly on the 3rd attempt at temperature 0, which is what an anchor
that is intermittently missing looks like from outside. Bisecting on the two-curl
reproducer put it squarely on the sgl-project#755 reorder: 9/10 degenerate with
SGLANG_MAMBA_SLOT_REORDER=1, 1/10 with it 0.

THE PREDICATE BELIEVED AN INTENTION. `_mamba_early_release_admissible` asks two
questions and the second is `mamba_backuped`, which reads `mamba_host_value is
not None`. The write-through path publishes that value in the SAME block that
hands the transfer to the cache controller and then records the node in
`ongoing_write_through` / `_write_through_inflight`
(hi_mamba_radix_cache.py:412-432). So between queue and ack the anchor exists as
an intention only, `mamba_backuped` reads True, sgl-project#755 releases the pin, and the
node is evictable before its bytes have landed. Evict there and the anchor is
dead -- which is the exact failure the predicate exists to prevent, and its own
docstring already promised "host-backed RIGHT NOW".

Two silent symptoms confirmed it rather than contradicted it: ZERO sgl-project#755 refusals
were logged (every node claimed to be backed) while there were ZERO completed
backup markers, and a deliberate prefix repeat reported cached=None. A contract
that never refuses and never completes is not a contract that is being met.

THE FIX IS THE MISSING HALF OF THE QUESTION, not a disabled feature. The
predicate now also requires the copy to have LANDED, via an overridable
`_mamba_host_copy_complete`: True on the device-only pool, which has no async
write-through, and on the hierarchical pool a read of the in-flight bookkeeping
the write path already maintains. A node still in flight takes the documented
sgl-project#755 refusal path -- insert skipped, request keeps computing, counter says
write-through is behind -- instead of trading correctness for a slot.

Red-first: the three in-flight tests fail against the old predicate, and the
can-fail proof is that the device-only completion hook returns True for exactly
the node the hierarchical one now refuses. 7 passed.

Feature stays ON: the standing boot keeps the full set, reorder included.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…isk-tier poison

Records what the two-curl reproducer measured (9/10 -> 0/10 salted, cached path
green only after the store was replaced) and the operational half of the fix:
hicache_storage_backend=file persisted 14187 entries written by the defective
build, so the patch alone does not restore correctness on a rig that ran it --
the disk tier has to be purged. Residual ~1/10 salted intermittency is called
out as open, not closed.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…has nothing running

A DWELL IS A THRASH BOUND, AND THRASHING NEEDS WORK IN FLIGHT. With running_bs
0 and prefill pending, holding protects no throughput -- there is none to
protect -- and nothing can end the wait either: the request that would restart
the clock is exactly the one the hold refuses to admit. That is a livelock
wearing a bound's clothes.

THE SPECIMEN. A tp_to_pp cutover committed, and the next decision logged
"holding in pp: min dwell: 0.0s since last flip < 3s (pending prefill 5813 tok,
running bs 0)". Serving then sat idle for 464 seconds across 41
ADMISSION-WEDGE reports -- "1 queued, 0 running, and NO first token" -- until
the watchdog killed the process tree. health answered 200 throughout, which is
why neither health nor forward_ct catches this class and why the admission
detector exists.

THE GUARD IS NARROW ON PURPOSE: the dwell is released only when nothing is
running AND prefill is pending. Work in flight still bounds thrash exactly as
before, which the first test pins by feeding the same specimen with running_bs
2 and requiring the hold to remain.

Found while trying to MEASURE sgl-project#767: the over-time falsifier could not run at
all because the scheduler wedged under it, so this had to be fixed first to
unblock that acceptance rather than being left queued behind it.

3 tests, red-first on the specimen numbers.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…nd fix the metric that hid it

The queue-vs-ack fix was real (salted 9/10 -> 0/10) but did not close sgl-project#767. An
over-time run puts the residual on the cached-resume path: with HiCache the
fourth cached hit degenerates and stays degenerate for eleven consecutive probes
across ten further flips, with store=0 proving the disk tier is not required --
the poisoned entry is in-memory and disk merely outlives reboots. With the
anchor interval off the same trigger segfaults instead, which reads as one path
with two failure modes rather than two defects. With HiCache off entirely the
same probe sequence is clean, 0/14 and 0/10.

Also fixes the instrument: the old falsifier tested for the word 'Paris', which
condemns a coherent answer that says something else first -- all three
'failures' in the healthy arm were that artifact. degen.py tests repetition,
which is what the defect actually produces.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…ost in the pool solve

THE RULE IS RIGHT, THE SIZING WAS WRONG. `collective_kv_backing_relief` grants
nothing when the MANDATORY ask exceeds what the rung can return above its
admission floor, because laundering a short ask into a seam that then does not
fit is worse than a clean abandon. Untouched here. What that rule cannot
survive is a pool solved without the staging term: the ask is then unfundable
for the life of the boot, so the rung reports it could return 1902-2037 MiB,
grants 0, and logs "evicted 0 rows over 0 shrinks so far" -- 72 times in one
boot -- while every flip has to find its bytes somewhere else.

THE THIRD TERM, and it is none of the two already charged. The seam reserve is
what a flip COSTS WHILE IT RUNS and is only knowable by measurement. The arming
floor is a LEVEL THE GATE COMPARES AGAINST, derived from the stated corridor
law. The staging ask is what the rung must be ABLE TO FUND for the seam to
enter at all, and `project_staging_bytes` computes it exactly, because "the
plan's only live-set input is the slot count, and everything else is static
layout". Same class as the arming floor before it: a term the planner had every
input for and did not charge, producing a healthy-looking boot that never
flips, with no runtime recovery because the pool is fixed at boot.

THE FUNDABLE LEG ONLY. pp_to_tp is the leg the rung may shrink for and the one
whose refusal is fatal under strict purity; tp_to_pp abstains by design because
its pool is about to become active again and recover_kv_backing would undo the
shrink inside the same flip. Charging for a leg that never shrinks would hold
memory against a payment nobody makes. 33 of the 72 observed refusals were that
by-design abstention and are NOT what this fixes.

EXACT OR ZERO, NEVER INVENTED. When the projection is not reachable at sizing
time the post is 0 and the log says which of the two it charged, because a
fabricated constant would be indistinguishable from the exact figure -- the
derived_provenance defect this module already names. A cold zero means the pool
is sized as it was before, which is a visible outcome rather than a silent one.

Red-first on the specimen numbers from this rig's boot projection, 840 MiB
(rank 0) and 1617 MiB (rank 1): 6 tests failed on the absent function, 16 pass
now across sgl-project#767/sgl-project#768/sgl-project#771. ruff clean.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…orce-clear falsifier arm

THE BRANCH CANNOT TELL ITS TWO CASES APART. 'if req.mamba_pool_idx is not
None: pass' keeps a slot the request already owns and skips the clear. That is
correct for a LEGITIMATE carrier -- a chunked continuation holding its own
in-progress state, or a COW resume whose copy fills the slot -- and silently
wrong for a request that arrived with a recycled slot nobody filled. Today the
code cannot distinguish them, so this counts both and names whether a COW copy
is actually pending, with the rid and slot id.

SGLANG_767_FORCE_CLEAR is a FALSIFIER, not a fix: it clears every carried slot
to test whether the short-prompt nondeterminism is dirty initial state. A
blanket clear would also wipe a legitimate carrier's own state, so it stays
behind an env and never becomes the default. If determinism returns under it,
the fix belongs at whatever PRODUCER hands out a stale slot without a copy.

Aimed by the measurement that re-pointed this ticket: a 912-token prompt with a
real cache hit is 8/8 byte-identical, while the 5-token prompt that is never
cached varies 11 ways in 12 identical temp-0 requests -- a short prompt is
dominated by its initial recurrent state, a long prefill overwrites one.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…int-interval

THE PREMISE WAS WRONG. protect_deepest_anchors returned False whenever no
interval was configured, reasoning 'no interval means no grid, so there are no
anchors either way'. There are: the no_buffer path donates a checkpoint for
every finished request at cache_len = len(token_ids), grid or no grid, and
evict_mamba's own docstring says what losing the deepest one costs -- it
'silently moves the resume point of identical requests and re-introduces
run-to-run drift'. The interval only adds MORE anchors on top; it is not what
makes the deepest one worth keeping.

MEASURED, one commit, short-prompt determinism gate (identical temp-0 requests
must return identical bytes): 48 slots idle 10 probes = 1 distinct, 20 probes =
2, under 4-way load = 7 distinct with a degenerate one; 12 slots idle = 3.
Divergence tracks slot pressure, which is what eviction responds to.

THE CAPACITY TRADE IS REAL AND ALREADY BOUNDED. Sparing anchors shrinks the
evictable set, but evict_mamba already runs a SECOND pass with the window off
when the first cannot free enough, so the pool still yields under pressure and
this cannot deadlock an allocation. Sizing the pool so the spared set is
affordable is the slot-count planner post, not a reason to hand back
determinism.

The host-tier exemption is untouched and is the one real one: a node whose
device value is dropped stays matchable and is loaded back, so the resume point
does not move. Window size is unchanged (SGLANG_MAMBA_CKPT_WINDOW, default 2)
and is independent of the interval, which is why the ungate is functional
rather than nominal.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…determinism

The second pass exists so anchor protection can never deadlock an allocation,
and that rule is correct. But every anchor it takes is a resume point moved,
which is the determinism the first pass was supposed to buy -- so at the
acceptance load the second pass must not be REACHED at all. This counts it and
names the arithmetic (freed vs needed, both pass totals, evictable size), so
'the pool is too small for the protected set' can be told apart from 'the
protected set is too broad'. Instrument only; no behaviour change.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…not usable

THE THIRD PATH, and it shipped as a TODO. The unified component skips
branching-state fill whenever a cache_controller is present -- 'we temporarily
skip branching-state fill in that mode and can add a HiCache-aware branching
policy later'. Under a host tier that leaves a match returned with
len(value_chunks) > effective_best_len, no fill to establish the missing
recurrent state, and -- unlike the device-only lineage, which truncates with
value = value[:best_value_len] (mamba_radix_cache.py:1878) -- nothing trimming
the KV half. The request resumes attention KV at a depth its mamba state never
reached.

MEASURED, same tip, same argv, one flag apart: HiCache ON gives 10/16 and then
11/12 REP-degenerate answers to a short greedy probe ('France is France is ...',
' is is is is'), permanent once it starts. HiCache OFF on the identical
configuration gives 0 REP. Host-tier read markers (load_back,
backup_from_device, write_through_ack, host_hit) are all ZERO on the failing
boot, so this is not the read path being exercised -- it is the match contract
differing between the two lineages.

THE RULE IS ALREADY WRITTEN DOWN, at the COW-starvation path: 'Reusing the KV
prefix without the matching mamba state would be silently wrong, so the full-KV
match is dropped as well.' This applies it to the host-tier lineage. Dropping
the match returns a cache MISS and costs prefix reuse -- a throughput cost --
where serving a mismatched state is a correctness one. The strict-resume case is
excluded because it already zeroed the result, and the device-only branch below
is untouched, so the path becomes reachable again the moment a HiCache-aware
branching policy exists.

Counted and named, so 'how much reuse did this cost' stays answerable.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…pleting the interval contract

THE GATE SPLIT A CONTRACT IN HALF. branching-state fill was gated on
'cache_controller is None' with the note that it was 'temporarily' skipped under
a host tier. But the checkpoint interval is a PAIR of behaviours: inserts are
grid-gated (an off-grid finish caches nothing) AND the fill establishes the grid
anchor. Keeping the first while skipping the second lets a match reach a depth
its recurrent state never did.

MEASURED AS A CLEAN 2x2 on the short-prompt gate, which is what separates this
from either feature being at fault:

    HiCache off, interval off -> 0/16 REP, 2 distinct
    HiCache off, interval ON  -> 0/16 REP, 1 distinct   (full pass)
    HiCache ON,  interval off -> 0/16 REP, 6 distinct
    HiCache ON,  interval ON  -> 10/16 REP

Neither flag alone degenerates; only the pair does. The reachability is
measured too: the fill's own predicate (len(value_chunks) > effective_best_len)
fired 9 times on the REP arm and 0 times on the passing arm, so this is the
condition that exists only under a host tier.

branch_grid semantics are unchanged (interval when configured, else the FLA
chunk size), so the two lineages stay readable against each other -- the drift
sgl-project#747 already records is not widened here.

Replaces the interim guard from ec48743, which dropped exactly these matches
instead of filling them. Dropping was safe but not sufficient: REP persisted at
6-10/16 with it active, because the consumer is not the producer.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…host tier (scaffolding)

NEITHER FLAG ALONE DEGENERATES; THE PAIR DOES. Measured as a 2x2 on the
short-prompt gate, identical temperature-0 requests scored for REPETITION
rather than for wording:

    hierarchical off, interval off -> 0/16 REP, 2 distinct
    hierarchical off, interval ON  -> 0/16 REP, 1 distinct   (full pass)
    hierarchical ON,  interval off -> 0/16 REP, 6 distinct
    hierarchical ON,  interval ON  -> 10/16 REP

The failure is repetition -- ' France is France is France is' -- permanent once
it starts, which is a correctness fault rather than the run-to-run drift the
sgl-project#412 determinism certificate documents as expected behaviour.

THE UNDERSTOOD HALF IS ALREADY REPAIRED and this refusal is not a substitute
for it: the branching-state fill now runs under a host tier (fa68dcb), so the
interval's grid-gated inserts and its anchor-establishing fill are no longer
separated. That did not clear the REP (6/16 with the fill in, against a 6-11
run-to-run band), and neither did dropping the affected matches outright
(ec48743), so the match-time mismatch is a SYMPTOM and the producer is still
unidentified.

Until it is found, the combination must not ship silently wrong -- a confident
wrong answer is the worst class this corpus tracks. Both features are wanted
together, so this is scaffolding written to be deleted by the commit that finds
the producer, and it says so in its own docstring.

ruff: 357 pre-existing F722 in this file at HEAD and after, none added.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
THE CHECK WAS IN THE WRONG PLACE, NOT MISSING. write() already refuses at
ENQUEUE via the sgl-project#718 device-tier disarm. The copy happens later, and the flip
rebinds in between, so a write-back queued before a cutover reaches
backup_from_device_all_layer carrying a pointer table into the pool it was built
from. Both crash specimens died three seconds AFTER a pp_to_tp cutover
completed: 14:08:14 -> 14:08:17 (epoch 27) and 07:12:09 -> 07:12:12 (epoch 3),
seven hours apart, same direction, same lag.

WHY THE SHAPE GUARD COULD NEVER CATCH IT, and why its silence was misread as
innocence -- by me, until the operator pushed back. Under layer_first the host
layout EQUALS the device layout, so a stale binding is shape-IDENTICAL to the
live one and check_shapes passes by construction. That is exactly what sgl-project#760
recorded: KV-TRANSFER-GUARD armed on all three ranks, zero transfers refused,
SIGSEGV anyway. Matching shapes plus a crash puts the fault below the Python
seam; a generation stamp is what tells "same shape" from "same pool".

MEASURED, ONE VARIABLE. HiCache host+disk under sustained 4-way load with the
flip REMOVED (plain TP3, which keeps speculation on -- PP+spec requires the
flip, server_args.py:18385) survives five minutes with 0 segfaults and 0
admission wedges, and passes the REP gate outright (1 distinct/12, salted 0/6).
The fault needs the cutover.

STAMPED BY CONSTRUCTION, VERIFIED AT CONSUME. The stamp lives in
CacheOperation.__init__ rather than at one enqueue site: an op built by any
other path would otherwise be unstamped, and an unstamped op must be refused,
which silently dropped legitimate write-backs and broke the staged-dispatch
tests until I moved it. A stale op is dropped loudly and counted; its prefix
simply misses later, the same cheap failure the sgl-project#718 disarm already accepts.

Also folded in, both consequences of earlier sgl-project#767 work rather than new choices:
the anchor-protection test that encoded "no interval means no anchors" is
updated to the corrected premise it was measured against, and the SECOND-PASS
EVICTION line drops from warning to info -- the second pass is documented as
legitimate, and anchor eviction was falsified as the drift cause, so it is
accounting rather than an alarm.

4 new tests, red-first (a pre-rebind stamp must be refused). mem_cache and
managers suites: 4047 passed, 43 failed -- all 43 the pre-existing sgl-project#772 class
(PhasePolicyConfig lacks idle_locked_settle_s after the sgl-project#713 revert), one fewer
than the 44 baseline because the 747 premise test is now correct. ruff clean on
both touched files (0 at HEAD, 0 now).
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…s at the flip, write state bytes in the computing pool

The sgl-project#767 round-2 residual (NOTE_735: 'the fourth cached hit degenerates
and stays degenerate') rooted to two wrong-pool defects in the mamba
checkpoint path of a phase-flip build, found via two new metal
discriminators on boot 735_seamfix2 (39 epochs standing):

  - salted probes with a UNIQUE first token: 0/8 degenerate, serial;
  - salted probes sharing one lead token: ~10/12 degenerate, including
    one answered with a verbatim FOREIGN topic (the load run's river
    essay) that survived /flush_cache;
  - concurrent unique-lead probes: 2-3/8 degenerate with prompt-level
    bleed.

So corruption enters exclusively where a prefix hit restores a mamba
checkpoint, and the payload is stale pool bytes:

1. resident_mamba_slots() moved only live requests' slots at a cutover
   while the KV leg unions the radix tree's values. Every tree-held
   checkpoint kept its slot NUMBER across the flip while its CONTENT was
   never translated into the new layout's pool; the prefix-hit COW
   (model_runner._maybe_execute_deferred_mamba_cow_and_clear) then
   seeded fresh requests from whatever the active pool held at that
   slot. flip_mamba_slots() now unions the tree's mamba values, and
   refuses a tree that cannot enumerate them.

2. The radix caches' checkpoint copies (donate-copy in cache_unfinished,
   int8 store_from_active) ran through the tree's bound pool -- the
   primary PP stack's, forever -- while a TP-phase request's real state
   bytes live in the TP stack's pool. The copy therefore duplicated the
   PP tensor's stale previous occupant into the checkpoint even with no
   flip during the request's lifetime. State-byte operations now resolve
   the computing stack's pool (mamba_state_pool.active_mamba_state_pool,
   installed by build_gdn_flip_mover); slot bookkeeping stays
   single-authority on the bound pool. Non-flip builds have no resolver
   and keep the old path bit for bit.

Excluded by prior metal falsifiers and this trace: the sgl-project#767 slot-carry
branch (0 carry-without-copy logged, force-clear changed nothing),
allocator divergence (single authority by construction), fresh-no-match
prefill state reads (has_initial_states = extend_prefix_lens > 0),
ping-pong track path (no_buffer on this shape), ReplaySSM (refused by
gdn_flip_preconditions).

Tests: test_gdn_flip_tree_slots_767.py (red-first: ImportError then 5
passed), test_mamba_checkpoint_active_pool_767.py (7 passed).
mem_cache+managers suites: 4071 passed, 43 failed -- all the
pre-existing sgl-project#772 PhasePolicyConfig class, plus the known env-dependent
test_localslot_family_756 retry failure (fails identically on clean
HEAD). Metal validation on the rebooted arm follows in the boot note.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…cow+clear / mtp commit)

Env-gated, default-off tracing for the residual wrong-context bleed on
the fix767 arm (fresh probes answering WARMUP questions -- banana, 4+5,
black-image -- with cached=0 and no shared prefix with the donors):
- unified match finalize: match len, cow, mamba_value, host hit;
- model_runner deferred cow/clear: indices per extend batch;
- update_mamba_state_after_mtp_verify: dst slots, steps, pre-commit row
  sums.
Diagnostic only; no behavior change with the env unset.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…rn reason

TP-phase probe prefills produced ZERO cow_and_clear lines while the
bleed reproduced -- the executor never runs there, so fresh requests
keep the previous slot occupant's state bytes. Name the eaten branch.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
…arget

The phase-flip TP TARGET worker is deliberately built with
is_draft_worker=True (phase_flip_boot.py, init reuse), and
_maybe_execute_deferred_mamba_cow_and_clear early-returned on that raw
flag -- so EVERY TP-phase extend dropped its pending mamba clear/COW
indices. Metal (boot fix767t3, SGLANG_767_TRACE): probe prefills logged
'SKIP: draft=True mode=1 clear=[5]' while fresh salted probes answered
the WARMUP requests' questions (banana, 4+5=9, the black test image)
out of uncleaned slots -- with the radix side proven clean in the same
trace (all probe matches best_len=0, no COW, no host hit).

Guard on is_draft_model_runner (model_runner.py:517), which is False
for the flip TP target and stays True for the real draft runner --
whose skip remains correct: it shares the target's pool and runs after
the target wrote fresh state; a re-clear there would zero it.

This is the deepest of the three sgl-project#767-residual wrong-pool defects and
the one that produced foreign-content answers without any radix match;
ecef447's two fixes (tree slots carried at the flip, checkpoint
copies in the computing pool) stand on top of it.

Tests: test_mamba_cow_clear_owner_767.py red-first (flip-TP-target case
failed on the raw flag, 3 passed after), plus the ecef447 suites
unchanged. Metal verification on the rebooted arm follows.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 19, 2026
… is found

db2e86f's scaffolding refused --mamba-checkpoint-interval together
with --enable-hierarchical-cache after the pair measured 10/16 REP. Its
docstring says it is deleted by the commit that finds the producer. The
producer was the sgl-project#767 wrong-pool family, fixed in ecef447 and
b6cdbed: dropped TP-phase mamba clears/COWs (the flip TP target
posing as a draft runner), checkpoint copies reading the bound instead
of the computing pool, and tree-held checkpoint slots not carried at
cutovers. The interval merely raised the number of live checkpoints and
with them the collision surface -- which is why the pair amplified a
corruption that HiCache alone already exhibited on salted probes.

On b6cdbed the base arm passes every gate the refusal cites: REP
1 distinct / 16, 0/16 degenerate; salted 0/8; cached hits 0/12 REP;
2 load runs with cutovers, 0 SIGSEGV. The pair arm's acceptance runs on
the boot that follows this commit and is recorded in the boot note.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 20, 2026
…sides

The two fixes on this branch make prefixes reusable again, and the failure
mode that has to stay shut while doing so is sgl-project#767: a resume whose KV and
recurrent state belong to DIFFERENT positions, which surfaced as a foreign
request's text continuing into a fresh prompt. Widening a match is exactly
how that comes back, so the guard is now asserted, not argued.

test_resume_stops_at_the_position_the_state_was_taken builds a path where
deeper KV genuinely exists past the anchor -- otherwise the assertion would
be vacuous:
  A: 128 raw tokens, on-grid at interval 64 -> files an anchor at raw 128
  B: 168 raw tokens extending A, off-grid   -> KV retained, NO anchor
The path then carries 167 bigrams of KV while the deepest snapshotted state
is at raw 128, and the test requires both: that the tail really was retained
(167), and that a query for B resumes at 127 bigrams (raw 128), never 167.

Can-fail control: making is_resume_candidate accept anchorless nodes
reproduces the sgl-project#767 widening exactly --
  "AssertionError: 167 != 127: the resume point must be the raw position
   the state was taken at"
and simultaneously reddens the two tombstone guards with
  "AssertionError: 64 != 0: a tombstoned node must never serve as a resume
   anchor"
so all three assertions discriminate the rule rather than the harness.

Full test_unified_radix_cache_unittest.py: 212 errors / 648 skips, identical
failure set to the pre-sgl-project#783 baseline, zero new failures. ruff clean on the
added code (the 6 findings in this file are pre-existing, lines 1637-2182).
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 20, 2026
…ving hot paths

An isolation boot wedged for 25+ minutes with 120 ADMISSION-WEDGE markers.
py-spy (two dumps 25 min apart, byte-identical, so hard-stuck) put PP0's
MainThread INSIDE logging.emit while PP1 and PP2 starved in
pp_chain_receiver.recv for a chain send PP0 never reached.

ROOT CAUSE. PP0 admitted the first radix-carrying request and reached the
sgl-project#767 instrument in HybridReqToTokenPool.alloc, which logged
req.mamba_pool_idx -- a 1-element CUDA tensor -- as a %s argument. The
format call runs Tensor.__repr__ -> _tensor_str -> a D2H copy -> a stream
synchronize, inside logging.emit, on the admission path. The device was
occupied by a spinning ncclDevKernel_SendRecv, so the sync never returned.
The instrument produced ZERO output on that boot: the record died mid-format,
which is why the log looks like the branch never ran.

THE TRAP, NAMED SO IT IS NOT RE-INTRODUCED. Every obvious way to print the
value synchronizes: %s/str()/repr(), .item(), .cpu(), .tolist(), float(),
int(), and f-string interpolation. A fix that swaps one for another only
relocates the sync. sync_free_tensor_repr returns host-resident metadata
instead -- shape, dtype, device, and id() to correlate one tensor handle
across lines -- and passes non-tensors through unchanged, so a value that is
sometimes a tensor and sometimes a plain int is safe either way.

SWEPT THE FAMILY (sgl-project#695: expensive work inside logging arguments on serving
paths), fixing six more sites of the identical shape:
  mamba_component.py               sgl-project#767-TRACE prefix-match
  model_runner.py                  sgl-project#767-TRACE cow_and_clear SKIP and body,
                                   per extend forward pass -- hotter than the
                                   original site
  mamba_radix_cache.py             cache_finished / cache_unfinished / match
  dflash_solo_pool.py:_reclaim     THE ONE WITH NO GATE

The dflash site matters most: every other hit sits behind an opt-in debug
flag, that one runs unconditionally on decode-time draft-slot allocation
under real load. It computed self._slot_epoch[victims].max().item() purely
for a diagnostic string. Victims are drawn from the ascending argsort's low
end, so their epoch is bounded above by self._epoch, which is already a host
int -- and the message text is REWORDED to match what is now reported
("at round X ... untouched since before this round") rather than quietly
printing a different number under the old wording.

LISTED, DELIBERATELY NOT FIXED, with reasons rather than silence:
phase_flip_output_trace.trace_round and phase_flip_resident_carry's cutover
falsifier (both bounded on purpose, the second says so in its own comment),
ngram_corpus.debug_result (reachable only from a __main__ demo), and
dspark_planner._log_verify_lens_decision -- mechanically the same shape and
genuinely hot when armed, but its whole purpose is the exact per-request
values, so an identity stand-in would gut the tool rather than trim it. It
wants rate-limiting, not this treatment, and is left as a named follow-up.

TEST. test_admission_log_no_device_sync_790.py, hermetic and CPU-only. A
tripwire monkeypatches Tensor.__repr__/__str__/item/tolist/cpu/__float__/
__int__ to raise, and the test drives the REAL HybridReqToTokenPool.alloc
through the sgl-project#767 branch rather than a re-implementation. Red-first was
demonstrated by reverting just the one call-site argument: the tripwire fires
through alloc -> logger.warning -> emit -> format -> getMessage -> msg % args,
reproducing the incident's exact path. Green after: 5 passed. A can-fail case
restores the identity formatting to prove the trap still fires from inside
the real branch.

Verified with the sgl-project#788 and sgl-project#787 suites alongside: 12 passed.

Pre-existing and NOT caused by this change: 4 failures in
test_mamba_anchor_seams_747.py (AttributeError: 'MambaComponent' object has
no attribute 'cache' in _raw_token_pos), confirmed identical with the change
reverted. Ruff findings in mamba_radix_cache.py and model_runner.py outside
these hunks are pre-existing lint debt.

This is the probable cure for the isolation boot's wedge: the log sync was
the linchpin edge of that cycle. It does not touch sgl-project#789 -- one relay, two
transports, no shared readiness contract -- which remains open debt.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 22, 2026
… unified lineage

The previous commit refused the sgl-project#755 floor reduction because the lineage
that gets built does not implement the mechanism. This builds it, and the
floor drops back to 1+P+1 -- honestly this time, because the runtime now
does what the arithmetic claims.

MECHANISM. cache_unfinished_req releases the OLD anchor's mamba pin BEFORE
the donation allocation instead of after the insert, so the old and new
anchors never coexist and a running request holds active + donated rather
than active + donated + old pin. That is the slot, and on the standing
boot (max_running_requests 8) it is 8 of them.

STRICTLY SAFER THAN THE ORIGINAL, and this is why the port was worth
doing rather than re-gating. MambaRadixCache releases the WHOLE node lock
early; inc_lock_ref walks ancestors for the FULL component, so its window
also leaves the request's own matched KV prefix evictable. The unified
tree locks per component, so dec_mamba_lock_only drops ONLY the mamba
lock: the KV path stays protected and the single state slot being
un-double-counted is the only thing made evictable. dec_swa_lock_only is
the same shape for SWA, so this is the file's existing idiom.

PER-NODE GATE. The config predicate cannot know whether THIS anchor
survives losing its slot, so MambaComponent.anchor_release_admissible asks
again: the node must carry a host copy (an evicted-but-backed anchor is a
valid match that triggers load_back -- is_resume_candidate's
device_only=False rule), and that copy must have LANDED. sgl-project#767: write-through
publishes host_value the moment the transfer is handed to the controller
and records the node in ongoing_write_through in the same block; between
those two facts the anchor is an intention only, and releasing there is
the dead anchor the gate exists to prevent.

PAIRING, which is where this class of change goes wrong (sgl-project#583). Two exit
paths, both handled:
  * the normal path skips the mamba half at the usual dec_lock_ref, via
    the skip_lock_node_ids set the components already consult -- a ref that
    was never taken must not be given back;
  * the bail path (nothing inserted, so no new anchor takes over the pin
    and req.last_node is unchanged) RE-ACQUIRES, restoring the exact
    pre-call state rather than carrying an imbalance into the next call.

TESTS: test_mamba_reorder_unified_773.py, 17 tests, CPU-only.
The end-to-end pair is the real proof: the pool is sized so the donation
allocation can only succeed if the old anchor was released first (2 slots
= one active + one anchor, free = 0). A backed anchor caches; an unbacked
one, identical in every other respect, does not. That is the saved slot,
observed as behaviour rather than as arithmetic.

CAN-FAIL, ALL EXECUTED, and three of them were earned the hard way:
  * unwiring the reorder in cache_unfinished_req  -> 1 fails
  * dropping the skip set                         -> 1 fails
  * dropping the bail re-acquire                  -> 1 fails
The last two SURVIVED the first version of this file, because every
pairing test simulated the sequence by hand instead of driving the entry
point. release_component_lock no-ops at zero, so a double release on a
singly-held node hides completely; it only shows when the anchor has a
SECOND holder, whose ref the unskipped release would steal. Both tests
were rewritten to go through cache_unfinished_req, and the skip-set case
needed a spare slot -- with a full pool the step bails and correctly
restores the pin, which is a different path and now has its own test.

Floor on the standing boot: 24 -> 16. The retention budget introduced in
703b05c becomes 8 slots instead of 0, so mamba host backups are
possible again rather than uniformly declined.

REGRESSION: test/registered/unit/mem_cache/ = 1473 passed, 8 failed, the
same 8 as an untouched HEAD worktree, diffed name-for-name.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 22, 2026
… the refusal too

THE PHYSICAL ROOT of the unwritten trailer, and it is not memory pressure.

`_dist_exchange`'s `incoming_nbytes` is a PREDICTION. The caller derives it
locally -- `gdn_flip_mover.move` computes `_pair_nbytes(..., len(slots), ...)`
from its OWN rank-local slot enumeration -- while the sender packs its payload
from ITS OWN. For the GDN leg that enumeration is `flip_mamba_slots`, "resident
requests' mamba slots UNION the radix tree's checkpoints", which has NO
cross-rank agreement step at all. Its own docstring contrasts it with the KV
leg's `build_flip_live_slots_fn`, which does agree by union; sgl-project#767 fixed what
this leg enumerates but left it rank-local.

On 2026-08-22 the three ranks had enumerated 150695 / 159848 / 151656 rows, and
PP1 -- the peer whose payload failed -- had spent the preceding six seconds in a
void livelock (2353 x #797d paired with 2353 x sgl-project#798, on three real retractions;
the healthy boot ran 5 voids on 5 retractions).

FOUR INDEPENDENT MISSES let a short receive through:
  * the receive buffer is `torch.empty` and is never zeroed;
  * NCCL p2p with mismatched counts does not raise;
  * the receiver's length check passes -- an under-filled buffer keeps its
    ALLOCATED numel;
  * `bounded_collective` polls `is_completed()`, never a byte count.
So the tail keeps allocator garbage exactly where the checksum trailer is read,
and the flip died reporting a corruption that had not happened.

THE FIX is a size agreement before any byte moves: one zero-filled matrix
summed across the group carries both halves -- what each rank will SEND to each
peer and what each rank has SIZED ITS RECEIVE for -- and every rank checks every
ordered pair against the identical matrix. It runs unconditionally and BEFORE
the `if not ops` early return, because a rank that skipped it while its peers
entered it would be the desynchronisation this exists to prevent.

THE REFUSAL IS COLLECTIVE, and the first cut of this guard was not. Its own
three-process test caught that within a minute: checking only "what MY peers
advertised versus what I expected" makes the verdict rank-local, so in a
three-rank group where rank 1 packs short, ranks 0 and 2 raise while rank 1 sees
nothing wrong, walks into `batch_isend_irecv` and blocks for ever on peers that
have already left. A guard that strands the group is worse than the corruption
it prevents. Both halves are now gathered and every rank reaches the identical
verdict off one shared matrix.

RESIDUAL RISK, STATED PLAINLY. `_dist_exchange` serves three callers -- the GDN
mover, the flip seam leg (phase_flip_runtime) and the KV reshard leg -- and the
guard now applies to all of them. That is intended: a p2p pair whose two ends
disagree on the byte count is never legitimate. But it cannot be exercised on
metal from here. If "SIZE DISAGREEMENT" fires on the KV or seam leg at the next
boot, that is a second, previously invisible instance of this same defect and
not a regression of this change -- the previous behaviour was to receive short
and read garbage.

TESTS (CPU, real three-process gloo group, driving the SHIPPED `_dist_exchange`):
  test_reshard_size_agreement_802.py                    2 passed  (new)
  test_gdn_payload_trailer_802 + gdn_flip_tree_slots_767
    + kv_reshard_headroom_363 + kv_reshard_stuck_arm_363
    + seam_arena_tail_additive_656                     57 passed

CAN-FAIL: the mutant that restores the rank-local verdict (`receiver != me`)
does not fail the suite -- it HANGS it, which is precisely the defect. Bounded
demonstration: the mutant does not complete within 60 s; the fixed build
finishes the same case in 5.2 s. The empty-exchange case is the second
direction: it pins that the collective still runs when a rank has nothing to
move, which is the deadlock this change could otherwise introduce.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 23, 2026
…t#816, sgl-project#810, sgl-project#806, sgl-project#797, sgl-project#790/sgl-project#777, sgl-project#817/sgl-project#820, sgl-project#818

Merge-checklist duty for the nine stages on this branch. Entries follow each
section's own house style, and the mechanism text is taken from the commits'
measured evidence rather than restated from the ticket titles.

§3 KV backing relief + the allocator cap -- UPDATED IN PLACE rather than given
a second bullet, because sgl-project#814 and sgl-project#816 are follow-on defects OF the KvRowCap
mechanism that bullet already describes: the census reading the withheld block
as a leak (340262 of 465190 ids), the lift being reachable only from a cutover
(one boot at 26.8% of its id space for the life of the process), and exposure
exceeding the backing (417850 rows over 105413 committed, the device-side
assert in masked_set_kv_buffer_kernel).

§3 HiCache staging write-through ring (sgl-project#810), new bullet, plus its two
companion refusals -- the unbounded-file-tier refusal and the boot preflight
ledger entry, the latter being why 22.01 GB of MHATokenToKVPoolHost across
three PP ranks previously reached the preflight as nothing.

§7 BAR1 deadline + loud abort -- appended the sgl-project#818 peer-liveness half to the
existing narrative: the gate could wait forever on a peer that no longer
exists, and neither Bar1CollectiveStalled (reset by every resolved read) nor
defer_stall_for_building_peer (900 s off a build marker) caught it.

§12 Robustness canon -- three new families: contradictory-flag (sgl-project#806),
read-back-after-construction (sgl-project#797), denylist-of-reasons (sgl-project#817, sgl-project#820).

§18.3 hicache staging sizing (sgl-project#810) -- §18's own rule is that a merge adding a
reusable module adds its entry in the SAME merge, and this module had none.
Records the removal of fits_pinned_host_budget so it is not reintroduced.

§18.6 mamba carry instrument (sgl-project#767, gated by sgl-project#790) and flip break-even N
(sgl-project#777).

No existing entry was contradicted. Checked before writing: none of sgl-project#814,
sgl-project#810, sgl-project#806, sgl-project#772, sgl-project#797, sgl-project#790, sgl-project#777, sgl-project#817, sgl-project#820, sgl-project#818 had a catalog entry, and
the one sgl-project#677 line (§19.2, RESTORE-NEVER-REBUILD) describes a different
mechanism than the sgl-project#677 layout hold, so it is not stale and was left alone.

Gates for the tree this documents (hermetic, CUDA_VISIBLE_DEVICES=""):

  battery test/registered/unit/{managers,planner,server_args,mem_cache}
    baseline integ @ 78d27da       44 failed
    c56d238 (through sgl-project#818)         30 failed, 8452 passed   0 new ids, 14 fixed
    1c4eadb (through sgl-project#816)         30 failed, 8461 passed   0 new ids, same set
  test_barlink_abort_gate_liveness_818.py (outside the battery dirs)  10 passed
  ruff --select=F401,F821,UP037 and codespell: 0 new findings vs the same
    file set on 78d27da (16 ruff / 6 codespell exist identically on base)
  docs-only change; codespell clean on the catalog itself
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 25, 2026
…r guard, and the consumers split

W38-B died six seconds into the TP phase, three ranks at once:

    hybrid_cache_controller.py:583  start_loading
    hybrid_cache_controller.py:729  move_hybrid_indices
    cache_controller.py:1217        device_indices = device_indices.cpu()
    AttributeError: 'NoneType' object has no attribute 'cpu'

ROOT, and it is structural rather than a missing None-check. At 17:25:53 the
controller was rebound to the 'tp' pools (generation 3). The TP host tier is
built at phase_flip_boot.py:2019-2032 with EXACTLY ONE entry, PoolName.KV --
on a model whose boot-time tier is `pools=KV + MAMBA`. Six seconds later a
mamba state living only on the host was matched (MAMBA-HOST-RESUME, the first
in any boot on this branch), load_back built the mamba PoolTransfer with
device_indices unset BY CONTRACT, and `_resolve_pool_transfers_allocation` --
whose contract is "auto-alloc where they are None" -- found no entry for
MAMBA and `continue`d, returning the transfer unresolved inside the same list
as the resolved ones.

`check_shapes` admits that rebind because it compares ONE SCALAR, the anchor's
layer count. The invariant that was actually violated is structural: the
incoming tier must describe every pool the outgoing one did. Nothing asked.

THE CLASS, and it is why this is a sweep and not a one-line fix: a narrower
binding installed under a scalar guard splits its consumers in two.

  * THE ONES THAT CRASH  -- move_indices dereferences the unresolved index
    set (this specimen); its write-side twin dies one line lower at
    cache_controller.py:1218 on host_indices.sort() and simply had not fired
    yet.
  * THE ONES THAT SKIP SILENTLY -- HostPoolGroup.load_to_device_per_layer
    (:1758) and backup_from_device_all_layer (:1789) skipped a transfer whose
    pool they did not know. The KV moves, the recurrent state does not, and
    the radix tree goes on reporting the prefix RESIDENT: a wrong ANSWER.
    This is the site that would have HIDDEN the defect had only the crash
    been patched, and it is LIVE rather than latent on the
    kernel/page_first/write-back-JIT path, which hands op.pool_transfers to
    the executor RAW (hybrid_cache_controller.py:468-475), bypassing
    move_hybrid_indices -- so on that configuration no crash could ever have
    exposed it.
  * THE ONES THAT LEAK -- append_host_mem_release (:389) and the drain in
    unified_radix_cache (:3035) resolved a release through the CURRENTLY
    bound entry_map, so after a rebind an extra pool's host slots were
    neither queued nor freed. One leak per load-back, for the whole phase.

REFUSE, NEVER SKIP, at every one of them. Skipping moves the KV while the
state stays behind and the tree calls the prefix resident; refusing costs a
recompute, which is merely slow. That trade is already the tree's own, at
mamba_component.py:986-991 (slot starvation -> re-prefill the segment) and
throughout hicache_phase_guard (a refused prefetch is a miss now). No
mechanism is invented here: the refusal path (rollback_allocated + return
None, with callers freeing what they took at :439 and :554), RebindRefused,
and the `name in entry_map` idiom (hybrid_pool_assembler.py:779) all already
existed.

WHAT CHANGED
  hicache_phase_binding.check_pool_coverage  the rebind now compares the POOL
    SET, not one scalar; called from rebind() beside check_shapes. A refused
    rebind leaves the sgl-project#718 device tier disarmed, which the code already
    documents as the correct state: every read-through misses, and a miss is
    recomputed.
  _resolve_pool_transfers_allocation  refuses instead of returning a
    half-resolved list, at the FIRST pool it cannot resolve (not after
    allocating and rolling back the later ones), with a rate-limited refusal.
  ... and carries a POST-CONDITION: a returned list contains no None index
    set. That is the check that turns a boot-second-20 crash into a unit
    test, and it stands on its own -- a DERIVED transfer copies its source's
    index sets and no per-branch check inspects it, so the post-condition is
    the only thing between that None and move_indices.
  HostPoolGroup._entry_for_transfer  the executor raises, naming the pool and
    the tier, instead of skipping. Per-LAYER skips (layer_mapper -> None)
    stay: those are legitimate and are covered by a control test.
  entry_for_extra_release  both release paths resolve through the entry
    captured beside the queue when neither the bound tier nor the registry
    knows the pool, and say so (rate-limited) rather than dropping slots.

RESIDUAL, handled rather than noted: match_prefix re-derives the host hit
every tick, so a refused load-back REPEATS every tick for as long as the
state sits on the host. The request still makes progress (it re-prefills);
what must not happen is one line per tick, which is the 449 MB/20 min flood
class. All three new emitters are rate-limited first-3-then-every-200th, the
cadence the stale-release routing in the same file already uses, and the rate
limit is under test.

NOT BUILT, FILED: docs/dev/NOTE_847_tp_host_tier_pool_set.md -- the TP host
view built with the full pool set, which is what would keep the device tier
ARMED across a cutover. It is not two lines: _make_layer_mapper bounds ids by
transfer_layer_num, the TP view reports 16 layers against the boot-time
32/18/14, and copying the boot-time MAMBA entry across yields a mapper that
returns None for every mamba layer -- the same silent skip, moved one level
down and harder to see. The note carries the acceptance it needs.

A NEGATIVE FINDING, recorded because it was the reason this was investigated:
sgl-project#767 ("cache hit = degeneration, cache miss = correct") is NOT this. The
mechanism predicts that symptom exactly, but it can only bite after a
cutover has narrowed the tier, and all three sgl-project#767 boots
(boot_735_acc767 / _full767 / _standing767, 2026-08-19/20) ran with
`phase_flip_rebind_hicache=False` and contain ZERO hicache-rebind lines
against 57/189/105 completed flips -- the flag is printed in their
server_args, so the emitter existed and the absence is a measurement, not a
missing log line. The tier was never narrowed, entry_map always held MAMBA,
and the skip was unreachable. sgl-project#767 was separately root-caused and fixed in
ecef447 / b6cdbed / e80aa43 (mamba checkpoints written against the
bound instead of the computing pool). Adjacent family, different producer.

TESTS
  test_bound_pool_set_coverage_847  17 passed. Hermetic, mocks only.
  Mutation-proven, six mutations, each reverting one change:
    M1  refusal -> continue, post-condition off      6 failed
    M1b refusal -> continue, post-condition left in  1 failed (the early
        refusal is not redundant with its backstop: it must refuse BEFORE
        allocating and rolling back later pools)
    M2  post-condition removed only                  1 failed
    M3  check_pool_coverage not called from rebind   1 failed (wiring; a
        check nobody calls is inert)
    M4  executor raise -> silent skip                2 failed
    M5  release path back to bound-tier-only lookup  1 failed
  Restored: 17 passed.

  mem_cache unit suite:  1757 passed, 1658 skipped, 361 subtests, 2 failed.
  managers unit battery: 4326 passed, 18 skipped, 356 subtests, 15 failed.

  All 17 failures are PRE-EXISTING and MEASURED as such, not assumed: the
  four changed files were reverted to the branch tip (25e7849) and the
  same test files re-run, reproducing the identical 15 + 2 by name and by
  reason. All are environmental for a hermetic (CUDA_VISIBLE_DEVICES="") run
  -- 13x "RuntimeError: No CUDA GPUs are available" and 4x the retry wrapper
  swallowing it -- in test_acceptance_emitters_758 (2),
  test_arena_high_water_631 (7), test_phase_flip_rotation_wiring_809 (4),
  test_restore_never_rebuild_677 (4). Zero new failures.

  black/isort/ruff/codespell clean on the changed files. The formatters'
  unrelated churn was reverted by hand: the installed black is older than the
  one the tree was formatted with, and isort moved a deliberately-late
  `# noqa: E402` import in memory_pool_host.py.

NOT PROVEN HERE: that a mamba load-back after a cutover restores state on
metal. This change makes that case refuse loudly instead of crashing or
answering wrongly; making it WORK is the filed posten.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
…t when Full triggers it

Boot 2f died 40 s in, 14 s after the first real cache hit. Not a wedge -- the
scheduler RAISED at on_idle:

  pool memory leak detected! [full] total=465669, available=132894,
    evictable=346, protected=8192, session_held=0, uncached=0,
    withheld=324357, double_owned=8129, double_owned_src=live

THE DEFECT IS EXCLUSIVITY, NOT ACCOUNTING, and the ledger is only what
noticed. `double_owned_src=live` means the number came from
`_live_double_claimed_rows`, which is `len(free_rows & cached_rows)` over the
allocator's real free set and `all_values_flatten()` -- "the SIZE OF AN
ENUMERATED INTERSECTION, the ids are known, not estimated". So 8129 rows were
genuinely on the free list AND named by live tree nodes. Those ids stay
matchable, which is the sgl-project#767 direction: a later prefix hit can serve KV out of
rows that have already been reissued.

ROOT, one line. `full_component.evict_component` (:115-118) frees the device
rows on ANY cascade that reaches it and deliberately leaves `cd.value` set --
correctly, because `free_swa` has to read it first, so the clear is deferred
to `_cascade_evict`. That deferred tombstone then asked

    trigger.component_type == BASE_COMPONENT_TYPE

which is a DIFFERENT QUESTION from "were Full's rows freed". A cascade
triggered by MAMBA or SWA (`mamba_component.py:529`, `swa_component.py:441`)
that reaches Full freed its rows and never tombstoned them, so the node went
on naming ids the allocator had handed back -- permanently, not for a window.

The fix asks the question the deferral actually owes: `base_rows_freed`, set
when Full is the trigger OR when the cascade loop evicts Full, and the
tombstone fires on that. The opposite direction is preserved and pinned: a
cascade that never reaches Full must NOT clear `value`, because stranding live
KV is a deficit -- the worse defect in the other sign.

SIBLING SWEEP, and the class is a single instance: `mamba_component.py:484`
and `swa_component.py:393` both clear `cd.value = None` INLINE, immediately
after freeing. Only Full defers, only Full needed a completion condition, and
only Full got it wrong. Nothing else to fix.

WHY NOW, AND WHY IT IS OLD (#wurzel-vor-wirkung): the intersection can only be
as large as the tree. Until the mamba checkpoint grid stopped vetoing every
anchor, no prefix match ever succeeded -- the tree stayed at `evictable=1` and
this term measured about ONE row, which is exactly the 2c precedent that
motivated sgl-project#912's live reading. The first real 8538-row cached prefix turned it
into 8129. The defect is not in a516b37's diff; a516b37 only made hits
reachable.

THE ARITHMETIC, since it names the sign: PP0's raw ledger is
132894+346+8192+324357 = 465789, a 120-row SURPLUS over 465669. Subtracting
double_owned=8129 makes it an 8009-row DEFICIT, and `_check_pool_invariant`
raises on `!=`, so either sign is fatal. The two peer ranks sit at a 64-row
surplus with double_owned=0; the 56-row difference is exactly PP0's extra free
rows. All three trees hold the same 8538 rows (8192+346 on PP0) -- only the
lock and the free-list overlap differ, which is why the rank that matched is
the rank that died.

RELATIONSHIP TO THE NEIGHBOURS, checked rather than assumed: sgl-project#916 (lawful
tree/request share) and sgl-project#922 (stale _resident_rows) are different populations
and are untouched. sgl-project#912 is the DETECTOR, and it worked exactly as designed --
it was built to catch a row claimed by two owners and it caught one. This is
not an indicator defect; the indicator was right.

Tests, hermetic, CUDA_VISIBLE_DEVICES="": test_cascade_tombstone_927.py,
5 passed. Red-first proven: restoring the old trigger-gated condition turns
`test_the_tombstone_is_not_gated_on_who_triggered` RED, then reverted.

SPECIMEN 2 ARRIVED MID-BUILD AND CHANGED THE VERDICT. The targeted repro
(boot_2f_a516b3750b_0827_0649.log) reproduced it with double_owned=8192 -- the
WHOLE hit prefix, so the first specimen's 63-row gap was incidental, not a
discriminator. And its ledger BALANCES EXACTLY:

  available 125865 + protected 8192 + evictable 1111 = 135168
    = the post-cutover free pool ("POOL CENSUS post-cutover ... free=135168")
  135168 + withheld 305265 = 440433 = total          -> surplus ZERO

So on that run there is no leak and nothing to correct: the raise is caused
ENTIRELY by subtracting 8192 from an exact ledger. That means the two free
readings disagree by exactly the protected count -- `double_owned` is derived
from `free_reading.rows` (an ENUMERATION) and subtracted from a ledger built
on `available_size()` (a COUNT), and `FreeRowReading`'s own docstring warns
that "HOW MANY" and "WHICH ONES" are different questions on this allocator
family. Nothing compared them.

SO THIS COMMIT DOES NOT CLAIM TO CLOSE 2f, and says so rather than letting the
tombstone fix take credit for a crash it may not cause. The second change is a
DIAGNOSTIC, not a gate: when the live reading fires, it now logs the
enumeration size against the count and the delta. Whether the enumeration
over-reports or `available_size()` under-reports decides which side is the
defect, and the fix differs on each side -- so it names the disagreement and
leaves the verdict to the reader instead of guessing.

The tombstone fix stands on its own merits, independent of 2f: a live node
naming freed rows is wrong whatever the ledger says about it, and the sibling
parity argument (both peers clear inline) is what proves it rather than the
specimen.

OBSERVABLES for the next boot: the new "sgl-project#927 FREE READING DISAGREES WITH
ITSELF" line and its delta -- if it prints delta == protected, the enumeration
is the defect and the correction term must be built from the count; if it does
not print at all while double_owned is still large, the rows really are doubly
claimed and the tombstone path is the one to keep pulling.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
…h setters

WHAT THE FIELD MEANS, stated once because two sites were deriving it and only
one of them was right: `cache_protected_len` is HOW MANY LEADING ROWS OF THIS
REQUEST'S KV THE TREE OWNS. It is not a length of anything the request owns.
Two consumers depend on exactly that reading -- `_insert_helper`'s duplicate
free (`dup_start = max(0, prev_prefix_len - total_prefix_length)`) and sgl-project#824's
`retention_shrinks_protected` -- and both are unsafe if it under-reports.

THE HAZARD, REPRODUCED BEHAVIOURALLY rather than argued. On a prefix HIT
`req.prefix_indices` ARE the tree's row ids; the request reuses them, it does
not copy them. So in the prefix region `_insert_helper`'s `value_slice` holds
the TREE's ids, and `prev_prefix_len` is the only thing standing between them
and `token_to_kv_pool_allocator.free`. With `prev_prefix_len=0` and a full
prefix hit, every row of the prefix ends up in the free list AND in the tree at
once -- counted, ids compared, not read off the source. That set is precisely
the `double_owned` population (`free_rows & cached_rows`) the on-idle ledger
reports as `src=live`.

THE ROOT: the two setters guessed differently, because neither was told.
`MatchResult.cache_protected_len` defaults to None and `UnifiedRadixCache`
never populates it, so on this rig the field's value depended on which site
touched the request last:

  * `Req.init_next_round_input` (schedule_batch.py:1351-1354) -- has an `else`
    and falls back to `len(self.prefix_indices)`. CORRECT.
  * `match_prefix_for_req` (schedule_policy.py:148-149) -- had NO else, so the
    branch never fired and the field kept its previous value, which is 0 for a
    fresh Req (schedule_batch.py:1677). Meanwhile the same function assigns
    `req.prefix_indices = match_result.device_indices` UNCONDITIONALLY. A
    request could therefore carry the tree's rows while claiming none of them
    were tree-owned.
  * `UnifiedRadixCache.cache_unfinished_req` (:1261) -- `len(new_indices)`.
    CORRECT.

The sibling is given the same fallback here, so the two cannot diverge again.
Both callers pass `include_req=True` over the WAITING queue, so the value can
only be (re)derived for requests that are not yet in flight -- it cannot
unprotect anything mid-prefill.

AND THE VALUE THE LIVE LOG SHOWS IS RIGHT, WHICH MATTERS MORE THAN THE FIX.
2g-1 reads `cache_protected_len 8192` with a mamba `tracked position 4096`, and
sgl-project#824 declines the anchor. That decline is CORRECT and the 8192 is not a
symptom:

  * with `--chunked-prefill-size 4096` and a ~9447-token prompt,
    `cache_unfinished_req` publishes the protected length at each chunk
    boundary -- 4096, then 8192, then 9447. At the chunk-2 boundary the tree
    genuinely owns 8192 leading rows, so 8192 IS the true value at that
    instant.
  * `tracked position 4096` is a DIFFERENT AXIS: it is mamba's `cache_len`
    after the ReplaySSM `write_pos` subtraction, i.e. the last FLUSH boundary
    of the recurrent state. The mamba state lags the KV by a chunk.
  * so sgl-project#824 is refusing to file a state captured at 4096 under a key of 8192,
    which is the sgl-project#767 pairing direction exactly. Refusing is right.

THE WARNING THAT FOLLOWS, for whoever owns the anker/decline chain: do NOT
"fix" the decline by lowering `cache_protected_len` to meet the tracked
position. That would re-open the duplicate-free hazard above AND pair a
recurrent state with a depth it was not captured at -- both directions of the
same corruption at once. The number is right; the lag is the defect.

Tests, hermetic, CUDA_VISIBLE_DEVICES="": test_insert_dup_free_927.py,
3 passed. Combined mem_cache+managers lane: 17 failed / 7473 passed, and all
17 are NAME-IDENTICAL at f1a3391 (arena_high_water_631 x7,
restore_never_rebuild_677 x4, phase_flip_rotation_wiring_809 x4,
acceptance_emitters_758 RefillTiming x2) -- zero new failures. Genuinely red-first this time, and checked with the mutant shape that
defeated the last suite: reverting the `else` turns
`test_match_prefix_for_req_states_the_protected_len` RED while the other two
stay green, then restored. The hazard case is a CHARACTERISATION (it asserts
the tree's rows ARE freed at prev_prefix_len=0) rather than a red-first pin,
and is labelled as such.

THE RE-ADMIT PATH, TRACED, because the observed crashes all run through it
(PP prefill -> retract at the cutover -> re-admission in TP as a full prefix
hit, `ADMIT prefix_lens=9447 phase=tp #cached-token: 9447`):

  * the hazard condition IS created there. `Req.reset_for_retract`
    (schedule_batch.py:1611) sets `prefix_indices = empty`, `last_node = None`
    and `cache_protected_len = 0`, and the request is requeued at the front of
    the waiting queue. A request that then takes a FULL prefix hit is exactly
    `prev_prefix_len=0` + full hit -- this file's characterisation case.
  * but it is CLOSED again before the insert. `get_new_batch_prefill` calls
    `req.init_next_round_input(self.tree_cache)` (scheduler.py:8723) on every
    admitted request, and that is the sibling that HAS the `len(prefix_indices)`
    fallback. So the value reaching `_insert_helper` on the observed path was
    already correct, and the crash is NOT this hazard firing.
  * SO sgl-project#927 IS NOT CLOSED BY THIS COMMIT. What this closes is the window where
    `match_prefix_for_req` is the last setter -- real, but not the observed
    instance. Said plainly so the ticket is not marked done on it.

ONE ADJACENT GAP FOUND WHILE TRACING, recorded rather than fixed blind: under
`pp_size > 1`, `scheduler.py:8749-8773` truncates `req.prefix_indices` to the
PP-agreed `told` (sgl-project#791 admission uniformity) and does NOT update
`req.cache_protected_len` with it -- zero mentions of the field in that block.
After `init_next_round_input` set them equal, the truncation leaves
`cache_protected_len > len(prefix_indices)`. That direction is SAFE for the
duplicate free (a larger `dup_start` frees less), which is why it has not shown
up as a double-claim; it is the direction that feeds
`assert req.cache_protected_len <= len(new_indices) + page_size - 1`
(unified_radix_cache.py:1231). Not touched here because the safe direction does
not warrant a blind edit on the admission path, and because it wants its own
red-first.

NOT CLAIMED: that this closes the 2f/2g crash. The live value is already
correct via the sibling that had the fallback, so this closes a WINDOW -- the
path where `match_prefix_for_req` is the last setter -- not necessarily the
observed instance. What it does settle is the reachability question and the
meaning of the field, and it removes the disagreement so the next reader is not
choosing between two answers.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
…not by who computes now

THE GARBAGE. Boot 2g and the 2g-2 length ladder: under strict phase purity
every prompt -- 718 tokens as much as 9447, one prefill chunk as much as three
-- answered with text unrelated to the prompt, and a second send of the SAME
prompt at temperature 0 answered differently again. One send emitted a single
EOS. No chunk boundary is needed, so the chunked-prefill handoff is not it.

THE ASYMMETRY, IN TWO LINES. The WRITE side resolves by phase:
mamba_component.py:916 donates through active_mamba_state_pool
(mamba_state_pool.py:32-35, via phase_active_mamba_pool), so the anchor's
conv/ssm bytes are placed in the pool of the phase computing AT DONATE TIME.
The READ side does not: model_runner.py:4368-4373 copies out of
pool.mamba_pool with pool = self.req_to_token_pool (:4317), unconditionally,
and model_runner.py contains no occurrence of the phase-aware accessor at all.
Across a flip the writer and the reader resolve to DIFFERENT pool objects
(gdn_flip_mover.py:848-851 names both).

WHY EVERY REQUEST. Strict purity prefills in PP, retracts the request at the
pp_to_tp cutover and re-admits it in TP against its own just-cached prefix
(boot_2f_698cd396ce_0827_0704.log:3805/3808, :4672/:4673 -- "ADMIT
prefix_lens=9447" then "phase=tp, #new-token: 1, #cached-token: 9447"). The
decode's recurrent state therefore comes from the radix anchor, and the anchor
is a bare slot id. Nothing moves the bytes at the cutover either: gdn_flip_mover
moves RESIDENT slots and the log reads "0 live slots, sent 0 cells / 0.00 MiB".
So the resume read slot N of the TP pool while the state sat at slot N of the
PP pool, and slot N of the TP pool holds whatever the TP stack last left there
-- three identical sends, three different answers.

This is sgl-project#767's unfixed half, and the fix says so: install_phase_aware_mamba_
state_pool scopes itself in its own docstring to "only the byte copies
(checkpoint donation copy, int8 store)". All six call sites of
active_mamba_state_pool are donate/store. Not one is a resume.
mamba_state_pool.py's header records the same failure from the write side,
measured 2026-08-19: "a kite prompt answered with a foreign river essay".

THE FIX. active_mamba_state_pool answers "who computes NOW"; at a TP resume
that is TP while the anchor sits in PP, so the accessor alone cannot serve the
read side. It needs PROVENANCE. mamba_state_pool.py gains a bounded ledger
(one entry per mamba slot, overwritten on every insert, so a recycled slot
cannot be vouched for by its previous tenant) plus anchor_bytes_reachable /
anchor_provenance_verdict. Single-pool boots answer True unconditionally and
are bit-for-bit unchanged; on a split boot an anchor nothing recorded answers
False, the conservative direction -- refusing costs a re-prefill, trusting
costs the wrong answer.

RECORDED AT THE TREE INSERT, NOT IN A DONATE BRANCH. This rig runs
mamba_radix_cache_strategy='no_buffer', so enable_mamba_extra_buffer is False
(server_args.py:19472-19476) and the ping-pong branch is never entered; the
live branch is the plain one at :901-918. There are four donate branches and
they disagree about whether they copy at all, so teaching provenance to one
would have been inert on a rig running another -- the enablement-gap class.
commit_insert_component_data is the single place an anchor becomes a node's
value, so the hook is there and covers every branch by construction.

REFUSAL, NOT A SILENT READ, at finalize_match_result -- two arms, both
previously silent:
 (a) mamba_value is None with no host copy. The `if` had no else, so the
     request kept mamba_needs_clear True (memory_pool.py:2090), ZEROED its
     recurrent state, and reused the full KV prefix anyway.
 (b) the anchor's bytes belong to the other phase's pool.
Both zero the match and keep branching_seqlen, as the strict-resume zeroing
already does. The rule is quoted from thirty lines below, where the same
function already applies it to slot starvation: "Reusing the KV prefix without
the matching mamba state would be silently wrong, so the whole match is zeroed."

WHY REFUSE RATHER THAN FETCH: the PP pool is layer-axis sharded and the TP pool
head-axis sharded. Translating is what gdn_flip_mover does, on a plan and a
collective; a per-request copy at match time cannot.

THE COST, NAMED RATHER THAN DISCOVERED ON METAL. Refusing sends the request
back to a full prefill, which under strict purity runs in PP, donates a fresh
PP-pool anchor, and meets the same verdict at the next re-admission. A request
that is RETRACTED instead of carried across the cutover can therefore refuse
forever, two cutovers a lap. The loop is not created here -- it is the hole the
wrong answer was hiding -- and the way out is the resident carry of the mamba
state across pp_to_tp, not a softer refusal. A SECOND refusal of the same
request logs that by name at ERROR instead of looping in silence.

SIBLINGS, SAME MOVE:
 * second lineage (sgl-project#747's rule): mamba_radix_cache.py records at both insert
   sites and refuses at its resume, same shape.
 * int8 checkpoint pool, the same defect in the opposite direction
   (_commit_int8_checkpoint writes the TREE-BOUND pool, model_runner.py:4361
   reads the EXECUTING runner's). Inert today only because mamba_ckpt_size is
   unset, which is a boot flag away from the same wrong answer, so
   install_phase_aware_mamba_state_pool announces the mismatch at boot -- the
   only place both objects are in scope.
 * model_runner.py:4354 clear_slots writes the computing stack's own slot and
   is correct as it stands.

BOOT INSTRUMENT, one grep. The match seam logs the pool that WROTE the anchor
("[sgl-project#928 anchor] ... anchor_pool=0x..") and model_runner.py logs the pool that
READS it ("[sgl-project#928 cow] ... state=0x.."). One boot puts the two ids side by side;
no tensor is touched and no D2H sync is added on that line.

TEST RESULTS (desk, CUDA_VISIBLE_DEVICES="", /spinning/htsglang-gpu/.venv):
 * test_anchor_bytes_follow_provenance_928.py -- 6 passed. Six arms: the
   defect; same-phase resume NOT refused (a fix that refuses everything is an
   outage); single-pool boots never refused; unrecorded anchor refused; a
   recycled slot not vouched for by its previous tenant; and provenance
   recorded by the tree insert rather than a donate branch (the no_buffer
   enablement guard).
 * MUTATION, both danger directions and the hook itself:
     A  anchor_bytes_reachable -> always True (the pre-fix silence)  3 failed
     B  anchor_bytes_reachable -> always False (over-refusal)        3 failed
     C  insert drops note_anchor_bytes                              1 failed
   restored: 6 passed.
 * REGRESSION: test/registered/unit/mem_cache/ plus every flip/gdn/phase test
   in managers/ -- 3580 passed, 927 skipped, 616 subtests passed, 6 failed.
   All six re-run on the parent 290fea9 and fail there identically:
   2x test_acceptance_emitters_758 "No CUDA GPUs are available" (desk has no
   GPU) and 4x test_phase_flip_rotation_wiring_809 "retry() exceed maximum
   number of retries". Pre-existing, not this change.
 * ruff clean on every file this touches; the 5 remaining in model_runner.py
   and 21 in mamba_radix_cache.py are byte-identical on the parent.

STILL OPEN, and it is the capacity half: cached anchors are not carried across
the cutover the way resident slots are. Until they are, a strict-purity resume
gives up its hit instead of giving a wrong answer.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
…he pin's door is on the prefill path

CHECKED BEFORE BUILDING, as ordered, and the check changed the answer.
NOTE_888b §5 recorded "pin release ABSENT" for the mamba anchor pin, taking
NOTE_773's deferral at its word. That was wrong in the safe direction, and my
own sgl-project#902 row inherited it verbatim.

WHAT IS ACTUALLY ON THIS BASE. sgl-project#755's reorder release EXISTS:
`UnifiedRadixCache._mamba_anchor_early_release` (:1022), guarded by
`MambaComponent.anchor_release_admissible` (:564) -- which requires the host
copy to have LANDED (`host_value` present AND the node absent from
`ongoing_write_through`), not merely to have been intended. That guard is
precisely the dead-anchor case sgl-project#767 documents, and it is already built.

WHAT IS NOT. Its ONLY call site is `cache_unfinished_req` (:1173), which runs
while prefill batches are built. So the door lives on the PREFILL path, and
finish releases the pin with everything else the request holds. Under strict
purity the TP window forbids prefill and the seam RETRACTS rather than
finishes -- so in the TP layout no door opens at all.

sgl-project#811 IS THE LAYOUT-INDEPENDENT DOOR AND IS NOT HERE. `[sgl-project#811] Release the mamba
admission anchor pin at the write-through ack`, 14606c6 on
`fix/811-admission-pin-ack-release`, cut from integ/round7 @ a2a47b4. That
parent IS in this base's ancestry; the sgl-project#811 commit is NOT, and its metal proof
is still the open W-811 window ticket. So the honest outcome is neither "just
declare it reachable" nor a duplicate build: the row is corrected to the doors
that exist, and the finding SHARPENS from "no door" to "no door THIS layout
can open".

`gated_by`, AND THE CHECK READS IT. The prefill door sits behind
`mamba_slot_reorder_active` -- three conditions, any of which turns it off. A
door behind an unarmed flag is SHUT, so the condition is a field rather than a
sentence, and `release_path_conformance` emits a third verdict, CONDITIONAL,
naming the gate. Adding a field the check ignored would have been the exact
defect this file exists to prevent, one commit after I wrote that down.

FINDINGS NOW, both true and neither new work:
  pp:  CONDITIONAL mamba_anchor_pin -- prefill door, only while the reorder
       flag is armed
       UNREACHABLE kvso_host_region
  tp:  UNREACHABLE mamba_anchor_pin -- strict purity forbids its only path
       UNREACHABLE kvso_host_region

TEST RESULTS (desk, CUDA_VISIBLE_DEVICES=""):
 * test_release_path_declarations_902.py -- 8 passed. The pin arm now asserts
   the CORRECTED truth in both layouts (conditional in pp, unreachable in tp)
   rather than the inherited "undeclared", and every declared symbol still
   resolves.
 * REGRESSION: participants / 859 / 773 / 755 suites plus this one -- 61
   passed, 0 failed.
 * ruff clean on both touched files.

STILL OPEN, and it is the next slice: kvso_host_region. Unchanged by this
commit -- finish/abort only, no layout reaches it.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
…ke the verdict an observation

WINDOW-946FIX-0828 MEASURED A COMPENSATOR THAT WAS, FOR THE FIRST TIME IN THIS
FAMILY, PROVABLY ON THE DEFECT'S PATH AND STILL DID NOTHING. The sgl-project#946 escape
fired 8885 times (act_rid_hit) while PREFETCH RE-ISSUED stayed 0, cached>0
stayed 0, and the rid stayed frozen at told=8192. Root: `_prefetch_kvcache`
returned None on every one of its paths and the escape read that as success --
`prefetch(req); return "refetch"`.

ITS SUCCESS VALUE WAS NOT EVIDENCE THAT IT ACTED. Five earlier instances were
compensators placed off the path the failure takes; this one is a compensator
whose own report cannot distinguish acting from not acting.

SAME CLASS, NAMED SIBLINGS: sgl-project#872 (silent falsy paths), sgl-project#501 (the contract
promises what the code does not deliver), sgl-project#685 ("a silent precondition is
indistinguishable from dead code"), sgl-project#656/HANDOFF_678 4.0 (four early ABSTAIN
returns above the trace), sgl-project#767 (name the eaten branch).

THE VERDICT IS AN OBSERVATION, NOT A PROMISE. There are SIX silent exits
between the escape and registration -- two in `_prefetch_kvcache`, four inside
`prefetch_from_storage`. Enumerating them one at a time is how this family has
failed five times: a seventh added later would be silent again. So the verdict
is taken from the EFFECT -- did the operation appear in `ongoing_prefetch`
(unified_radix_cache.py:2996)? -- which covers every exit at once, including
ones nobody has written yet. Deep reasons come from the sgl-project#915 gate counters as a
per-call DELTA (anchor / too_short / rate_limited).

CONSEQUENCE, and it is where the old code leaked: the mark was cleared BEFORE
the attempt, so a DECLINED re-fetch spent it and the request never saw the
escape again -- invisible while every decline reported success. Now an OUTCOME
spends the mark, an attempt does not: issued clears it, a decline keeps it and
retries, bounded by REFETCH_DECLINE_CAP=3, then the terminator. Kein-Doppel-
Prefill unchanged: re-fetch preferred, told=0 the bounded last resort that
still names its discard.

sgl-project#915 WIRED AT LAST. `note_prefetch_gate` has recorded the decline reason on
every attempt since sgl-project#915 landed; `format_prefetch_gate` had ZERO callers, so it
was never reported -- PRESENT-BUT-UNWIRED for twelve days, printed by every boot
script and read as a note. Now logged on the census cadence.

CANDIDATE (iii) REFUTED BY MEASUREMENT, not by argument. The suspicion was the
sgl-project#915 host-tier capacity asymmetry (prefetch_capacity_limit = 0.5 *
mem_pool_host.size, cache_controller.py:841 -- NOT :729, a stale pointer in
sgl-project#915's own comment). The gate line is byte-identical across both stages of the
window (attempted=6, anchor/too_short/rate_limited ABSENT), so the escape never
reaches the gate at all: it returns at the ANCHOR exit above it. The escape's
precondition (`last_host_node.backuped`) is anti-correlated with the situation
the escape exists for.

TESTS, each module alone in a fresh process, 33-module blast radius derived from
the touched symbols, identical script both sides vs the 707f234 baseline:
  BEFORE  1017-11 = 1006 passed, 9 failed
  AFTER   1017 passed, 9 failed
Exactly ONE module differs: test_chunked_continuation_clamp_946.py 28 -> 39
(+11 new arms). Every other module matches its baseline EXACTLY, including
test_unified_radix_cache_unittest.py (642 passed / 860 skipped / 44 subtests,
both sides). The 9 failures are PRE-EXISTING at the pin and identical on both
sides: test_prefetch_progress_symmetry_580.py (7) and
test_collective_family_siblings_610.py (2). Extraction count probe: 9 == 9.

CAN-FAIL PROVEN IN BOTH DIRECTIONS, not asserted: a mutant returning "issued"
unconditionally is caught by the delivery arm; restoring the old consume-
before-attempt is caught by the mark arms. Four contract inversions recorded at
their sites -- stubs that returned None used to read as successful re-fetches,
which is the defect itself encoded as a test.

ruff (F401,F821,UP037) and ruff format clean. The two codespell hits in
scheduler.py are pre-existing at the pin.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 28, 2026
…d acquired

Boot 10 (b27d7c2) died on PP0 at 19:58:17 with
`AttributeError: 'NoneType' object has no attribute 'unsqueeze'` at
mem_cache/unified_cache_components/mamba_component.py:1056, reached via
_pp_process_batch_result -> process_batch_result_prefill ->
maybe_cache_unfinished_req -> cache_unfinished_req, rid
e3d6a9ff11c5460cb115f266f2b187a3.

ROOT (class, not effect). The admission loop's revert site in
managers/scheduler.py frees `req.mamba_pool_idx` whenever a request is not
added to `can_run_list`, guarded by `not req.session`. That predicate is
upstream's PROXY for "nobody else already owned this slot" -- correct
upstream, where a session was the only carrier of a pre-existing slot. This
fork invalidated it: sgl-project#984 (void-park), #968b (rehome-on-displace) and sgl-project#971
(rehome-on-refusal) re-queue requests UNRESET, holding the live mamba slot
of a prefill batch that is still IN FLIGHT. The revert then hands a live
owner's slot back to the allocator and nulls the field; the in-flight
batch's result arrives and dereferences it.

The silent direction is the same defect: when the free lands outside the
in-flight window, HybridReqToTokenPool.alloc re-acquires a fresh slot with
mamba_needs_clear=True -- a ZEROED recurrent state in place of the
request's own (sgl-project#767's shape), with no crash and no log line. Both close at
the provenance test.

FIX, at the one junction. Stamp provenance where the slot is acquired
speculatively by an admission round's prefix match --
unified_cache_components/mamba_component.py (COW resume + host load-back),
mamba_radix_cache.py, hi_mamba_radix_cache.py (both siblings) -- and free
at the revert site only when that stamp is set. The stamp is cleared the
moment HybridReqToTokenPool.alloc takes the slot into a batch, and on every
release/reset path (free_mamba_cache, _rollback_alloc, release_kv_cache's
early branch, reset_for_retract, Req.__init__ default). This is sgl-project#984's own
"pages versus claim" doctrine applied to the third increment: the lock ref
(sgl-project#990) and the chunk (sgl-project#971) already carry provenance; the mamba slot was
the one that did not. It opens neither sgl-project#929 (deficit) nor sgl-project#924 (surplus) --
the stamp is one-shot and dies with the slot.

AFFIRMATIVE REPORTING. None of the five mamba free sites named a rid, which
is why the specimen could only be reached by elimination. The refused
give-back now logs rid + rejection result, so the next boot is the metal
proof of the root rather than a yes/no on the crash.

BACKSTOP, named as a defect. mamba_component.prepare_for_caching_req now
declines retention with a counted, rid-bearing warning instead of
dereferencing a None slot. This is NOT the fix and is stated as such in
place: it costs the step's retention and re-prefills the chunk, which the
standing no-double-prefill order forbids as a routine. It exists because a
crash here takes the whole instance while a decline takes one step.

SIBLING SWEEP: all five writers of `mamba_pool_idx = None` audited and the
stamp cleared at each. gdn_slot_runtime.py:136 is not wired on this build
(the gdn_resident_state_slots gate is off, no "armed" line in any boot log)
and is left untouched. streaming_session.py's clears stay covered by the
retained `not req.session` term.
FUTURE CHECK: a new producer of a pre-existing slot cannot reopen this
silently -- it either stamps at its acquire (and is given back correctly)
or it does not (and is kept), and the backstop's counter names it with a
rid if it manages to drop one anyway.

Evidence: desk. py_compile + import smoke on all seven touched files;
lifecycle probe (Req default False, reset_for_retract clears). Belegstufe:
DESK-BEWIESEN, not metal -- boot 11 is the test.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 24, 2026
… einen Slot (fnFL2 H19)

fnFL2x130 (Chunk 512, 97841 Token = 191 Chunk-Knoten, MAMBA_ARENA_SLOTS 32):
P schreibt je Chunk einen Mamba-Anker in die Host-Arena. Jeder gelandete
Schreibvorgang nimmt je P-Rang eine Leserreferenz (complete_write), die der
Knoten haelt, solange er seinen Host-Wert hat; waehrend des Prefills gibt
nichts sie frei (Arena-Zeilen liegen ausserhalb der Host-Pool-Groesse, der
Host-LRU laeuft nie). Ab dem 31. Anker antwortet arena_claim 4, der
Clock-Evictor ueberspringt jeden Slot (refcount != 0), _weg2_direct_claim
verweigert den Knoten ganz (KV-Claim mit) und der Sweep stoppt
(stopped: mamba_full, xsn342). Die Arena hielt die ERSTEN 30 Anker
(Seiten 0..239), der Endanker (97792) wurde zehnmal verweigert, D kappte
bei Seite 240 (#1028B FETCH CAP caps={mamba: 240}), W50, zweiter Prefill.

Die Vorgaenger deckten das nicht ab: protect_deepest_anchors (sgl-project#767) schuetzt
Anker nur im Device-Pool der alten MambaRadixCache-Linie und ist mit
Host-Tier ausdruecklich aus; sgl-project#1481 haelt den Device-Zustand des Endankers,
bis er gesichert ist -- es besorgt ihm keinen Arena-Slot; der
RETAIN-PUBLISH (e13d3c9) publiziert eltern-zuerst und bricht seit
ce59ad3 an der ersten mamba_full-Verweigerung ab, erreicht den Endanker
also nie.

Neu (weg2/mamba_arena_displace.py, Haken in _weg2_direct_claim):
* ANTEIL: eine Anfrage (rid, am Knoten beim Chunk-/Retain-Publish
  vermerkt) haelt je Rang hoechstens `cap` Arena-Anker. Vor ihrem naechsten,
  tieferen Anker gibt der Rang die Referenz auf ihren FLACHSTEN gesicherten
  Anker frei (Mamba-Host-Wert des Knotens, wie der Host-LRU es taete; KV
  bleibt); der Slot wird gedroppt, sobald kein Rang ihn mehr referenziert
  (arena.c arena_drop_unreferenced, kein Plattenschreiben). Der Ausloeser
  ist eine Zaehlung entlang der eigenen Kette, auf allen PP-Raengen gleich --
  ein reiner "Arena voll"-Ausloeser konvergiert nicht, weil ein Slot erst
  frei wird, wenn der LETZTE der drei Raenge freigegeben hat.
* VOLL: verweigert die Arena trotzdem, gibt der Knoten einmal je Rang einen
  weiteren eigenen Anker frei; hat die Anfrage keinen eigenen abzugeben
  (erster Anker, Endanker hinter voller Arena), nimmt sie den flachsten
  ZWISCHEN-Anker einer anderen Anfrage -- nie einen Endanker, nie den
  tiefsten einer Anfrage, nie einen unmarkierten Knoten.
* Logzeilen: 'WEG2 MAMBA-ARENA rid=.. written= displaced=(share,full)
  dropped= refused= held= deepest= end_anchor=slot|missing|refused cap=
  slots= at=retain' je fertiger Anfrage, dieselbe Zeile beim Claim eines
  markierten Endankers, 'WEG2 MAMBA-ARENA DISPLACE' (gedrosselt, fremde
  Verdraengung immer).
* SGLANG_WEG2_MAMBA_ARENA_RID_ANCHORS: -1 (Default) = max(2, slots // 4)
  (32 -> 8; Chunk 16384 mit 6-7 Ankern je 98k-Anfrage bleibt unberuehrt),
  N >= 2 = N, 0 = aus (first-come wie bisher).

Tests: test_weg2_mamba_arena_displace_h19 (9, echte Arena, drei Rang-Pools,
echte Knoten; x130-Form mit Schalter 0 reproduziert den Verlust des
Endankers, mit Default landet er COMPLETE auf allen drei Raengen, je Rang
bleiben die 8 tiefsten, ctrl/mid unberuehrt; Chunk 16384 identisch;
fremde Anfragen unangetastet; Endanker nimmt fremden Zwischenanker) gruen.
Arena-/Mamba-/Retain-Suiten (64 Dateien): 228 Fehler vorbestehend und
identisch zu 549ce38 (Stream.query/retry auf CPU), 0 neu. Gate-Liste
144 passed.
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.

1 participant