Skip to content

Fix prompt len in parallel sampling - #928

Merged
Ying1123 merged 2 commits into
sgl-project:mainfrom
yichuan-w:fix_promptlen
Aug 5, 2024
Merged

Ying1123 merged 2 commits into
sgl-project:mainfrom
yichuan-w:fix_promptlen

Conversation

@yichuan-w

Copy link
Copy Markdown
Contributor

Thank you for your contribution, we really appreciate it. The following instructions will help improve your pull request and make it easier to receive feedback. If there are any items you don't understand, don't worry. Just submit the pull request and ask the maintainers for help.

Motivation

Fix prompt len in parallel sampling

Modification

openai Adapter and resolve one fixme in test openai API

Checklist

  1. Ensure pre-commit pre-commit run --all-files or other linting tools are used to fix potential lint issues.
  2. Confirm that modifications are covered by complete unit tests. If not, please add more unit tests for correctness.
  3. Modify documentation as needed, such as docstrings or example tutorials.

@yichuan-w
yichuan-w requested review from Ying1123 and merrymercy and removed request for Ying1123 August 5, 2024 06:22
@Ying1123
Ying1123 enabled auto-merge (squash) August 5, 2024 07:55
@Ying1123
Ying1123 merged commit fd7926e into sgl-project:main Aug 5, 2024
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
JinyanYi pushed a commit to JinyanYi/sglang that referenced this pull request Jul 10, 2026
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
… why sgl-project#929 is not this

Addendum to the record on the same branch; still test-only.

THE INPUT THAT NARROWS IT. The sgl-project#929 analysis reads mamba_exist=True with
len(key) == 0 at the re-admit insert (unified_radix_cache.py:1569/:1668): the
FULL prefix is already in the tree and it DOES carry a mamba value, and the
decode is garbage regardless. "No anchor" is therefore not the explanation --
the anchor exists and is found. What is wrong is what the resume reads out of
it, which is this branch's root: a slot id resolved against the pool of the
phase that is computing, not the pool that holds its bytes.

DEPTH IS NOT THE OPEN TERM EITHER. The donate pairs key and state at one
position by construction (cache_len = req.mamba_last_track_seqlen,
mamba_component.py:721; mamba_ckpt_utils' "Never floor" states why it may not
be corrected after the fact). Provenance is the term nothing holds.

sgl-project#929 IS A DIFFERENT BOOKING, and the counter-check is cheap enough to state
rather than schedule. On the plain-finished path with mamba_exist=True the
freshly allocated donate slot (mamba_component.py:902-903) is dropped without a
free: cleanup_after_caching_req's enable_mamba_extra_buffer branch (:947-956)
frees only req's own slots, and the insert_params.mamba_value free exists only
on the int8 branch (:942-943) and the unfinished branch (:961-963). It leaks
BECAUSE it was never attached to a node -- and the resume's COW source is
last_node.component_data[ct].value, a slot the tree HOLDS. Orphaned-unreachable
and tree-held are disjoint, so no resume can read the orphan. The rank-0 +1
mamba slot divergence is sgl-project#929's insert-side booking, not a second root here,
and it is struck from this trace.

TEST RESULT (desk, CUDA_VISIBLE_DEVICES=""): unchanged, 1 failed as intended --
"AssertionError: <mamba pool tp> is not <mamba pool pp-primary>".
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
…layer ids, or refuse

sgl-project#706 slice 2 (a38f39f, 2026-08-17) built the geometry-neutral {hash}.mamba
blob and build_mamba_window to cut it for either phase. It has never once been
built at runtime, on any model, on any boot.

THE HOP. HiCacheController._canonical_mamba_window opened with

    cache_params = getattr(model_config, "mamba2_cache_params", None)
    mamba_layer_ids = list(getattr(cache_params, "layers", None) or [])
    if not mamba_layer_ids:
        return None

