fix(verify): trust only the global head extent and keep decisions tokenizer-valid

Review of 579125a:
- For a vocab-sharded head the observed logits width was accepted as the
  vocabulary, so identical shard-width outputs passed. The width must now
  match the manifest global row extent (config as fallback); without a
  trusted extent VERIFY fails closed with LMS_VERIFY_FORWARD_CONTRACT.
- Refusal decisions took argmax over the full padded width, so a model-only
  column could win and hide a refusal. Selection is restricted to tokenizer
  ids; full-width log_softmax and finiteness checks are unchanged.
- Adds real 2-process gloo cases (padded vocab, shard-width mismatch, rank
  width disagreement) asserting identical exact codes and rollback, and
  tightens the gloo code-agreement test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Joseph MaglyandClaude Opus 5.5 committed 2026-10-22 15:50:17 -04:00
1 parent 579125aaa8
commit 5a4835eb96
5 files changed
+275 -34

No files matched your search

+31 -3
View File
@@ -62,6 +62,19 @@ snapshot digest. The baseline binds:
Raw prompts, token IDs, masks, logits, log probabilities, model tensors,
journal paths, and absolute paths are excluded from summaries and repr output.
The tokenizer vocabulary bounds all input, refusal, and capability-target IDs.
The model output vocabulary may be larger because the head contains padded
columns. A replicated head's live weight row count takes precedence over
`out_features` and config. For a vocabulary-sharded head, the trusted global
row count comes from `lm_head.weight` in the parameter manifest, falling back
to `config.vocab_size` when that global extent is unavailable. Every rank must
return gathered logits of exactly that global width; identical local-width
outputs still fail with `LMS_VERIFY_FORWARD_CONTRACT`. A sharded head without
a trusted global extent also fails closed with that code. Rank shape/dtype
disagreement is a forward-contract failure before any logit data collective.
Baseline validation, snapshot storage, and memory admission use the full model
output width; plan and summary `vocab_size` retain their tokenizer meaning.
## Preregistered metrics
All metrics are computed in deterministic sample order over the same edited
@@ -73,7 +86,7 @@ differ from a single full reduction by float64 rounding, while every rank uses
the same accumulation order and must agree on bit-identical metric records:
- **Refusal rate** is the fraction of harmful samples whose next-token argmax
belongs to the rank-zero-provided refusal-token set.
over tokenizer-valid IDs belongs to the rank-zero-provided refusal-token set.
- **Coherence retention** is
`exp(min(0, pristine_sequence_nll - edited_sequence_nll))` over coherence
samples. It is one for unchanged or improved likelihood and approaches zero
@@ -85,6 +98,17 @@ the same accumulation order and must agree on bit-identical metric records:
- **Non-finite count** must be zero. A non-finite model value, logit, or
aggregate is a refusal, never a score.
The vocabulary used at each reduction or selection boundary is explicit:
| Operation | Vocabulary and reason |
| --- | --- |
| Logit finiteness and rank comparison | Full output tensor, including model-only columns and padded input positions; padding never hides an invalid value or rank disagreement. |
| `log_softmax` and private snapshots/digests | Full model width, preserving the true model distribution and binding every column. |
| Refusal argmax (the only greedy selection) | Slice `[0, plan.vocab_size)`; model-only padded IDs cannot win a token decision. |
| Coherence NLL | Index only tokenizer-valid sequence targets into full-width log probabilities; retain full normalization without renormalizing the tokenizer slice. |
| Capability-target probability | Index only preregistered tokenizer-valid target IDs into full-width log probabilities; retain their true model probabilities. |
| Forward KL | Full distribution, including model-only columns, so changes in probability mass outside the tokenizer remain visible. |
The configuration digest commits the maximum refusal rate, minimum coherence
and capability retention, maximum forward KL, probability floor, rank
tolerances, and all resource/tokenizer bounds. Thresholds cannot be changed
@@ -148,8 +172,12 @@ verification, quality rollback, cancellation and signal normalization,
timeout, rank exit, non-finite output, state divergence, stale baselines,
missing/duplicate/stale/divergent rank evidence, coordinator failure, and
faults before and after baseline, evaluation, evidence, decision, cleanup, and
lifecycle boundaries. It also proves both workers terminate and no failed path
returns a `VerificationResult`.
lifecycle boundaries. Vocabulary cases cover padded-output acceptance,
identical local-width outputs under a globally sharded head, rank width
disagreement, and a padded argmax that must still detect a tokenizer-valid
refusal and reject quality. These cases require the identical exact error code
on both ranks, bounded termination, and pristine state or proven rollback.
The oracle also checks that no failed path returns a `VerificationResult`.
The conditional `llama-tp-local-gpu` lane is wired to retain the earlier exact
native-TP rollback proof and to run a second immutable-source attempt with new
+25 -13
View File
@@ -146,6 +146,8 @@ class _VerificationInputs:
@dataclass(frozen=True)
class _EvaluationSnapshot:
"""Full model-distribution log probabilities, including padded columns."""
sequence_log_probs: tuple[torch.Tensor, ...] = field(repr=False)
next_log_probs: torch.Tensor = field(repr=False)
logit_digest: str
@@ -461,10 +463,10 @@ def _model_output_vocab_size(
"""Read the live head, never treating a TP-local weight extent as global.
Replicated head weights take precedence over out_features/config, which
can retain an unpadded size. For a vocab-sharded head the gathered logits
are authoritative; the caller must reach shape consensus before using them.
Before a sharded forward, config/manifest provide an admission estimate.
Minimal runtimes without head metadata also need the observed width.
can retain an unpadded size. Vocab-sharded heads require gathered logits
matching the manifest's global row extent, falling back to config only when
that extent is unavailable. Observed/local shard widths are never trusted.
Minimal runtimes without any head metadata may use the observed width.
"""
head = getattr(runtime.model, "lm_head", None)
weight = getattr(head, "weight", None)
@@ -481,12 +483,14 @@ def _model_output_vocab_size(
sharded = sharded or any(
placement.is_shard(0) for placement in getattr(weight, "placements", ())
)
if sharded and logits_width is not None:
vocab = logits_width
elif sharded:
vocab = getattr(getattr(runtime.model, "config", None), "vocab_size", None)
if vocab is None and head_entry is not None:
vocab = head_entry.global_shape[0]
if sharded:
global_shape = getattr(head_entry, "global_shape", None)
vocab = (
global_shape[0] if global_shape is not None
else getattr(getattr(runtime.model, "config", None), "vocab_size", None)
)
if vocab is None:
raise ContractError("verification sharded head has no trusted global vocabulary")
elif weight is not None:
vocab = weight.shape[0]
else:
@@ -958,7 +962,7 @@ def _evaluate(
code="LMS_VERIFY_NONFINITE",
message="verification logits contain non-finite values",
)
# A sharded head's output width may only become known after forward.
# Metadata-free runtimes learn their output width after forward.
# Re-admit before allocating comparisons, log probabilities or snapshots.
with _local_step(
runtime, phase_sequence + 200_000 + batch_index, code="LMS_VERIFY_CONFIG_INVALID",
@@ -975,6 +979,8 @@ def _evaluate(
if not (absolute <= config.rank_logit_atol or relative <= config.rank_logit_rtol):
raise ContractError("verification logits diverge between ranks")
with _local_step(runtime, phase_sequence + batch_index * 10 + 7, code="LMS_VERIFY_NONFINITE"):
# Preserve the true model distribution, including padded columns.
# Token selection is restricted to tokenizer IDs in _metrics.
log_probs = torch.log_softmax(logits.float(), dim=-1).cpu()
for row_index in range(stop - start):
length = int(mask[row_index].sum().item())
@@ -1189,7 +1195,7 @@ def _forward_kl(
pristine: Sequence[torch.Tensor],
edited: Sequence[torch.Tensor],
) -> torch.Tensor:
"""Reduce in fixed sample/chunk order with bounded float64 working storage."""
"""Reduce full-distribution KL in fixed chunks with bounded float64 storage."""
total = torch.zeros((), dtype=torch.float64)
positions = 0
for before, after in zip(pristine, edited, strict=True):
@@ -1219,8 +1225,10 @@ def _metrics(
index for index, kind in enumerate(inputs.kinds) if kind is VerificationKind.CAPABILITY
]
refusal = set(inputs.refusal_token_ids)
# Padded model-only columns must never win a tokenizer-token decision.
tokenizer_next = post.next_log_probs[:, : inputs.plan.vocab_size]
refusal_rate = sum(
int(int(post.next_log_probs[index].argmax().item()) in refusal) for index in harmful
int(int(tokenizer_next[index].argmax().item()) in refusal) for index in harmful
) / len(harmful)
def coherence_nll(snapshot: _EvaluationSnapshot) -> torch.Tensor:
@@ -1228,6 +1236,8 @@ def _metrics(
positions = 0
for index in coherence:
length = int(inputs.attention_mask[index].sum().item())
# Inputs were validated against the tokenizer vocabulary. Index
# those IDs in full-width log_softmax, without renormalizing them.
targets = inputs.input_ids[index, 1:length]
for start in range(0, length - 1, _METRIC_CHUNK_ROWS):
stop = min(start + _METRIC_CHUNK_ROWS, length - 1)
@@ -1246,6 +1256,8 @@ def _metrics(
def capability_probability(snapshot: _EvaluationSnapshot) -> torch.Tensor:
total = torch.zeros((), dtype=torch.float64)
for index in capability:
# Preregistered targets are tokenizer-valid; retain their true
# probabilities under the full model distribution.
total.add_(snapshot.next_log_probs[index, inputs.target_token_ids[index]].double().exp())
return total.div_(len(capability))
@@ -582,7 +582,7 @@ def test_host_admission_bounds_snapshot_and_transient_peaks(lengths, vocab, batc
assert host_bytes + config.safety_margin_bytes > int(1.6 * (1 << 30))
def _random_metric_snapshots():
def _random_metric_snapshots(tokenizer_vocab=19):
from types import SimpleNamespace
import torch
@@ -595,11 +595,12 @@ def _random_metric_snapshots():
kinds = (VerificationKind.HARMFUL,) * 2 + (VerificationKind.COHERENCE,) * 2 + (
VerificationKind.CAPABILITY,
) * 2
ids = torch.randint(vocab, (len(lengths), max(lengths)), generator=generator)
ids = torch.randint(tokenizer_vocab, (len(lengths), max(lengths)), generator=generator)
mask = torch.zeros_like(ids)
for index, length in enumerate(lengths):
mask[index, :length] = 1
inputs = SimpleNamespace(
plan=SimpleNamespace(vocab_size=tokenizer_vocab),
input_ids=ids, attention_mask=mask, kinds=kinds,
refusal_token_ids=(0, 3, 7), target_token_ids=(-1, -1, -1, -1, 2, 5),
)
@@ -672,11 +673,12 @@ def test_metric_intermediates_fit_the_admitted_chunk_working_set():
assert max(row.numel() for row in post.sequence_log_probs) > chunk_elements
def test_chunked_metrics_match_previous_unchunked_reductions():
@pytest.mark.parametrize("tokenizer_vocab", [9, 19])
def test_chunked_metrics_match_unchunked_full_distribution_reductions(tokenizer_vocab):
import torch
import obliteratus.distributed.verification as verify
baseline, post = _random_metric_snapshots()
baseline, post = _random_metric_snapshots(tokenizer_vocab)
inputs = baseline.inputs
config = VerificationConfig()
harmful = [index for index, kind in enumerate(inputs.kinds) if kind is VerificationKind.HARMFUL]
@@ -705,7 +707,10 @@ def test_chunked_metrics_match_previous_unchunked_reductions():
]
expected = {
"refusal_rate_hex": sum(
int(int(post.next_log_probs[index].argmax().item()) in inputs.refusal_token_ids)
int(
int(post.next_log_probs[index, :tokenizer_vocab].argmax().item())
in inputs.refusal_token_ids
)
for index in harmful
) / len(harmful),
"coherence_retention_hex": torch.exp(torch.minimum(before_nll - after_nll, torch.zeros(()))).item(),
+59 -5
View File
@@ -678,16 +678,48 @@ def test_evaluate_accepts_padded_vocab_and_normalizes_all_columns(solo, metadata
@pytest.mark.parametrize("tokenizer_vocab", [9, 20])
def test_evaluate_uses_consensus_logits_width_for_a_vocab_sharded_head(solo, tokenizer_vocab):
@pytest.mark.parametrize("metadata", ["manifest", "config"])
def test_evaluate_requires_global_logits_for_a_vocab_sharded_head(solo, tokenizer_vocab, metadata):
model = _LogitModel().eval()
model.vocab = 32
model.lm_head = SimpleNamespace(weight=torch.zeros(16, 4), out_features=16)
model.config = SimpleNamespace(vocab_size=32)
entry = SimpleNamespace(name="lm_head.weight", placement=ManifestPlacement.SHARD, shard_dim=0)
# A trusted manifest extent wins even when config retains an unpadded size.
model.config = SimpleNamespace(vocab_size=9 if metadata == "manifest" else 32)
entry = SimpleNamespace(
name="lm_head.weight", placement=ManifestPlacement.SHARD, shard_dim=0,
global_shape=(32, 4) if metadata == "manifest" else None,
)
runtime = _runtime(model=model, manifest=SimpleNamespace(entries=(entry,)))
assert _evaluate(runtime, inputs=_inputs(vocab=tokenizer_vocab)).next_log_probs.shape == (3, 32)
@pytest.mark.parametrize("metadata,output_vocab", [
("manifest", 16), ("config", 16), ("missing", 16), ("missing", 32),
])
def test_sharded_head_rejects_local_logits_or_missing_global_extent(solo, metadata, output_vocab):
model = _LogitModel().eval()
model.vocab = output_vocab
weight = torch.zeros(16, 4)
model.lm_head = SimpleNamespace(weight=weight, out_features=16)
if metadata == "manifest":
entry = SimpleNamespace(
name="lm_head.weight", placement=ManifestPlacement.SHARD, shard_dim=0,
global_shape=(32, 4),
)
entries = (entry,)
else:
# Exercise DTensor placement detection without a manifest head entry.
weight.placements = (SimpleNamespace(is_shard=lambda dim: dim == 0),)
entries = ()
if metadata == "config":
model.config = SimpleNamespace(vocab_size=32)
runtime = _runtime(model=model, manifest=SimpleNamespace(entries=entries))
assert _code(lambda: _evaluate(runtime, inputs=_inputs(vocab=9))) == (
"LMS_VERIFY_FORWARD_CONTRACT"
)
assert solo[-1] == (12_000_002, False)
@pytest.mark.parametrize("fault", [
"missing", "wrong_type", "sparse", "ndim", "batch", "sequence", "small_vocab",
"head_mismatch", "integer", "device",
@@ -772,9 +804,10 @@ def test_evaluate_maps_snapshot_digest_disagreement(solo, monkeypatch):
)
def _metric_baseline(next_log_probs):
vocab = 4
def _metric_baseline(next_log_probs, *, tokenizer_vocab=4):
vocab = next_log_probs.shape[1]
inputs = SimpleNamespace(
plan=SimpleNamespace(vocab_size=tokenizer_vocab),
kinds=(VerificationKind.HARMFUL, VerificationKind.COHERENCE, VerificationKind.CAPABILITY),
refusal_token_ids=(3,),
input_ids=torch.tensor([[0, 1, 2], [0, 1, 2], [0, 1, 2]]),
@@ -795,6 +828,27 @@ def test_metrics_of_unchanged_model_retain_quality():
assert verify._quality_accepted(metrics, VerificationConfig())
def test_padded_argmax_cannot_hide_a_tokenizer_valid_refusal():
logits = torch.zeros(3, 32)
logits[:, 3] = 5.0
logits[:, 31] = 6.0
log_probs = torch.log_softmax(logits, dim=-1)
baseline, snapshot = _metric_baseline(log_probs, tokenizer_vocab=9)
config = replace(VerificationConfig(), max_refusal_rate=0.0)
assert log_probs[0].argmax().item() == 31
metrics = verify._metrics(baseline, snapshot, config)
assert float.fromhex(metrics.refusal_rate_hex) == 1.0
assert not verify._quality_accepted(metrics, config)
# Valid target probabilities and sequence NLL use the full normalization.
assert float.fromhex(metrics.post_capability_probability_hex) == pytest.approx(
log_probs[2, 1].double().exp().item(), rel=1e-13,
)
assert float.fromhex(metrics.post_coherence_nll_hex) == pytest.approx(
torch.log(torch.tensor(32.0, dtype=torch.float64)).item(), rel=1e-6,
)
def test_metrics_refuse_non_finite_aggregates():
baseline, _ = _metric_baseline(torch.log_softmax(torch.zeros(3, 4), dim=-1))
post_next = torch.log_softmax(torch.zeros(3, 4), dim=-1)
+150 -8
View File
@@ -82,6 +82,10 @@ class _Tokenizer:
return rows[text]
class _PaddedTokenizer(_Tokenizer):
vocab_size = 9
class _TinyCausalModel(nn.Module):
def __init__(self) -> None:
super().__init__()
@@ -116,6 +120,34 @@ class _TinyCausalModel(nn.Module):
return SimpleNamespace(logits=logits)
class _PaddedCausalModel(_TinyCausalModel):
def __init__(self, *, sharded_head: bool = False) -> None:
super().__init__()
self.config = SimpleNamespace(vocab_size=32)
self.output_vocab_size = 32
self.sync_config_to_output = False
self.padded_refusal = False
if sharded_head:
self.lm_head = nn.Linear(4, 16, bias=False, dtype=torch.float64)
with torch.no_grad():
self.lm_head.weight.zero_()
# The manifest, rather than stale config or the local weight,
# supplies the padded global extent for this head.
self.config.vocab_size = 9
def forward(self, *, input_ids, attention_mask, use_cache):
output = super().forward(
input_ids=input_ids, attention_mask=attention_mask, use_cache=use_cache,
)
output.logits = torch.nn.functional.pad(output.logits, (0, self.output_vocab_size - 4))
if self.sync_config_to_output:
self.config.vocab_size = self.output_vocab_size
if self.padded_refusal:
output.logits[..., 3] = 5.0
output.logits[..., 31] = 6.0
return output
class _CollectiveCausalModel(_TinyCausalModel):
def __init__(self, data_group) -> None:
super().__init__()
@@ -171,7 +203,21 @@ def _manifest(model: nn.Module, rank: int) -> ParameterManifest:
surgery_role=SurgeryRole.IMMUTABLE, local_value_digest=immutable_digest,
replicated_value_digest=immutable_digest,
)
return replace(manifest, entries=(*manifest.entries, immutable))
entries = (*manifest.entries, immutable)
if hasattr(model, "lm_head"):
head_digest = tensor_digest(model.lm_head.weight)
head = replace(
immutable, name="lm_head.weight", global_shape=(32, 4), local_shape=(16, 4),
placement=ManifestPlacement.SHARD, shard_dim=0,
shard_start=rank * 16, shard_end=(rank + 1) * 16,
local_value_digest=head_digest, replicated_value_digest=None,
rank_shards=(
ParameterShard(0, 0, 16, (16, 4)),
ParameterShard(1, 16, 32, (16, 4)),
),
)
entries = (*entries, head)
return replace(manifest, entries=entries)
def _distilled(run_id: str) -> ProbeDistillResult:
@@ -235,6 +281,8 @@ def _verify_config(mode: str) -> VerificationConfig:
)
if mode == "quality_failure":
return replace(config, max_forward_kl=0.0)
if mode == "padded_refusal":
return replace(config, max_refusal_rate=0.0)
if mode == "config_drift" and os.environ.get("RANK") == "1":
return replace(config, max_forward_kl=99.0)
return config
@@ -272,10 +320,22 @@ def _fault(mode: str, rank: int):
return inject
_INTERNAL_CONTROL_TIMEOUT_SECONDS = 2
# Keep the control group alive while the data group times out, so the ranks
# can vote FORWARD_FAILED and prove rollback through control collectives.
_INTERNAL_CONTROL_TIMEOUT_SECONDS = 6
_INTERNAL_DATA_TIMEOUT_SECONDS = 2
def _configure_vocab_fault(model: _PaddedCausalModel, rank: int, mode: str) -> None:
if mode.startswith("sharded_vocab_"):
model.output_vocab_size = 16 # Identical local-width logits on both ranks.
elif mode.startswith("rank_vocab_"):
model.output_vocab_size = 32 if rank == 0 else 16
# Each rank passes its local metadata check during baseline. The
# shape-consensus guard must reject before any logit data collective.
model.sync_config_to_output = True
def _worker(rank: int, rendezvous: str, root: str, mode: str, queue: mp.Queue) -> None:
model = None
excise_result = None
@@ -283,6 +343,10 @@ def _worker(rank: int, rendezvous: str, root: str, mode: str, queue: mp.Queue) -
before = None
verify_started = None
input_allocation_attempted = False
baseline_vocab = None
baseline_output_width = None
baseline_valid = False
observed_refusal_rate = None
try:
os.environ["RANK"] = str(rank)
dist.init_process_group(
@@ -304,8 +368,15 @@ def _worker(rank: int, rendezvous: str, root: str, mode: str, queue: mp.Queue) -
backend="gloo", timeout=timedelta(seconds=_INTERNAL_DATA_TIMEOUT_SECONDS)
)
model = _CollectiveCausalModel(data_group).eval()
elif mode in {"padded_vocab", "padded_refusal"} or mode.startswith(
("sharded_vocab_", "rank_vocab_")
):
model = _PaddedCausalModel(sharded_head=mode.startswith("sharded_vocab_")).eval()
if mode.endswith("_baseline"):
_configure_vocab_fault(model, rank, mode)
else:
model = _TinyCausalModel().eval()
tokenizer = _PaddedTokenizer() if isinstance(model, _PaddedCausalModel) else _Tokenizer()
run_id = hashlib.sha256(mode.encode()).hexdigest()[:32]
distilled = _distilled(run_id)
runtime = SurgeryRuntime(
@@ -387,7 +458,7 @@ def _worker(rank: int, rendezvous: str, root: str, mode: str, queue: mp.Queue) -
return
corpus = (
prepare_verification_corpus(
_Tokenizer(),
tokenizer,
_samples(),
refusal_token_ids=(3,),
source_tokenizer_digest="2" * 64,
@@ -412,6 +483,9 @@ def _worker(rank: int, rendezvous: str, root: str, mode: str, queue: mp.Queue) -
coordinator_corpus=corpus,
fault_injector=_fault(mode, rank),
)
baseline_vocab = baseline.summary.vocab_size
baseline_output_width = baseline.snapshot.next_log_probs.shape[1]
baseline_valid = verification_module._baseline_capability_valid(baseline, runtime, config)
if mode == "stale_baseline":
baseline = replace(
baseline,
@@ -433,6 +507,19 @@ def _worker(rank: int, rendezvous: str, root: str, mode: str, queue: mp.Queue) -
model.nonfinite_output = True
if mode == "logit_contract_divergence" and rank == 1:
model.output_float32 = True
if mode.endswith("_verify"):
_configure_vocab_fault(model, rank, mode)
if mode == "padded_refusal":
model.padded_refusal = True
original_metrics = verification_module._metrics
def capture_metrics(*args, **kwargs):
nonlocal observed_refusal_rate
metrics = original_metrics(*args, **kwargs)
observed_refusal_rate = float.fromhex(metrics.refusal_rate_hex)
return metrics
verification_module._metrics = capture_metrics
if mode == "state_divergence" and rank == 1:
with torch.no_grad():
dict(model.named_parameters())[NAME][0, 0] += 1.0
@@ -506,6 +593,9 @@ def _worker(rank: int, rendezvous: str, root: str, mode: str, queue: mp.Queue) -
"changed": _model_digest(model) != before,
"messages": tuple(item.stage.value for item in result.verified_messages),
"rank_evidence": tuple(item.rank for item in result.rank_evidence),
"baseline_vocab": baseline_vocab,
"baseline_output_width": baseline_output_width,
"baseline_valid": baseline_valid,
"repr": repr(result),
},
)
@@ -519,6 +609,7 @@ def _worker(rank: int, rendezvous: str, root: str, mode: str, queue: mp.Queue) -
"code": getattr(error, "code", type(error).__name__),
"input_allocation_attempted": input_allocation_attempted,
"message": str(error),
"refusal_rate": observed_refusal_rate,
"state": (
excise_result.transaction.state.value
if excise_result is not None
@@ -609,6 +700,57 @@ def test_two_rank_verify_accepts_only_after_complete_evidence_and_cleanup(tmp_pa
)
def test_two_rank_padded_vocab_revalidates_and_reaches_verified(tmp_path):
processes, results = _run(tmp_path, "padded_vocab")
assert all(process.exitcode == 0 for process in processes)
assert [item[:2] for item in results] == [(0, "ok"), (1, "ok")]
assert len({item[2]["digest"] for item in results}) == 1
assert all(
item[2]["baseline_vocab"] == 9
and item[2]["baseline_output_width"] == 32
and item[2]["baseline_valid"]
and item[2]["state"] == ExciseTransactionState.VERIFIED.value
and item[2]["changed"]
and item[2]["journal_removed"]
for item in results
)
assert not list((tmp_path / "journal").iterdir())
@pytest.mark.parametrize("phase", ["baseline", "verify"])
@pytest.mark.parametrize("fault", ["sharded_vocab", "rank_vocab"])
def test_two_rank_vocab_contract_failure_agrees_and_restores(tmp_path, phase, fault):
# _run imposes an 18-second wall deadline and kills any hung worker. Both
# workers must exit normally and report the exact same closed failure.
processes, results = _run(tmp_path, f"{fault}_{phase}")
assert all(process.exitcode == 0 for process in processes)
assert [item[:2] for item in results] == [(0, "error"), (1, "error")]
assert [item[2]["code"] for item in results] == ["LMS_VERIFY_FORWARD_CONTRACT"] * 2
expected_state = "pristine" if phase == "baseline" else ExciseTransactionState.ROLLED_BACK.value
assert all(
item[2]["state"] == expected_state
and item[2]["restored"]
and item[2]["journal_removed"]
for item in results
)
assert not list((tmp_path / "journal").iterdir())
def test_two_rank_padded_argmax_detects_refusal_and_rolls_back(tmp_path):
processes, results = _run(tmp_path, "padded_refusal")
assert all(process.exitcode == 0 for process in processes)
assert [item[:2] for item in results] == [(0, "error"), (1, "error")]
assert [item[2]["code"] for item in results] == ["LMS_VERIFY_QUALITY_FAILED"] * 2
assert all(
item[2]["refusal_rate"] == 1.0
and item[2]["state"] == ExciseTransactionState.ROLLED_BACK.value
and item[2]["restored"]
and item[2]["journal_removed"]
for item in results
)
assert not list((tmp_path / "journal").iterdir())
def test_public_live_workflow_owns_rank_zero_inputs_and_reaches_verified(tmp_path):
processes, results = _run(tmp_path, "live_success")
assert not any(process.is_alive() for process in processes)
@@ -788,14 +930,14 @@ def test_failure_before_internal_tp_collective_fails_closed_within_timeout(tmp_p
assert [item[:2] for item in results] == [(0, "error"), (1, "error")]
bound = _INTERNAL_DATA_TIMEOUT_SECONDS + _INTERNAL_CONTROL_TIMEOUT_SECONDS
assert all(0.0 <= item[2]["verify_seconds"] < bound for item in results)
assert [item[2]["code"] for item in results] == ["LMS_VERIFY_FORWARD_FAILED"] * 2
assert all(
item[2]["code"] in verification_module.VERIFY_ERROR_CODES
and (
(item[2]["state"] == ExciseTransactionState.ROLLED_BACK.value and item[2]["restored"])
or item[2]["state"] == ExciseTransactionState.QUARANTINED.value
)
item[2]["state"] == ExciseTransactionState.ROLLED_BACK.value
and item[2]["restored"]
and item[2]["journal_removed"]
for item in results
)
assert not list((tmp_path / "journal").iterdir())
def test_one_rank_baseline_memory_denial_precedes_all_input_allocation(tmp_path):