feat(safety): decode-time safety control loop with checkpointed rollback (ADR-012)#5
Merged
Merged
Conversation
…ack (ADR-012) Wrap the ADR-005 per-token steering in a recoverable, on-device control loop that catches unsafe drift mid-generation and rewinds to the last safe prefix, instead of treating safety as a one-shot per-token gate. Core primitives (el-safety): - ChunkGuard / SafetyScore: deterministic, float-free risk scoring of recent output (integer milli-units). - RollbackPolicy: tier-aware cadence + bounds (guard_every, soft/hard thresholds, max_rollbacks, max_checkpoints). - CheckpointManager / Checkpoint: bounded ring of safe-prefix snapshots (offsets only; KV payload never copied). Runtime control loop (el-runtime): - InferenceSession::generate_with_policy drives grammar mask -> safety adjust -> sample -> commit, captures a checkpoint at each guard-verified-safe boundary, scores every guard_every tokens, and on a hard breach rolls KV + output back to the last safe checkpoint, banning the divergence token. - Mandatory final guard check before EOS / max_tokens termination, so a tail shorter than guard_every (or an unsafe completion ending in EOS) is never returned unscored. - Bounded, fail-closed: rollbacks capped; on exhaustion or under memory pressure (no checkpoint) the loop refuses deterministically. - el-memory: KvRegion::truncate -- O(dropped) descriptor rewind, no replay. Engine rollback contract: - InferenceEngine::rollback is required (no default), so no engine can silently resume on a stale KV cache (fail-open). Stateless engines implement a no-op; QwenEngine (candle) rebuilds the safe prefix by replaying the prompt from index_pos 0 (candle exposes no in-place cache truncation). Docs: ADR-012, Safety DDD context + domain events, el-safety README, and the supporting SecDecoding research. Selective soft-steering over an early-token window is documented as a deferred SecDecoding follow-up, not current behavior. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements ADR-012 — a layered decode-time safety control loop with checkpointed rollback. ADR-005 decided which safety mode runs and where the
LogitAdjustmentsits in a decode step; it did not decide how steering recovers once generation has drifted unsafe. This PR wraps that per-token steering in a recoverable, fully on-device (air-gapped) control loop that catches unsafe drift mid-generation and rewinds to the last safe prefix.What's included
Core safety primitives (
el-safety)ChunkGuard/SafetyScore— deterministic, float-free risk scoring of recent output (integer milli-units).RollbackPolicy— tier-aware cadence and bounds (guard_every, soft/hard thresholds,max_rollbacks,max_checkpoints).CheckpointManager/Checkpoint— bounded ring of safe-prefix snapshots; offsets only, KV payload never copied.Runtime control loop (
el-runtime)InferenceSession::generate_with_policypreserves the invariant ordergrammar mask → safety adjust → sample → commit, checkpoints at each guard-verified-safe boundary, scores everyguard_everytokens, and on a hard-threshold breach rolls KV and output back to the last safe checkpoint — banning the divergence token so the resumed decode diverges.max_tokenstermination, so a tail shorter thanguard_every(or an unsafe completion ending in EOS) can never be returned unscored.el-memory::KvRegion::truncate—O(dropped)descriptor rewind, no payload copy.Engine rollback contract
InferenceEngine::rollbackis required (no default) so no engine can silently resume on a stale KV cache (fail-open). Stateless engines implement a no-op;QwenEngine(candle) rebuilds the safe prefix by replaying the prompt fromindex_pos 0, since candle 0.8.4 exposes no in-place cache truncation.Docs
ADR-012, updated Safety DDD context + domain events,el-safetyREADME, and the supporting SecDecoding research that motivates the design.SecDecodingfollow-up, not current behavior.Cost model note
The session-layer rollback is
O(dropped)and replay-free. The engine-layer cost is adapter-dependent: stateless engines areO(1), but an append-only-cache transformer (candle/QwenEngine) replays prompt + kept prefix per rollback — bounded bymax_rollbacks. ADR-012's "Consequences" documents this explicitly.Testing
cargo test --workspace— all green (77 tests; el-runtime 15, el-engine-candle 14, el-safety 6, …).cargo clippy --all-targetsandcargo fmt --all --checkclean.max_tokensguard-bypass, terminal-breach rollback recovery, and the session→engine rollback propagation (stateful mock engine mirroringQwenEngine's KV hazard).🤖 Generated with Claude Code