and mamba2_cache_params is a property of the CHECKPOINT config
(Qwen3NextConfig, configs/qwen3_next.py:288, layers=self.linear_layer_ids),
never of sglang's ModelConfig: `grep -c mamba2_cache_params
configs/model_config.py` is 0. The getattr missed on every model, the list was
always empty, and the one silent branch fired every time. The correct hop is
hf_text_config -- the one gdn_flip_mover.py:929 already uses for GDN geometry.

MEASURED, boot 2g (boot_2f_698cd396ce_0827_0704.log). Format explicitly armed
(phase_flip_canonical_kv_page=True, phase_flip_writeback=True, backend 'file',
page_size 1, so the pairing guard at server_args.py:8716 held), and the log
carries "sgl-project#706 canonical KV page active" THREE times -- one per rank -- against
"sgl-project#706 canonical GDN blob active" ZERO times and zero refusals. Exactly the split
_canonical_mamba_window's own docstring calls fatal: "a canonical KV page beside
a phase-local GDN blob delivers ZERO usable prefix ... Silently running KV-only
would look like the feature was on while every cross-phase lookup missed."

THAT IS WHERE sgl-project#928 COMES FROM. KV crossed the flip geometry-neutrally while the
recurrent anchor stayed phase-local; sgl-project#856 then drops the tree at every cutover
trusting the canonical store ("Nothing is carried across"), and read-through
returned a correct KV prefix beside an anchor in the writing phase's layout. The
on-device fallback could not cover it either: the GDN mover runs AFTER the drop
and logged "moved 0 slot(s)" on all ten flips of that boot.

THE FIX IS THE SIBLING LADDER, NOT A SECOND BARE LOOKUP. resolve_attn_layer_ids
was given exactly this treatment on the same day, for the same reason ("RESOLVED,
not guessed" -- it could not tell NOT HYBRID from NOT POPULATED). The linear half
kept a raw getattr aimed at the wrong object. canonical_page_store gains
resolve_linear_layer_ids with the same four rungs: (a) ModelConfig's own list if
a future one populates it; (b) the checkpoint config's own properties through
hf_text_config, linear_layer_ids first and mamba2_cache_params.layers second;
(c) [] ONLY on a positive dense proof; (d) otherwise a NAMED REFUSAL. The
caller's `return None` is now sound rather than a hole: an empty list can only
mean a proven dense model.

BEHAVIOUR CHANGE THE NEXT BOOT WILL SHOW, stated rather than discovered. A
hybrid whose config class exposes neither property now REFUSES the boot instead
of silently running KV-only -- the conversion the caller's docstring demanded
("this must succeed or attach fails"), with the remedy in the error text. And
because the window is now actually built, derive_mamba_blob_spec is reached for
the first time; if this checkpoint's config lacks a GDN field it will say so
loudly. So the first boot on this commit yields either "sgl-project#706 canonical GDN blob
active" three times or a named refusal. Both are results. Neither is silent, and
silence was the defect.

TEST RESULTS (desk, CUDA_VISIBLE_DEVICES="", /spinning/htsglang-gpu/.venv):
 * test_canonical_gdn_blob_attaches_931.py -- 5 passed. Five arms: a
   Qwen3-Next-shaped hybrid resolves its 48 GDN layer ids; the wrapped source
   (mamba2_cache_params.layers) resolves too; a proven-dense model returns []
   (a ladder that refuses everything is an outage); an unresolvable hybrid
   RAISES; and _canonical_mamba_window gets PAST its early return -- the attach
   itself, probed by making the next call raise a sentinel, because a green
   resolver beside a caller still holding its own getattr looks identical from
   outside.
 * MUTATION, one per claim:
     M1 caller reverts to the bare getattr on ModelConfig   1 failed (the attach arm)
     M2 resolver aims at ModelConfig instead of hf_text_config  4 failed
     M3 the (d) refusal degrades back to a silent skip      1 failed (the refusal arm)
   restored: 5 passed.
 * REGRESSION: test/registered/unit/mem_cache/ -- 2822 passed, 927 skipped,
   471 subtests passed, 2 failed. Both are test_acceptance_emitters_758
   "RuntimeError: No CUDA GPUs are available" and fail identically on the
   parent; the desk has no GPU. The sgl-project#706 format suites
   (test_canonical_mamba_blob_706, test_canonical_page_store_706,
   test_mamba_phase_uniform_706, test_mamba_gates_the_hit_706) are inside that
   run and stay green.
 * ruff: canonical_page_store clean; cache_controller 13 errors before and 13
   after, all E402/F541 at lines 16-44 and 1414, none in the edited region.
   (First count of "0" was a broken extraction -- ANSI codes in the concise
   output defeated the per-file grep; recounted verbatim.)

NOT BUILT, AND NAMED RATHER THAN IMPLIED: the end-to-end content proof --
archive a PP-phase anchor through the fence, load it back in the TP phase,
compare against the reference state -- needs live pools and a storage backend
and is not hermetically cheap at the desk. It is a boot-proof item, and the
measurement window's coherence probe drives exactly that path.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
…he allocator per access

sgl-project#927 IS A CHECKER-SIDE DEFECT, AND THE on_idle RAISE WAS A FALSE POSITIVE.
Nothing in the KV pool is repaired here, because the evidence now says nothing
in it was broken: the guard read the wrong object.

THE MECHANISM, and it is constructed rather than inferred.
`SchedulerInvariantChecker` stored `token_to_kv_pool_allocator` as a dataclass
field taken once at construction (`scheduler.init_invariant_checker`). The
phase flip REBINDS that allocator -- `hicache_phase_binding._stamp` sets
`token_to_kv_pool_allocator = incoming.allocator`, and `phase_pools_for` takes
that object from the incoming phase's OWN worker stack (`:341-343`), so it is a
DIFFERENT OBJECT per phase. But `readers_of` names exactly three readers --
scheduler, tree_cache, cache_controller -- and the checker is not one of them.
Its own docstring states the consequence in advance: "a reader this function
forgets is a reader the rebind silently leaves behind." Nothing else refreshed
it either; `vram_dial._refresh_capacity_snapshots` touches only
`max_total_num_tokens`.

So after the first cutover, `cache_controller.load` allocated load-back rows
from the INCOMING allocator (it IS rebound) while the ledger read the BOOT one.
Both address the same id space, so those rows read as FREE to the checker while
the tree legitimately named them, and `_live_double_claimed_rows` reported the
overlap as `double_owned src=live` -- in the magnitude of the loaded-back
prefix, on the rank that matched, at the instant `load_back` filled the nodes'
`value`. Every measured property of the crash, including the timing that
refuted four earlier candidates.

WHY THE TIMING FITS EXACTLY, which is what makes this the answer rather than
another candidate: the tree was refilled long before the hit, by
`_insert_helper_host`, which creates nodes carrying ONLY `host_value` (`:1788`)
-- `value` stays None, and `all_values_flatten` reads `value`. So the nodes were
invisible to the ledger from the cutover until `load_back` populated them. That
is why `double_owned` read 0 on every census and then jumped at the first hit.

THE FIX IS PER-ACCESS RESOLUTION, AND A `readers_of` ENTRY WOULD NOT HAVE
WORKED AT ALL. That was the smaller-looking option and it is unavailable: all
three affected components are `@dataclass(kw_only=True, slots=True,
frozen=True)`, and `_stamp` moves a reader by `setattr`. On a frozen instance
that raises, `rebind` catches it mid-set and escalates to `RebindIncoherent`
("One reader failed mid-way: the set is now split") -- so adding them to the
dict would have converted a silent stale read into a hard flip failure. Per
access is the only shape that works here, and it is also the one the next
component to hold a binding cannot be forgotten out of.
`_allocator()` derives the allocator when it reads, from a callable the
scheduler supplies -- the idiom this class already uses for `get_last_batch` /
`get_running_batch`. Absent getter falls back to the field, so constructions
outside the phase-flip boot are byte-identical.

SIBLING SWEEP, and the class had THREE members, not one. The class is
"construction-time reference to a rebindable object, on a component outside
`readers_of`":
  * `SchedulerInvariantChecker`      (invariant_checker.py:92)   -- FIXED
  * `SchedulerPoolStatsObserver`     (pool_stats_observer.py:144) -- FIXED;
    this one feeds the SAME ledger (`session_held`, the `available` fallback),
    so it was reading the stale pool alongside the checker.
  * `SchedulerDPAttnAdapter`         (dp_attn.py:270)             -- FIXED
All three now resolve per access and are wired from their construction sites.

BOOT PREDICTION, stated so it can be falsified: the three on_idle crashes
should DISAPPEAR with this commit, with nothing in the pool having been
repaired. If they do not, this is not the producer and the reframing above is
wrong.

MANDATORY RE-READ BEFORE ANYONE BUILDS ON THE OLD NUMBERS. If the ledger has
been auditing the boot phase's allocator since the first cutover, then every
post-flip reading it produced is suspect -- sgl-project#913's standing "live rows already
unmapped" lines on every boot, and the sgl-project#912 `withheld`/`available` readings,
included. They must be re-read on the next boot AFTER this fix before any of
them is treated as a measurement. This warning belongs in both task contexts.

ONE REGRESSION OF MY OWN, CAUGHT BY THE GATE AND FIXED IN THE DOUBLE. The
first full run came back 20 failed against 17 known pre-existing, and all three
new ones were `test_kv_page_invariants.py` with
`AttributeError: '_FakeChecker' object has no attribute '_allocator'`. That
double binds `_check_kv_page_invariants` off the real class but carried only
the FIELDS, so once the production method resolved through `self._allocator()`
the double stopped modelling production -- the drift class this tree has been
bitten by before ("the suite's own double had the attribute and not the method,
exactly backwards from production"). Fixed in the DOUBLE, not in production: it
now binds `_allocator` off the real class alongside the method under test.
Swept the siblings -- every other test touching these three classes uses
`_check_pool_invariant`, a @staticmethod with explicit args, so no other double
carries the same risk.

Tests, hermetic, CUDA_VISIBLE_DEVICES="": test_checker_reads_bound_pool_927.py
4 passed; the three sgl-project#927 files together 10 passed; test_kv_page_invariants.py
5 passed. Combined mem_cache+managers gate: 17 failed / 7477 passed, and the
17 are NAME-IDENTICAL to f1a3391's -- zero new failures. ruff: 105 errors at
base and 105 now across the four touched files, none added. Genuinely red-first --
mutating `_allocator` back to the construction reference turns
`test_the_checker_resolves_the_live_allocator` RED while the rest stay green,
then restored. The characterisation test reproduces the crash as arithmetic:
rows allocated from the INCOMING allocator and held by the tree read as N
doubly-claimed against the BOOT allocator and 0 against the bound one.

OWNERSHIP BOUNDARY held: the mamba twin of the same host re-population
(`mamba_exist=True` out of `_insert_helper_host`) is the sgl-project#928 agent's, shared
and not touched here.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
…spec in sgl-project#936

NOT A FIX. This adds one function and calls it from nowhere. It is committed
alone so it cannot be lost in a worktree, and so the successor building sgl-project#936
starts from a written rule rather than from a description of one.

WHAT IT IS. `lower_protected_to(req, new_protected_len)` lowers
`req.cache_protected_len` by `min`, never assigns and never raises it.
`cache_protected_len` means "the tree owns the KV below this" -- the premise
both free-sites in `cache_finished_req` rest on and the one
`retention_shrinks_protected` states in this same module. Raising it would
promise ownership nobody holds; a flat assignment would clobber a HIGHER claim
a later legitimate match had earned. So: min.

WHY IT EXISTS. When the tree does NOT take a request's prefix, the promise is
false for the rows that request still holds, and the two branches that free
FROM `cache_protected_len` while inserting nothing then skip over them:

  * `unified_radix_cache.cache_unfinished_req`, the `effective_cache_len <= 0`
    skip branch -- frees `kv_indices[req.cache_protected_len:]` (:1196) and
    returns (:1212) without inserting and without lowering cpl;
  * `unified_radix_cache.cache_finished_req`, the `is_insert=False` branch
    (:1130-1131) -- identical shape.

The `effective_cache_len <= 0` that opens the first one comes from mamba's
`_decline_retention(is_finished=False)`, which returns 0. That refusal is
measured, not inferred -- boot 2g, in its own words: "mamba retention would
truncate a protected prefix: tracked position 4096 under cache_protected_len
8192, caching without a mamba anchor".

THE RULE sgl-project#936 SHOULD APPLY: if the tree does not take the prefix, there is
nothing left to protect -- cpl falls in the SAME moment to what the tree
actually holds (0 when nothing was inserted), and the free then covers
everything. At the moment of the refusal, never blanket on the request: a
later successful match may legitimately grant a protected prefix again.

EXPECTED TO BE REPLACED. sgl-project#930's `truncate_prefix_to` carries the same
min-never-assign discipline; when it lands, sgl-project#936 should use it and delete this
one. Two helpers for one rule is the shape that lets them drift.

sgl-project#935's guard (fa7dd3b) is the falsifier for that work and stays as it is: it
MEASURES the orphaned interval rather than repairing it, so if it still fires
after sgl-project#936 there is a second source and it names the share.

Desk checks only, as befits an unwired helper: py_compile clean, ruff clean.
No test, because a function with no caller has no behaviour to pin -- the
red-first test belongs with the wiring, and its shape is specified in sgl-project#936
(mamba retention refused + a full cache_protected_len, asserting the interval
is neither inserted nor freed today).
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 27, 2026
…ted_len with it

`cache_protected_len` is HOW MANY LEADING ROWS OF THIS REQUEST'S KV THE TREE
OWNS. `init_next_round_input` sets it equal to `len(prefix_indices)`. The sgl-project#791
admission-uniformity block in `_get_new_batch_prefill_raw` then truncates
`prefix_indices` to the PP-agreed `told` -- on PP0 from the guard's clamped
candidate, downstream from PP0's decision -- and NEITHER branch touched the
protected length. The request was left claiming more tree-owned rows than it
holds.

I FILED THIS AS "THE SAFE DIRECTION" AND THAT WAS THE WRONG HALF. The surplus
IS harmless for `_insert_helper`'s duplicate free -- a larger `dup_start` frees
less -- which is exactly why it never surfaced as a double claim. It is the
DANGEROUS direction for `cache_finished_req`'s truncate branch
(`unified_radix_cache.py:1111-1116`):

    free_start = max(effective_cache_len, req.cache_protected_len)
    free(kv_indices[free_start:])    # starts ABOVE the interval
    ...                              # the insert covers only up to ecl

With `cache_protected_len > effective_cache_len` the rows in
`[effective_cache_len, cache_protected_len)` are neither freed nor inserted and
belong to nobody afterwards. That interval is sgl-project#935's per-request row leak
(36824 rows on the 2i acceptance boot).

SCOPE, kept sharp so the two tickets do not blur. The GAP is the root and is
sgl-project#935's: it must not be able to leak whatever the value is. This closes one of
the two PRODUCERS that make it reachable; the other is the sgl-project#928 refusal
re-prefill. Closing a producer does not close the gap, and closing the gap
makes the producers harmless -- both are owed, and neither substitutes for the
other. Different files, no collision with fix/935-finished-req-gap.

ONE HELPER, TWO SITES, because the two sites are siblings of each other and
drifted identically -- both sliced `prefix_indices` by hand and both forgot the
same field. `Req.truncate_prefix_to(told)` now owns the pair, and the wiring
pin asserts neither branch slices by hand again.

MIN, NEVER ASSIGN: the helper may only LOWER the claim. A request whose
protected length was already below `told` owns exactly that many, and raising
it here would invent protection the tree never granted -- which is the
dangerous direction for the duplicate free, i.e. the defect this commit is
NOT allowed to trade for. Pinned in both directions.

Tests, hermetic, CUDA_VISIBLE_DEVICES="":
test_truncation_keeps_protected_len_930.py, 6 passed. Combined
mem_cache+managers gate: 17 failed / 7483 passed, the 17 NAME-IDENTICAL to
f1a3391's -- zero new failures. Genuinely red-first with
the mutant the ticket names -- restoring "slice the prefix, never touch cpl"
turns 3 red, including the consequence test that computes the abandoned
interval from the real `max(ecl, cpl)` arithmetic, while the may-only-lower
direction stays green. Restored after.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 1, 2026
…d a pp_to_tp/tp_to_pp livelock, 0 decode

Bisected against a51e5e8f28 (last decode-green boot, 297 decode batches).
git bisect narrowed to an ambiguous parent/child pair
(96bdb4a / 67b08b8) after several sgl-project#631-style crash-only commits
were skipped; direct-parent verification (67b08b8^ == fdb7b21, the
last confirmed-good commit) resolved it definitively in favor of
67b08b8 ("[sgl-project#1033] The flip hold asked half the one-chunk grant").

That commit added two new terms to the pp_to_tp/tp_to_pp quiescence
predicates: `fits_in_one_chunk` in `prefill_runnable_in_current_layout`
and a new `completed_chunk_pages_acked` ack-gate consumed by
`chunk_blocks_quiescence`. Root-caused via a first, WRONG partial revert
(kept `fits_in_one_chunk`, reverted only the ack-gate) that still failed
on the metal with a NEW symptom: 51 flips alternating every 27-40s (a
flip-flop livelock, 0 decode) plus a separate sgl-project#928-anchor retraction loop
on one request. Reading the full original diff showed the pre-sgl-project#1033 code
never had an ack-gate either (unconditional `return False`), so that half
of my hand revert was a no-op; `fits_in_one_chunk` was the actual driver.

This reverts 67b08b8's entire diff (both functions plus the
scheduler.py wiring in `build_flip_quiescence_fn`), applied at the
current branch tip via `git revert --no-commit` rather than a blanket
file-copy from the old commit: none of the 12 commits that touched these
two files between 67b08b8 and this tip touch these functions (only
one, [#1054d], and it edits an unrelated region ~11000 lines away), so
the revert applied with zero conflicts and preserves every later commit's
work in both files intact.

Per upstream-minimal: the sgl-project#1033 mechanism was itself a fork-own
compensation layer over the sgl-project#887 one-chunk grant; its own defect (an
unreachable-in-practice "both halves must agree" premise that instead
produced a livelock) makes it a deletion candidate, not a repair target.
Deleted the now-stale devtools/check_1033_quiescence_edge.py alongside it
(it exercised `fits_in_one_chunk`/`completed_chunk_pages_acked`, both
gone).

Test results (BOOT-PROVEN, two independent boots, driver load
disc631_driver.py --duration 480 --words 24000 --concurrency 2):
  - boot_855_fullrevert1033_67b08b87b6_0901_044806.log (smoke, at the
    bisect commit): VERDICT=GOOD, 15 decode batches, single clean
    pp_to_tp flip (no flip-flop), 0 crashes.
  - boot_855_tiprevert1033_2b23c255fb_0901_050011.log (this exact commit
    content, at branch tip): VERDICT=GOOD, 12 decode batches (accept
    rate 0.66), single clean pp_to_tp flip (3 reconciled rank-flips, no
    flip-flop), 0 Tracebacks, 0 sgl-project#631 crash markers, 0 sgl-project#928-retraction
    markers.

Not yet run: the >=30 min real-router-agent-load acceptance test
(Phase 3). This commit closes Phase 1/2 (bisection + root-cause fix,
boot-proven) only.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 15, 2026
… Prefetch-Verdikt TOLD auf der Request-Leitung

Befund (Boot xsn116, 2026-09-15 17:32:17, rid e10588ca, zweite Anfrage mit
identischem Praefix, D hatte ihn durchgeschrieben): jeder P-Rang registriert
seinen HiCache-Storage-Prefetch, keiner wartet darauf (sgl-project#973 PP0 PREFETCH WAIT
DISARMED / #969Z), der spaeter fertige Host-Treffer wird als sgl-project#1245
'undistributable' verworfen, damit die Raenge gleich bleiben -- P prefillt
einen im Store byte-vollstaendigen Praefix neu (STORE WITNESS state=unprobed
loaded=0, 'sgl-project#928 anchor REFUSING resume ... re-prefilling'). D leg 2 liest
denselben Store korrekt (cached_tokens=4314/4316), weil der TP-Pfad wartet
(Policy timeout) und MIN-reduziert.

Fix: der Traeger ist die Request-Leitung, die es schon gibt (recv_reqs wird
je Pass PP0->PP1->PP2 gepickelt weitergereicht; sgl-project#1268 fix 1c faehrt dort
schon Weg2IdleVoteReq). Protokoll je rid:
  1. Intake: PP0 registriert wie bisher und haelt; Folgestufe registriert
     NICHTS ('declined:weg2_held', neuer sgl-project#915-Partitionsterm).
  2. PP0 vor dem Forward: fuer jeden gehaltenen rid mit terminiertem
     Prefetch (check_prefetch_progress, kollektivfrei bei tp_size 1) wird
     die geladene Zahl ohne Pop gelesen, als told gespeichert und als
     Weg2StoreTold(rid, told) auf die Leitung gehaengt. PP0 admittet nur,
     was es auf die Leitung gelegt hat.
  3. Folgestufe nach dem Forward, vor dem Dispatch: nimmt die Objekte aus
     der Liste, speichert told, registriert den Prefetch fuer EXAKT told
     Token (_prefetch_kvcache(limit_tokens=told)) -- gleiche Seiten, gleiche
     Laenge, gleicher Store: Host-Baum und Load-Back-Extent sind inhaltlich
     uniform, keine Praefix-Truncation an einem Mamba-Anker noetig.
  4. Admission auf jedem Rang: ohne told -> Skip 'weg2_store_told_pending';
     mit told -> bounded Warten auf den eigenen Read, Pop, und benannte
     Verweigerung Weg2StoreToldMismatch bei own != told (Raenge nie uneins).
Der sgl-project#1245-Drop bleibt fuer die traegerlose Form ohne told; mit told ist der
Extent verteilbar. Arm nur bei pp_size>1, tp_size==1, Storage an, kein
Zeilentraeger; Kill-Switch SGLANG_WEG2_STORE_TOLD=0. pp_size<=1 (Gruppe D)
unveraendert.

Tests: test_weg2_store_told_1400.py 12 gruen; Mutant (Admission ohne Verdikt
+ Mismatch-Refusal aus) 3 rot. 16 Test-Dateien der beruehrten Symbole:
34 rot vor und nach der Aenderung identisch (Sockel: Doubles ohne ps /
_pp_post_send / _pp_send_admission_decision), 0 neu. Provider-Smoke 19/19.
Metall-Abnahme steht aus (arm_xsn117): zweite Anfrage gleicher Praefix ->
P leg 1 cached_tokens>0 und 0x 'sgl-project#928 anchor REFUSING'.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 17, 2026
…ssue it

weg2xsn241/243, rid weg2-6-2 (4316 tokens): the first hold read answered
NOTHING (store held 64 leading KV pages, no Mamba anchor in range yet ->
the component pool cut the claim to 0), and a zero answer is recorded
with deliverable=0, so it is not 'incomplete', raised no sgl-project#1324 shortfall
and was never re-read; at the wake sgl-project#928 refused the anchorless node and
the X gate priced the whole prompt -> W31.  _weg2_refetch_one now treats
a record with materialized == 0 for a span > 0 as short (reason
zero-answer) and re-issues it on the 2 s cadence, bounded by the settle
tick after the wake.

Tests: test_weg2_revoke_reissue_1479 (10) + 1471/1445 -> 23 passed.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 26, 2026
… kann -- sonst Re-Prefill aller statt benanntem Tod -- rc9m-Nachlauf dkrnfbar1rc9m09260642 starb nach 3,5 min Agentenlast (D-Log Z. 53969-54036, 06:57:28, rid weg2-18-15): TP0 stimmte 18112 (Host-Anker dort), TP1/TP2 15552, Gruppen-MIN 15552; H96 kuerzte TP0 auf 15552, TP0 hat dort aber KEINEN rekurrenten Anker ('[sgl-project#928 anchor] REFUSING resume ... match_tokens=2560') -> 'H96 RU FLOOR CAP-MISS ... capped_match=0', D tot. Wurzel: H96 nahm an, TP0s Host-Abdeckung sei Obermenge von TP1/TP2 -- gilt fuer den KV, nicht fuer die Mamba/GDN-Anker (die Host-Freigabe ist je Rang verschieden, Anker liegen je Rang auf verschiedenen Tiefen); das MIN der je Rang tiefsten nutzbaren Tiefe ist keine Tiefe, die jeder nutzen kann. Fix (27B-Weg a, 'langsamer, nie falsch'): der vorhandene gepackte MIN traegt einen zweiten Arm (-lokal) -> jeder Rang kennt auch das MAX; nur fuer rids mit 0 < MIN < MAX (Schieflage, auf allen Raengen identisch, also derselbe Pfad) laeuft EINE weitere kleine MIN-Reduktion 'ich kann die Gruppentiefe exakt realisieren' (seiteneffektfreier match_prefix auf key[:g], cow_mamba=False: Laenge == g und nutzbarer Anker); ein Rang mit 0 -> Gruppe pflanzt 0 fuer diesen rid, alle re-prefillen ('RU FLOOR SKEW-ZERO'). Ohne Schieflage bleibt der Pass bei einer Reduktion. H96-Kappung bleibt fuer den geprueften Fall, CAP-MISS nur noch als Riegel. Kein Schalter. Tests test_nf_rank_floor_skew_h97 (5, darunter rc9m-Form ueber die echte finalize_match_result: alle Raenge 0; rc9l-Form: alle 16384): alle rot auf 68d4bca, gruen mit Fix; H96 (7) + RU (15) gruen; Reduce-Suiten 823/823-live/1068/1206/1158: 32 Altlasten identisch zur Basis, 0 neu; H93-Suitenliste 0 neu
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 26, 2026
…orker-Anker ohne Bytes stimmen nicht mehr mit

rc9i/rc9k/rc9l/rc9m sind ein Bug. NF-D laeuft in Form A: TP0 haelt Attention,
GDN/Mamba, KV und Draft (q heads split [24, 0, 0]); TP1/TP2 sind reine
Experten-Worker ("Form A: rank N is an EXPERT WORKER ... no dense weights, no
KV, no draft", rc9m-D-Log Z. 63/80) mit 0-Byte-Pools (KV K/V 0.00 GB Z. 3738f,
Mamba ssm/conv 0.00 GB Z. 3720f, Host-KV MHATokenToKVPoolHost 0.00 GB Z. 4623/
4626, Mamba-Host 0.00 GB Z. 4943/4945, Null-Storage-Tier Z. 4949-4952). Ihr
Radix-Baum ist Buchhaltung ohne Bytes; ihre Host-Zeilen werden nach dem
Store-Ack als Transit freigegeben (unified_radix_cache.py:4014/6684/7554), die
Anker sterben bei Eviction, auf TP0 bleiben sie in der Arena -> Anker auf
anderen Tiefen. Trotzdem stimmten sie im RU-Usable-Arm des gepackten MIN mit
(rc9l: TP0 19712 / Worker 16384; rc9m: TP0 18112 / Worker 15552 -> H96
CAP-MISS; H97 138d9df macht daraus "RU FLOOR SKEW-ZERO" = alle Raenge
re-prefillen 18112 Token). Der Worker-Forward liest nur die Zeilenzahl
(model_runner.py:5293 num_tokens = input_ids.shape[0] fuer den MoE-Input-
Carrier), also extend_len = seq_len - prefix_len -- keinen KV-Index, keinen
eigenen rekurrenten Zustand.

Fix (Muster x22 "Form-A-Worker enthalten sich im gepackten Claim-Vote",
cache_controller.py CLAIM_VOTE_ABSTAIN), keine neue Kollektive, keine
Scheduler-Aenderung (alles in tp_match_floor + MambaComponent):
- Host (TP0) stimmt im Usable-Arm seinen exakten ZULASSUNGS-Match
  (admission_probe: gleicher Schluessel/limit wie Req.init_next_round_input,
  ankergeprueft, sgl-project#928) -- nicht mehr die Kopf-Walk-Zahl, die der Zulassungs-
  schluessel nicht erreichen kann (seitenvielfacher Prompt, limit = len-1).
- Worker stimmt seine KV-REICHWEITE (derselbe Schluessel, Mamba-Regel fuer
  genau diesen Walk ausgesetzt: follow_walk). Wo er folgen kann (Reichweite
  >= Host-Tiefe) ist das MIN-neutral -> Gruppe = TP0; wo nicht (toter Knoten)
  ist es die ehrliche Grenze -> MIN < MAX -> H97-Runde entscheidet (TP0
  realisiert die kleinere Tiefe oder alle re-prefillen). Reines ABSTAIN
  haette diesen Fall in einen Tod verwandelt.
- Worker enthaelt sich im MAX-Arm (MAX_ARM_NEUTRAL) -> MAX = Host-Tiefe; in
  der H97-Runde ist sein Votum "Reichweite >= g" (kein Walk).
- Zulassung (MambaComponent.finalize_match_result, vor dem COW): Worker mit
  Gruppentiefe g > 0 uebernimmt g auf dem KV-Pfad (follow_rematch: Schluessel
  [:g], Mamba-Validator/sgl-project#747/sgl-project#928/RU im Follow-Walk ausgesetzt), ausser sein
  eigener Match ist schon g auf nutzbarem Anker; g = 0 -> Null. Log
  "RU FORM-A FOLLOW rid=... tp0_depth=... worker_local=... followed=...".
- Riegel: Worker erreicht g nicht -> FormAFollowMiss (benannter Stopp);
  Host unter g (lokal < g, sgl-project#928 a/b oder Slot-Mangel bei g > 0) ->
  FormAHostBelowGroup. H96-CAP-MISS und H97-SKEW-ZERO bleiben.
Warum keine Uneinigkeit mehr: g = MIN(Host-Zulassung, Worker-Reichweiten),
H97 nullt es, wo der Host es nicht realisiert; Host laesst genau g zu (Probe
== Zulassung, H96-Kappung darunter, sonst benannter Stopp), jeder Worker
genau g (Reichweite >= g per Konstruktion, sonst benannter Stopp).

Schalter SGLANG_WEG2_ENABLE_FORM_A_TP0_FOLLOW (EnvBool(True), environ.py),
wirkt nur mit installiertem Form-A-Rollenplan; aus bzw. klassischer Boot =
Verhalten von 138d9df.

Tests test_nf_form_a_follow_h98 (16, echte tp_match_floor-Arme/-Runde, echte
MambaComponent.finalize_match_result/create_match_validator, echter
installierter Rollenplan je Rang): 12 rot auf 138d9df (rc9m/rc9i/rc9l
Re-Prefill bzw. flacheres Resume statt Resume auf TP0-Tiefe, Stueckteile
fehlen), 16 gruen mit Fix; 4 Waechter (Schalter aus, klassischer Boot,
H97-Rueckfall bei kurzem Worker-KV, Gruppe 0) auf beiden gruen.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 26, 2026
…r-Verdikten werden benannte Stopps

Release-Audit zu H98/H99: ein `except Exception`, das je Rang auf einen
anderen Pfad faellt, ist die bare-except-Falle (Rang verschluckt den Fehler
der Autoritaet, die Gruppe laeuft auseinander).

- form_a_follow_active(): Fehler beim Lesen von Schalter/Rollenplan -> bisher
  still False (H97-Pfad nur auf diesem Rang, andere folgen), jetzt
  FormAFollowUndecidable ("RU FORM-A FOLLOW UNDECIDABLE"). Davon haengen
  this_rank_follows(), die H99-Span-Enthaltung, die H98-Arme und die
  Zulassung ab -- alle erben den benannten Stopp.
- group_floor_zeroes()/group_floor_cap() (RU/H96, Zulassungsverdikte je Rang):
  Messfehler -> bisher still "keine Nullung"/"keine Kappung", jetzt
  RankFloorUndecidable.
- Worker-Zulassung (form_a_follow_admission): bei g > 0 IMMER der Follow-Walk.
  Die Abkuerzung "eigener Match schon g auf nutzbarem Anker" fragte
  anchor_unusable, dessen except im Fehlerfall "nutzbar" antwortet -> der
  Worker nahm den gewoehnlichen Pfad, und sgl-project#928 konnte ihn allein nullen.
  FOLLOW-Zeile weiter nur bei Abweichung.
- form_a_trim_to_group(): das `except: pass` um die Span-Buchhaltung entfernt
  (verlorener Span = Hold-Settle dieses Workers auf eigenem Span).
- Bleiben (begruendet im Code): die drei excepts in anchor_unusable,
  can_realize, admission_probe -- jeder Aufrufer ist eine STIMME, die in einen
  MIN-Reduce geht; ein rangeigener Fehler aendert den Gruppenwert auf allen
  Raengen gleich. Die Zulassung liest sie nicht mehr; ein Host, der ueber
  einen Anker stimmt, den er dann verweigert, stoppt benannt
  (FormAHostBelowGroup / RankFloorCapMiss).

Tests (4 neu in test_nf_form_a_prefetch_span_h99): Schalter-Lesefehler ->
benannter Stopp; ein Rang wirft im Vote (Mock-gloo, drei Raenge) -> dieser
Rang FormAFollowUndecidable, niemand registriert; Worker mit Grabstein auf
g und verschlucktem Ankerfehler folgt trotzdem auf 18112; Floor-Messfehler ->
RankFloorUndecidable. Alle 4 rot auf H99 (erster Commit), gruen mit Fix;
Datei gesamt 11 rot auf 2eed285, 12 gruen; H98 16/16.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 27, 2026
…told=0 for every rank

Metal rc12k27 b1 (dkr27breleasedraftbar1w109270932, 9417507), 09:45:58, rid weg2-10-95: W27 on
PP1, 1024 rows for 512 tokens, sender_geom=(512, 1536) receiver_geom=(16895, 17407). Fix A held
(P-CHUNK-BUDGET pos=16383 pos_src=told width=512 on all three ranks); the split was the START:
  * PP0 put Admit(told=16383, absolute) on the wire -- head 16383 = what ITS registration matched in
    its own tree, span 0;
  * PP0's own admission in the same pass: [sgl-project#928 anchor] REFUSING resume ... match_tokens=69
    best_value_len=0 kv_host_hit=0 -> re-prefill, P-CHUNK-POLICY plan start=512 pick=mid=1024;
  * PP1/PP2 read 16383 from the store WITH the anchor (sgl-project#988 LOADBACK ... mamba_restored=33) and
    extended from 16383 at the budget width 512.
The authority admitted a different prefix than the one it told; the width split followed from the
start. Why PP0's head was gone: nothing holds a registered-but-not-admitted head; at 09:45:55 PP0
loaded weg2-10-93 back into the whole device KV pool (WEG2-ARENA-LOAD rows=151514 dst=[1,265705] of
265706), which evicts every unlocked device node. (sgl-project#1469's 600-line trail was exhausted at 09:40,
so the evicting call itself is not on this boot's record.)

managers/weg2_told_fidelity.py (SGLANG_WEG2_TOLD_FIDELITY, default on; 0 = the old Admit byte for
byte): right before PP0 appends an Admit with told > 0 -- paced form, both the window path and the
PF fallback path -- it asks its own tree (match_prefix with the fetch's key form, capped at the
told depth; the sgl-project#928 (a) rule read-only: 0 when the deepest node carries no state on device or
host) what its admission will resume from. The depth is the told itself when absolute (twin /
TK ABS-TOLD), head + span otherwise. Less than that -> the Admit carries told=0 with the PF fallback
marker: PP0 releases its own read, every follower releases its read (follower_release) and every
stage prefills from 0 -- decided before any follower adopts. A probe that cannot be asked gives no
verdict; the check is decided before any import (a tree without match_prefix costs nothing -- the
PF gloo ring measured PP0's publish at 10.7 s when the imports came first).

pp_admission_congruence.divergence_cause: the W27 text now names the split read off the two
geometries -- START-SPLIT (with both prefixes; "PP0's told was not the prefix one side admitted"),
WIDTH-SPLIT (same start, different chunk width), RID-SPLIT.

Not built (single-phase told form): the rig runs the paced form (#1416e PACED-TOLD/ADMIT on b1).

Tests: test_27b_told_fidelity_0927.py 11 (metal W27 provenance -> START-SPLIT; width/rid/absent;
sgl-project#928 state rule on nodes incl. host anchor and dense tree; metal case retold 0 with the log line;
resumable told kept, asked with told keys incl. bigram; span-relative told checked at head+span;
no probe / raising probe / switch off / told 0 keep the Admit; #1416e ring: PP0 that lost its head
-> one Admit told=0 fallback, every rank admits the same PP0 pass at cap 0; resumable -> 100000
unchanged; switch off -> old Admit, no probe; wiring order). Affected suites per file (store_told
1400/hold_tk/paced_1416e/positive_tk, told_group_fallback_pf, p_twin_defer, width_divergence_1233,
admission_congruence_791, admission_wiring_791, p_budget_rank_identical, p_intake_h91a): 133 passed,
4 failed -- the same 4 fail on the base 3e5a263 (791 module-imports-no-torch x1, wiring_791 x3).
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 27, 2026
…ots NO writer can still come to -- an open claim (rank asleep, behind, mid flip) is never taken, by any process, for any length of time

rc12m-dpr 09271152: from 12:13:14 every finished request on P logged 'MAMBA-ARENA ... end_anchor=missing' (weg2-16-57 on; 74x sgl-project#1421 BACKUP-REFUSED why=mamba_claim), D resumed short or not at all -- weg2-18-64: deliverable 37248, deepest anchor 17536 -> 'prefetch INCOMPLETE ... shortfall 19712' (= 37248 - 17536, D-Log 99694); weg2-16-59: 'sgl-project#928 anchor REFUSING resume ... node carries no recurrent state' -> W50 fresh, second P prefill, and after the first byte W31/W50 in the open stream (empty 200). ARENA-REF-CENSUS of the mamba arena (slots=32): complete 29 (12:00) -> 5-8 (12:15-12:19), pinned <= 8, claims answered status 4 'no free slot' (D 12:04:26, 12:08:51).

Root: a mamba anchor slot is COMPLETE only when every P rank merged its extents (layers split over PP0/1/2). The ranks decide their anchor claims locally -- PP0 finds prefix nodes already backed, PP1/PP2 publish them (weg2-0-11..14, 12-46, 14-51/53, 16-56, 2-17..19, 4-20..22, 21-77: PP0 written=1, PP1/PP2 written=2..4). A stem PP1/PP2 claimed and wrote but PP0 never joined stays CLAIMED: not COMPLETE (no reader, no evictor may take it) and not FREE; the tree reset gives the writers' references back, the slot stays. Follow-up, not in this commit: a group-uniform anchor claim on P removes the orphans at their source.

Fix -- an orphan is a slot no writer can still come to, known from the slot, not from a clock:
- arena.c: the SlotHeader's former 8-byte pad carries touched_ms + writers (claims << 16 | open), layout and file format unchanged. arena_claim counts a claim and an open writer (fresh or join); arena_complete closes the writer (merge, or already COMPLETE); new arena_unclaim closes it without a merge (generation-checked). arena_reap_partial takes a CLAIMED slot only with claims > 0, open == 0, refcount 0 and untouched for the age (belt): index cell tombstoned, generation bumped, n_claimed exact. The payload path (arena_write, claims 0) is never judged.
- pools: abort_write, a failed _claim and free() of a pending JOIN unclaim it (a fresh claim is freed whole as before), so a writer that gave its claim up is not open forever.
- only the MAMBA anchor arena reaps (ArenaMambaPoolHost._weg2_reaps_orphan_claims, bound to the form -- per-rank anchor claims into a shared arena -- not to a model name): the KV pool's claim room and every form without mamba arena claims (27B: host_anchor_slots, 0 MAMBA-ARENA claims) is a no-op. SGLANG_WEG2_ARENA_PARTIAL_REAP_S (default 30 s, 0 = off), line 'sgl-project#231 ARENA-REAP-PARTIAL n= freed= total= slots= age_s='.

Guarantees (review 27B/coordinator):
(a) P asleep through a D phase (D awake on the same arena, claiming): P's open claim keeps open > 0 -- D reaps nothing of it, for any length of time; after the wake P's writer merges and the slot completes.
(b) flip leg / park: a claim in flight is open until its merge or abort, whatever the clock says.
(c) PP0 behind: PP0 never claimed -> the slot is an orphan of PP1/PP2 only after both merged; if PP0 comes later it claims the stem FRESH (the index cell is tombstoned) -- never status 3 on a slot it owns; the straggler costs only the anchor's completeness, named by MAMBA-ARENA as before.
A merged writer's node holds the reader reference until its tree lets the node go (refcount > 0 is never reaped).

Tests test_arena_partial_claim_reap_231 (10, the real C arena on a temp file mapped twice = P and D, the real _evict_for_claim of both pools, the real ArenaMambaPoolHost.free): the mandatory case -- PP1 merged, PP2 claimed and open, P's reset drops the reference, D fills the arena and asks for room 4x past the reap age: nothing reaped, D gets status 4, after the wake PP2 merges -> COMPLETE; the rc12m metal shape (four orphans, END anchor status 4 -> fresh slot after the reap, PP0 later claims fresh); a referenced partial slot is never reaped; an aborted join and a join freed unwritten make the slot an orphan; a recent orphan waits for the age; off switch; COMPLETE unreferenced slots still go first; the KV pool (27B form) reaps nothing; payload-written partials are never judged. Base 2f800ca: 5 red; the first form (age only, 60253792a9): 4 red incl. the mandatory sleep case and the KV no-op; this form 10/10. Arena suites (24 files): identical to the base except the new file.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 27, 2026
…rid waits for a D seat is re-routed fresh through P when D would have to prefill more than X of it; the front drops the rid's hand-off marks at every rid end

NF rc12r (dkrnfh91dprbar1dauer09271632, 2494e7e): weg2-12-39 was prefilled whole on P (76602), published,
then waited 255 s for a D seat (6/6); a flip's P reset gave the arena refs back (sgl-project#1427 RESET-RELEASE), H81
released the Mamba end anchors at=wake, the pages were overwritten, and at the D admission #1028B FETCH CAP
lost=1196 / sgl-project#928 no recurrent state / X-GATE uncached=76602 refused it mid-stream. The hand-off's life
was tied to phases, not to its consumption. NF's side (sglang.srt.weg2.handoff_pending: a pending mark
from P's publish to D's consumption, pending pages evicted last, a loss NAMED as HANDOFF-LOST +
<arena>/handoff/lost/<rid>.json; status(rid) / drop(rid, reason), never raising) is NF's commit.

This is the front half, agreed 27B <-> NF 27.09. (weg2/handoff_seam.py):
- Guarded read: without NF's module or when it raises / answers a wrong shape, state=none (the front is
  unchanged). The import is tried once per process.
- A rid whose leg 1 ran and that waits for a D seat (not skip_leg1 / d_direct / resume_via_p / p_only) is
  checked every controller pass (_hl_sweep, before _rvp_take), in d_admitter before the seat and again
  with the seat in hand (the seat wait is the long part). lost: credit = first_lost_page * page_size (no
  page_size -> credit 0, never an assumed size), uncached = leg-1 prompt - credit.
  uncached > X -> "WEG2 HANDOFF-LOST-REROUTE rid= first_lost_page= credit= path=fresh-P": drop(rid,
  reroute_fresh), leg1_done/seat/d_eligible/d_direct cleared, est_uncached = uncached, back at the queue
  HEAD (the oldest, as an intake stall), R28 reroute, controller kick -- the queue re-entry X-REQUEUE ends
  with; X-REQUEUE's own entry answers a refused LEG 2 and needs its request and seat, which a rid still
  awaiting admission does not have, and its W31/W35 counter is not touched. Bounded at one reroute per rid
  (handoff_lost_reroutes); a second loss is admitted and left to D's own X gate.
  uncached <= X -> "WEG2 HANDOFF-LOST-KEPT" once per rid; D prefills the lost tail itself (law 4).
- Rid end: handle_generate notes its rid on the aiohttp request; before the FORWARD_PATHS routes are
  registered the app binds front.handle_generate = handoff_seam.wrap_handler(...), the ONE rid-end site -- drop(rid, served | status_<code> (W35 503,
  refusals) | abort:<Exc> | disconnect) on every return, exception and cancel.
- Switch SGLANG_WEG2_HANDOFF_LOST_REROUTE (default on; 0 = no status reads, no reroute; the rid-end drop
  stays, it is bookkeeping).

Tests: test_weg2_handoff_seam_243_0927.py 15 (fake NF module: pending left alone; lost over X -> fresh P at
the head with drop reroute_fresh, flags cleared, the line; lost under X kept and named once; second loss
admitted; missing module / raising status read none; switch off reads nothing; no leg 1 / skip_leg1 /
d_direct not checked; no page_size credits nothing; sweep moves only the lost one and keeps the order; the
rid-end wrapper drops on 200 / 503 / exception / cancel and not without a rid; wiring: admitter before and
after the seat, controller sweep, route registration, rid noted).
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 28, 2026
…lform (array statt list) -- Admit(0) fuer alle, wenn PP0s Anker am told fehlt

rc12z2 (e8a2cd2, P-Log Z. 226312-226760, 03:26:31-41, rid weg2-44-76):
PP0 las 47168 Tokens (8x 'sgl-project#1433 L3->L2 fill' -- der Rueckweg, den Runde 4
erst oeffnete), klemmte told auf den Store-Anker 37952 (sgl-project#1416 ANCHOR-CLAMP)
und schickte ihn. Beim Zulassen:
  PP0 'sgl-project#904 ... reached=37952 refused=37952 why=MambaComponent:absent'
      -> '[sgl-project#928 anchor] REFUSING resume' -> Zulassung bei 0
  PP2 dasselbe -> 0
  PP1 'sgl-project#988 LOADBACK ... anchor_depth=37952 mamba_restored' -> 37952
PP1 bekam PP0s Zeilen 32768..49152 zu seinem Batch 70720..79688:
'sgl-project#1233 W27 PP WIDTH DIVERGENCE REFUSED ... cause=START-SPLIT', P tot.

Genau dafuer gibt es TF (weg2_told_fidelity, Default an): vor dem Admit
fragt PP0 den eigenen Baum, kann er am told nicht fortsetzen, geht told=0
mit PF-Fallback-Marke an ALLE Stufen (jede gibt ihren Read frei, alle
prefillen ab 0). Auf NF lief TF nie: '#TF told-fidelity probe skipped ...
AssertionError((<class 'array.array'>, <class 'list'>))' 10 von 10 auf
diesem Boot -- _probe_key baute den Schluessel als list, der Baum
vergleicht array('q')-Schluessel (RadixKey.match: assert type(t0) is
type(t1)). Keine Aussage -> Admit blieb 37952, waehrend PP0 selbst 0 nahm.

Fix (kein Schalter, bestehende Vereinbarung): _probe_key baut array('q').
Die #1416d-Klemme teilt den Schluessel; ein Array-Schluessel hasht dieselben
Seiten (compute_node_hash_values hasht die Array-Schluessel des Baums).

Test test_told_fidelity_array_key_rc12z2 (4; Fake-Baum vergleicht mit dem
ECHTEN RadixKey.match gegen einen Array-Knoten, told 37952, Bigram): 3 rot
auf e8a2cd2 (genau 'AssertionError((array.array, list))', Verdikt
(37952, None) statt (0, 0)), gruen mit Fix; Hash-Gleichheit list/array
gruen auf beiden. Die TF-Suite 0927 mass nur len(key) und erreichte den
Vergleicher nie.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 28, 2026
…-- die gruppeneinheitlich realisierbare Resume-Tiefe nach dem Finish (Front kappt credit auf min(ct, Tiefe))

Die Front schreibt einem D-Leg seine cached_tokens gut, also den KV, den D bei
der ANKUNFT fand. Was D fuer den naechsten Turn behaelt, ist eine andere Zahl:
Der Finish fuegt den ganzen Schluessel ein, aber ein hybrides GDN/Mamba-D setzt
nur an einem rekurrenten Anker fort (sgl-project#928), und der Finish ankert auf dem
Track-Raster (sgl-project#747). Ein Finish neben dem Raster haelt KV oberhalb seines
letzten Ankers, von dem keine Zulassung fortsetzen kann (RETAIN off-grid).
rc12z weg2-12-61: credit 55424, D-Extent 37952 -> 19840 > X, X-Verweigerung
mitten im Stream, 72 s P-Umweg; rc12y weg2-16-42 ebenso (27B f4a982e).

Neu: managers/weg2_resumable_depth.py.
- Der Output-Streamer stempelt auf der FINISH-Ausgabe (release_kv_cache lief
  schon) time_stats.weg2_resumable_depth. Wert = die seiteneffektfreie
  Admission-Probe der RU/H98-Stimmen (tp_match_floor.admission_probe:
  host_admission_len mit sgl-project#1040-Extent, sgl-project#928-Ankertest, #1424d-Beweisschnitt)
  auf der ganzen Sequenz, ohne das len-1-Limit dieses Turns.
- Gruppeneinheitlich: Form A -> der Host entscheidet (H98, Worker folgen und
  rechnen nichts); ein Rang -> trivial; klassisches TP -> MIN ueber die
  TP-CPU-Gruppe (nur fuer eine nicht leere Finish-Liste, auf allen Raengen
  gleich); DP-Attention ohne Form A oder PP -> kein Feld.
- 0 ist gemessen und wird gesendet; -1 = kein Feld. Abgebrochene Requests
  enden ueber denselben Pfad und tragen es mit.
- Traeger: time_stats.__getstate__ (auch ohne --enable-metrics) ->
  meta_info (/generate) -> sglext (OpenAI Body + Stream-sglext-Chunk) ->
  /v1/messages Top-Level-sglext (Message und message_delta). Damit greift der
  27B-Front-Leser (meta_info/sglext, Body und Stream-Tail) unveraendert.
- Metall-Marker: 'sgl-project#59 RESUMABLE rid=.. depth=.. seq=.. cached_tokens=.. mode=..'.
Kein Schalter: fehlt das Feld, bleibt der alte Preis.

Tests test_weg2_resumable_depth_59.py (17): alle rot auf 78b9ff7, gruen
mit Fix. Nachbarn 70 Dateien Basis gegen Fix: 0 neue Rote.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 28, 2026
… no byte yet goes back through P (W50 X-REQUEUE), not W123

NF rc12z10 08:40:07Z rid weg2-2-12 (image 6290..9528 of 9537 tokens): P 'END-ANCHOR anchor=0 target=9536
ok=False short=1' (sgl-project#241 class, root (A) is NF's), D 'sgl-project#928 REFUSING resume ... NONE-ON-THIS-PATH', covered=0
-> W123 to the client. Same code on 27B.

D (_weg2_answer_vision_d_refusals): a refused request that has generated NOTHING (output_ids empty,
replicated) is answered with the W50 Weg2TpPrefillExceeded refusal the front already re-routes through
P -- x_refusal_marker_in holds, the extent sentence carries len(fill) - covered, W123 is named inside.
The front's X-REQUEUE sends the ORIGINAL request, image included, to P (which has the tower); D resumes
from P's pages. Bounded by the front: a second refusal after a P leg that ran is its W35/W53 (SK-X), whose
body quotes D's message (W123 named). Before the first byte on both wire shapes: non-stream 503, stream
the refusal as the first chunk (the ROS lookahead / first-chunk X-REQUEUE). No D hold, so no
_rvp_inflight entry and nothing for the D->P drain to wait on (8340ee4).
An already STREAMED request keeps W123: RESUME-VIA-P's P leg carries input_ids only (resume_via_p.eligible
excludes multimodal), P could not encode the image from them -- that case needs a P leg with the original
body and is not built here.
Switch SGLANG_WEG2_VISION_D_REROUTE (default on, 0 = the plain W123).

Tests test_weg2_vision_d_guard.py 22 passed (3 new from the metal shape: rerouted with the X-REQUEUE
marker and extent 9537, W123 named inside; streamed keeps W123; switch off keeps W123; the existing
answer test pins the streamed case). Red on 7e227e5: 2 failed.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 28, 2026
…30e (Front-Log ...09282117_ca2a9706ec_0928_211748): weg2-14-37 (16869 Tok) 'X-EXACT-PRICE pending=779 credit=16090 src=d_leg2_cached' -> SHORT -> D: '[sgl-project#928 anchor] REFUSING resume ... match_tokens=3840 best_value_len=0', 'X-GATE uncached=16869 verdict=W31' -> 'W50-REROUTE x_refusal_midstream', 'PARK-IMMEDIATE cause=over-x' parkte 4 laufende Decodes (rpc_s=4.42), Flip, P rechnet alle 16869 (RESUME-VIA-P p_ms=15275). Die Gutschrift 16090 ist nicht seitenbuendig: sie ist der Token-LCP mit dem Zeugen-Eintrag, also der Divergenzpunkt selbst -- dort haelt D keinen Zustand. TokenSpans.pending rechnete credit = min(raw, lcp): liegt der Anker des Eintrags (raw = gemessene/gehaltene Tiefe, sgl-project#59-gekappt) hinter der Divergenz, wurde die Divergenz zur Gutschrift. 5 der 8 W50-REROUTEs dieses Boots haben diese Form (credit = lcp, nicht /64: 10-32 27250, 14-37 16090, 16-40 29285, 16-41 17017, 44-79 33484); die 3 seitenbuendigen (28-59 31808, 30-62 23040, 38-70 36480) sind credit = ct <= lcp, d.h. ein Anker auf dem Pfad, den D verloren hatte -- das ist die ANCHOR-LOST-Klasse (7cd2fda: Schlaf-Flush nimmt Gutschriften auf verlorenen Tiefen zurueck), PX laesst sie unberuehrt.

Fix (front_tokens): divergence_credit(raw, ct, cap, lcp) -- raw <= lcp: wie bisher; sonst der gemessene Aufsetzpunkt ct, wenn er auf dem gemeinsamen Pfad und innerhalb D's Tiefe liegt (ct <= lcp, ct <= cap), sonst 0. known_prefix_depth (sgl-project#59 A, Kappe neuer In-flight-Texte) nimmt die tiefste Kappe, die innerhalb ihres LCP liegt, statt die Kappe des laengsten LCP auf den LCP zu schneiden. Zu wenig Kredit kostet ein P-Leg; zu viel kostet den Request und jedes Decode, das der Umweg parkt. Kein Schalter.

Tests test_weg2_price_divergence_px_0928 (6): 14-37-Form (Zeuge 20171/ct 20160, LCP 16090 -> credit 0, pending 16869 > X), Aufsetzpunkt unter der Divergenz bleibt Kredit, sgl-project#59-Metallfall unveraendert, Folgeturn mit enthaltenem Eintrag unveraendert, ct jenseits D's Tiefe = 0, known_prefix_depth jenseits Divergenz = 0; 4 rot auf f7df18e, 6 gruen mit Fix. Drei Tests pinnten den Fehler und sind umgeschrieben: x_exact 'capped_by_the_token_lcp' (9990 hinter LCP 9000: (3000, 9000) -> (12000, 0)), sgl-project#59 'weg2_16_42 without the field' (die rc12y-Ueberkreditierung 46726/125, die der Dateikopf selbst als Metallfehler nennt -> (0, 46851)), sgl-project#59 'a_tokens_iv' (Nachbar-Anker 1800 hinter geteilten 1500 -> tiefste Kappe auf dem Pfad 512 statt 1500). Nachbarn 22 Dateien: Fix 2 Rote = Basis-Altlasten (h42 count-arm, h91a settle), 0 neu.

Metall-Marker: X-EXACT-PRICE credit ist nie mehr ein nicht-seitenbuendiger LCP ohne Anker; W50-REROUTE mit front_price << d_extent faellt fuer die Divergenzklasse weg. Erwartung: je Fall kein D-Sitz, kein PARK-IMMEDIATE (4,4 s RPC + Wiederaufnahme ~3 s, 3-4 laufende Decodes unterbrochen), der Request geht direkt LONG ueber P (14-37: 15,3 s RESUME-VIA-P -> P-Leg ~8 s ohne Park/Umweg).
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 28, 2026
…30e (Front-Log ...09282117_ca2a9706ec_0928_211748): weg2-14-37 (16869 Tok) 'X-EXACT-PRICE pending=779 credit=16090 src=d_leg2_cached' -> SHORT -> D: '[sgl-project#928 anchor] REFUSING resume ... match_tokens=3840 best_value_len=0', 'X-GATE uncached=16869 verdict=W31' -> 'W50-REROUTE x_refusal_midstream', 'PARK-IMMEDIATE cause=over-x' parkte 4 laufende Decodes (rpc_s=4.42), Flip, P rechnet alle 16869 (RESUME-VIA-P p_ms=15275). Die Gutschrift 16090 ist nicht seitenbuendig: sie ist der Token-LCP mit dem Zeugen-Eintrag, also der Divergenzpunkt selbst -- dort haelt D keinen Zustand. TokenSpans.pending rechnete credit = min(raw, lcp): liegt der Anker des Eintrags (raw = gemessene/gehaltene Tiefe, sgl-project#59-gekappt) hinter der Divergenz, wurde die Divergenz zur Gutschrift. 5 der 8 W50-REROUTEs dieses Boots haben diese Form (credit = lcp, nicht /64: 10-32 27250, 14-37 16090, 16-40 29285, 16-41 17017, 44-79 33484); die 3 seitenbuendigen (28-59 31808, 30-62 23040, 38-70 36480) sind credit = ct <= lcp, d.h. ein Anker auf dem Pfad, den D verloren hatte -- das ist die ANCHOR-LOST-Klasse (7cd2fda: Schlaf-Flush nimmt Gutschriften auf verlorenen Tiefen zurueck), PX laesst sie unberuehrt.

Fix (front_tokens): divergence_credit(raw, ct, cap, lcp) -- raw <= lcp: wie bisher; sonst der gemessene Aufsetzpunkt ct, wenn er auf dem gemeinsamen Pfad und innerhalb D's Tiefe liegt (ct <= lcp, ct <= cap), sonst 0. known_prefix_depth (sgl-project#59 A, Kappe neuer In-flight-Texte) nimmt die tiefste Kappe, die innerhalb ihres LCP liegt, statt die Kappe des laengsten LCP auf den LCP zu schneiden. Zu wenig Kredit kostet ein P-Leg; zu viel kostet den Request und jedes Decode, das der Umweg parkt. Kein Schalter.

Tests test_weg2_price_divergence_px_0928 (6): 14-37-Form (Zeuge 20171/ct 20160, LCP 16090 -> credit 0, pending 16869 > X), Aufsetzpunkt unter der Divergenz bleibt Kredit, sgl-project#59-Metallfall unveraendert, Folgeturn mit enthaltenem Eintrag unveraendert, ct jenseits D's Tiefe = 0, known_prefix_depth jenseits Divergenz = 0; 4 rot auf f7df18e, 6 gruen mit Fix. Drei Tests pinnten den Fehler und sind umgeschrieben: x_exact 'capped_by_the_token_lcp' (9990 hinter LCP 9000: (3000, 9000) -> (12000, 0)), sgl-project#59 'weg2_16_42 without the field' (die rc12y-Ueberkreditierung 46726/125, die der Dateikopf selbst als Metallfehler nennt -> (0, 46851)), sgl-project#59 'a_tokens_iv' (Nachbar-Anker 1800 hinter geteilten 1500 -> tiefste Kappe auf dem Pfad 512 statt 1500). Nachbarn 22 Dateien: Fix 2 Rote = Basis-Altlasten (h42 count-arm, h91a settle), 0 neu.

Metall-Marker: X-EXACT-PRICE credit ist nie mehr ein nicht-seitenbuendiger LCP ohne Anker; W50-REROUTE mit front_price << d_extent faellt fuer die Divergenzklasse weg. Erwartung: je Fall kein D-Sitz, kein PARK-IMMEDIATE (4,4 s RPC + Wiederaufnahme ~3 s, 3-4 laufende Decodes unterbrochen), der Request geht direkt LONG ueber P (14-37: 15,3 s RESUME-VIA-P -> P-Leg ~8 s ohne Park/Umweg).
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 30, 2026
…nn sein Span schon im Baum liegt (y5a weg2-19-28)

NF-Operator 30.09. (Mamba/GDN-Praefixzustaende gehen verloren, obwohl L3
Platz hat). Kette aus dem D-Log y5a (0110f8e132_0930_174039, TP0):
- 17:48:10 der Hold-Read von weg2-19-28 findet mit EIGENEN Schluesseln
  (sgl-project#1442 HANDOFF-KEYS NONE) den Sessions-Praefix im Store: "#1028B FETCH CAP
  kv=675 claimed=665 ... anchors_in_range mamba (9, 664)" = 42560 Token MIT
  Anker auf Seite 664. Schluessel-Identitaet ist NICHT die Luecke (18-24 las
  denselben Praefix mit eigenen Schluesseln: store_hit=42240; das "known=640"
  ist der Nachlese-Rest [42560, 43200) nach dem ersten Read).
- 17:48:12 das Geschwister weg2-18-24 wird zuerst zurueckgeladen ("sgl-project#988
  LOADBACK ... prefix moved to 43520 ... anchor_depth=43520"): sein KV liegt
  auf dem DEVICE, Zustand nur bei 43520.
- 19-28's Read endet (completed=42560): _insert_helper_host findet den
  ganzen Span schon im Baum, legt keinen Host-Knoten an (inserted_host_node
  None: der Knoten hat keine Host-KV-Kopie), und
  MambaComponent.commit_hicache_transfer(PREFETCH) GIBT DEN ANKER FREI.
- "[sgl-project#904 match-census] reached=43200 accepted=0 refusers=MambaComponent:
  absent=43200" -> "[sgl-project#928 anchor] REFUSING ... best_value_len=0 NONE-ON-
  THIS-PATH" -> W31 -> W50 x_refusal_midstream, 43396 Token zu P.

Fix: _insert_helper_host nennt den Knoten, an dem sein Schluessel ENDET
(InsertResult.matched_end_node; der Lauf hat ihn dort gespalten = Tiefe des
Ankers). Traegt dieser Knoten keinen Zustand (weder Device noch Host), nimmt
er den gelesenen Anker (host_value, Host-LRU) statt der Freigabe. Ein Knoten
MIT Zustand behaelt seinen, die Kopie wird wie bisher freigegeben. Der
naechste Match liest: best_match_node = der Knoten, state_anchor_depth =
seine Tiefe, mamba_host_hit_length = 1 -> init_load_back stellt den Zustand
in den Slot des Requests und nimmt den Device-KV darueber (der sgl-project#988-Weg).
Marker "WEG2 PREFETCH-ANCHOR-ATTACH". Schalter
SGLANG_WEG2_PREFETCH_ANCHOR_ATTACH (environ.py, default an).

Tests: test_weg2_prefetch_anchor_attach_0930.py 6 (echter UnifiedRadixCache
ueber echtem HybridReqToTokenPool; 5 rot auf 8406e68). Nachbarn
(anchor_drop_l3_257ii, arena_mamba_direct_1427, prefetch_* 7 Dateien,
short_read_anchor_sa, mamba_hicache_issuance_869b, mamba_gates_the_hit_706,
unified_radix_hicache_dispatch, unified_mamba_views, boundary_anchor_792,
mamba_anchor_seams_747): 152 gruen; 905 double_frees + 747 prepare_gates
rot auch auf der Basis (fremd).
efschu pushed a commit to efschu/htsglang that referenced this pull request Oct 1, 2026
…ssion, like its KV chain (sgl-project#1417) -- z30y15 weg2-12-56 told=0 re-prefill

z30y15 P PP0 04:21:39Z, rid weg2-12-56: the read brought the mamba anchor at
16383 (#1028B FETCH CAP anchors_in_range=(4, 16382)), the insert named the
end node (sgl-project#1423 INSERT-PLACED matched=16383 deepest=107) and the mamba
PREFETCH commit attached the anchor there. But check_prefetch_progress takes
the sgl-project#1417 pin BEFORE the components' commit: at pin time the node carried no
mamba host value, so its mamba lock was skipped (skip_lock_node_ids), and the
commit left the fresh anchor UNLOCKED on the mamba host LRU. The 112-slot
mamba arena evicted it within the second (sgl-project#1427 ARENA-DROP slot_bytes=
78446592 at 04:21:39), PP0's told-fidelity probe found no state
(pp0_admissible=0) and sent told=0 with acks {1: 16383, 2: 16383}; PP1/PP2
"sgl-project#928 REFUSING ... best_value_len=0"; P re-prefilled 16383 tokens.

Fix (unified_radix_cache.check_prefetch_progress): after the components'
PREFETCH commit, a request whose span was pinned re-takes the pin -- the
anchor is now host-locked with its chain until pop_prefetch_loaded_tokens /
release_aborted_request release it (unchanged release path). Not touched:
a read without a pinned span (declined / host_span_unclaimed).
On P "0x PREFETCH-ANCHOR-ATTACH" is no defect by itself: that line is the
branch for an end node WITHOUT a Full host copy (the D case); P's end node had
one and the anchor attaches silently.

Tests (CUDA_VISIBLE_DEVICES="", real check_prefetch_progress, real
FULL+MAMBA tree): new test_prefetch_anchor_pin_z30y15.py red on 38c1d66
(2 failed: host_lock_ref 0, drive_host_eviction strips the anchor), green
here (3 passed incl. the admission releasing the pin). Neighbours
(1417 pin/sanity/reset, 1424h2, 1157, 257, 937/939/905, p4b, 257iii, anchor
attach 0930 x2): pass, except 905 double-free retry test which fails
identically on the base. mem_cache prefetch/radix sweep: 221 failed / 765
passed identically with and without the fix (pre-existing scaffold failures).
efschu pushed a commit to efschu/htsglang that referenced this pull request Oct 1, 2026
…ss a kept told verdict, and acks only what it can resume (N1 dkr27browauthoritybar1fs10010740 PP1 sgl-project#968 death)

N1 boot (image 32fc268 = 341d089 + L1,5 shadow), PP1 07:46:29Z, rid
weg2-10-16: PP0 PF TOLD-ACKED told=17406 acks={1: 17406, 2: 17406}, PP0
sgl-project#988 LOADBACK mamba_restored; PP1 "sgl-project#1423 INSERT-PLACED matched=17406
deepest=122", "H91 STORE-TOLD KEPT told=17406 credit=0" (not seated in the
told visit), then "[sgl-project#928 anchor] REFUSING resume ... match_tokens=17406
best_value_len=0", "sgl-project#1175 UNDER-COVERAGE local=0 scheduled=17406", 19 s,
"sgl-project#968 PREFIX MATERIALISATION SHORTFALL" -> group stop.

(a) Root: weg2_store_told.admission popped the credit with
pop_prefetch_loaded_tokens, which also released the sgl-project#1417 span pin -- and the
recurrent anchor ANCHOR-PIN (341d089) keeps under it. A request the adder
does not seat in that visit (H91 KEPT) then waits with its anchor unlocked on
the mamba host LRU. Now the credit is popped and the pin stays
(_pop_credit_keep_pin); p_intake.settle_told releases it together with the
kept verdict when the request leaves the queue; an abort releases it as before.

(b) Riegel: the follower's PF ack (weg2_told_fallback.own_prefix) named its
KV depth. It now asks the told-fidelity probe (the sgl-project#928 rule read-only): KV
without a recurrent state at its end acks the resumable depth ("PF TOLD-ACK
UNRESUMABLE"), PP0 sees own != told and answers told=0 for EVERY rank -- a
rank-agreed re-prefill instead of a 19 s wait and a group death. No probe =
no verdict (the KV count stands).

Tests (CUDA_VISIBLE_DEVICES="", real check_prefetch_progress + real
FULL+MAMBA tree, array keys): new test_told_anchor_pin_ack_n1_1001.py red on
341d089 (2 failed: host_lock_ref 0 after the told admission; KV-only
follower acks 16 of 16), green here (3 passed incl. "anchored follower acks
told" = no false fallback). Changed area (pin 1417 x3, anchor pin, PF x2, told
1400/1416e/1416f/TF x2/TK x2/SL, shortread, dual x2, p_intake/h91): 261
passed; 1 failure (test_weg2_p_intake_h91a source-text assertion) fails
identically on 341d089.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants