Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
5ef165a
Fix NoKvSlot crashes: disable wasted SWA cache, margin the token-budg…
hardcoreerik Jul 4, 2026
4542e1d
Address Grok adversarial review of the NoKvSlot fix
hardcoreerik Jul 4, 2026
3fb2781
Fix Run-CF7GateExpanded.ps1 crashing when exactly one GGUF model is p…
hardcoreerik Jul 4, 2026
28f881f
Force role-executor recycle on first NoKvSlot instead of waiting for …
hardcoreerik Jul 6, 2026
d2d5219
Revert SwaFull=false: shrinks SWA cache below what Context Fabric's p…
hardcoreerik Jul 6, 2026
6e1f1a8
Root-cause and document the Gemma-4 NoKvSlot investigation; flag Gemm…
hardcoreerik Jul 6, 2026
5fd6ad3
Tier 1 retrieval fix: anchor-phrase ranking + coverage-aware evidence…
hardcoreerik Jul 7, 2026
f91afc4
Address CodeRabbit findings on the NoKvSlot retry/degrade path
hardcoreerik Jul 7, 2026
80e721d
Log Tier 1 validation results: 31->45 pass rate, B3 beats B2 for the …
hardcoreerik Jul 7, 2026
6d28071
Tier 1.5 retrieval fix: unordered proximity-pair anchors for inverted…
hardcoreerik Jul 7, 2026
e8fa139
Log Tier 1.5 validation: 45->56 pass rate, Paraphrased pure-misses 13->3
hardcoreerik Jul 7, 2026
9d71c5a
Tier 2 retrieval fix: truncate dense cards instead of rejecting them
hardcoreerik Jul 8, 2026
1b45178
Address CodeRabbit nitpicks: consolidate margin constant + fix report…
hardcoreerik Jul 8, 2026
cc79288
@
hardcoreerik Jul 8, 2026
1598329
CF bench: print per-candidate depot verdicts + disabled GGUFs on pref…
hardcoreerik Jul 8, 2026
e16edb1
Log HARDCORELAPTOPMSI Tier 2 validation: qwen 26->30/100, citation 77…
hardcoreerik Jul 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions OrchestratorIDE.UnitTests/ContextFabricEvidencePackTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,109 @@ public void BuildExhaustiveAnswer_Path_IsUnaffectedByEvidencePackChange()

Assert.That(pack.IncludedSegmentIds, Does.Contain("seg-a"));
}

// ── Tier 1 anchor-phrase retrieval (CF_RETRIEVAL_IMPROVEMENT_PLAN.md) ────────────────────

[Test]
public void BuildEvidencePack_PrefersPhraseMatch_OverUnigramEntityCollision()
{
// The measured production failure mode: 63/105 cards contained both "station" and
// "alpha" as separate words for a question about Station Alpha, tying on unigram score
// with the 3 cards containing the contiguous phrase. Segment IDs are chosen so the OLD
// ordinal tie-break would pick a collision card -- only phrase-aware ranking passes.
var collision1 = Card("seg-aaa", "Routine checks.",
"Station Cairn was inspected and no unusual activity was noted near Chapter Alpha.");
var collision2 = Card("seg-bbb", "Routine checks.",
"Station Kestrel closed its entry while Beacon Alpha reported scheduled maintenance.");
var target = Card("seg-zzz", "Designation noted.",
"The recorded designation for Station Alpha was BR-048.");
var question = new FabricBenchmarkQuestion(
"q-anchor-1", FabricQuestionKind.LocalFact,
"What was the recorded designation for Station Alpha during this cycle?",
["BR-048"], ["seg-zzz"]);

var runner = new ContextFabricFeasibilityRunner(new ScriptedFabricRuntime(), FabricRunOptions.Default);
var pack = runner.BuildEvidencePack(question, [collision1, collision2, target], null);

Assert.That(pack.IncludedSegmentIds[0], Is.EqualTo("seg-zzz"),
"the card containing the literal phrase 'Station Alpha' must rank first");
}

[Test]
public void BuildEvidencePack_PrefersVerbatimIdentifier_OverIdentifierFragments()
{
// The tokenizer splits "BR-048" into {br, 048}, so a card mentioning a DIFFERENT BR
// identifier plus the number 048 in another role ties with the real match on unigrams.
// Segment IDs chosen so the old tie-break picks the fragment card.
var fragments = Card("seg-aaa", "Side note.",
"Registry BR-121 logged the value 048 in a side note for the recorded designation file.");
var target = Card("seg-zzz", "Designation noted.",
"The recorded designation was BR-048 for this cycle.");
var question = new FabricBenchmarkQuestion(
"q-anchor-2", FabricQuestionKind.LocalFact,
"What was recorded for designation BR-048?", ["BR-048"], ["seg-zzz"]);

var runner = new ContextFabricFeasibilityRunner(new ScriptedFabricRuntime(), FabricRunOptions.Default);
var pack = runner.BuildEvidencePack(question, [fragments, target], null);

Assert.That(pack.IncludedSegmentIds[0], Is.EqualTo("seg-zzz"),
"the card containing the verbatim identifier 'BR-048' must rank first");
}

[Test]
public void BuildEvidencePack_CoversSecondEntity_BeforeStackingDuplicatesOfFirst()
{
// Coverage-aware fill: a MultiHop question naming two identifiers must include a card
// for EACH before a near-duplicate of the higher-scoring one. IncludedSegmentIds is in
// pick order, so the second pick must be the second entity's card even though the
// duplicate of the first entity has a higher standalone score.
var ck1 = Card("seg-ck1", "Checksum.", "Checksum CK-086 matched the shipment ledger record.");
var ck2 = Card("seg-ck2", "Checksum.", "Checksum CK-086 was archived after the shipment closed.");
var rpt = Card("seg-rpt", "Report.", "Report RPT-064 was filed covering the shipment.");
var question = new FabricBenchmarkQuestion(
"q-anchor-3", FabricQuestionKind.MultiHop,
"How does report RPT-064 relate to checksum CK-086?", ["RPT-064", "CK-086"],
["seg-rpt", "seg-ck1"]);

var runner = new ContextFabricFeasibilityRunner(new ScriptedFabricRuntime(), FabricRunOptions.Default);
var pack = runner.BuildEvidencePack(question, [ck1, ck2, rpt], null);

Assert.That(pack.IncludedSegmentIds.Take(2), Is.EquivalentTo(new[] { "seg-ck1", "seg-rpt" }),
"the first two picks must cover both question entities, not duplicate one");
}

[Test]
public void ExtractAnchorPhrases_FindsIdentifiersAndProperNounRuns_TrimmingQuestionOpeners()
{
var anchors = ContextFabricFeasibilityRunner.ExtractAnchorPhrases(
"Which Depot Fathom entries reference case-ledger-01 or CHN-112-0-1-2?");

Assert.Multiple(() =>
{
Assert.That(anchors, Does.Contain("Depot Fathom"),
"the question opener 'Which' must be trimmed, not swallow the entity run");
Assert.That(anchors, Does.Contain("case-ledger-01"));
Assert.That(anchors, Does.Contain("CHN-112-0-1-2"));
Assert.That(anchors, Does.Not.Contain("Which Depot Fathom"));
});
}

[Test]
public void BuildEvidencePack_WithNoExtractableAnchors_StillRanksByUnigramIdf()
{
// Questions with no identifiers or proper-noun runs must degrade exactly to the prior
// unigram-IDF behavior (anchor keys all zero).
var target = Card("seg-target", "Checksum recorded.",
"The archive recorded the checksum for this unusual shipment yesterday.");
var distractor = Card("seg-distractor", "General narration.",
"The depot log was reviewed and the records were unchanged.");
var question = new FabricBenchmarkQuestion(
"q-anchor-4", FabricQuestionKind.LocalFact,
"What checksum was recorded for the unusual shipment?", ["checksum"], ["seg-target"]);

var runner = new ContextFabricFeasibilityRunner(new ScriptedFabricRuntime(), FabricRunOptions.Default);
var pack = runner.BuildEvidencePack(question, [target, distractor], null);

Assert.That(pack.IncludedSegmentIds[0], Is.EqualTo("seg-target"));
}
}
31 changes: 31 additions & 0 deletions OrchestratorIDE.UnitTests/ContextFabricExhaustiveAnswerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,35 @@ public void BuildExhaustiveAnswer_IncludesEveryMatchingClaim_WhenOneCardListsMul
Assert.That(result.Answer?.Answer, Does.Contain("CASE-01-1"));
});
}

[Test]
public void BuildExhaustiveAnswer_MatchesIdentifierVerbatim_NotItsNumericFragment()
{
// Tier 1c (CF_RETRIEVAL_IMPROVEMENT_PLAN.md): "grade-20" tokenizes to {grade, 20}, and
// the rarest-unigram heuristic then admits ANY claim containing the token "20" -- here, a
// decoy about "20 crates" under a different grade. Verbatim identifier matching must
// include only the true grade-20 claims.
var target1 = Card("seg-g20-a", "Outpost Vantage was assigned grade-20 with marker G20A in the survey.");
var target2 = Card("seg-g20-b", "Outpost Thistle was assigned grade-20 with marker G20B in the survey.");
var decoy = Card("seg-dec", "Outpost Marrow was assigned grade-4 and stored 20 crates with marker DECOY in the survey.");
var fillers = Enumerable.Range(5, 5)
.Select(i => Card($"seg-g{i}", $"Outpost Grove was assigned grade-{i} with marker G{i}X in the survey."))
.ToArray();
var allCards = new[] { target1, target2, decoy }.Concat(fillers).ToArray();
var corpus = Corpus(allCards.Select(c => c.SegmentId).ToArray());
var question = new FabricBenchmarkQuestion(
"q-5", FabricQuestionKind.Exhaustive,
"List every outpost assigned grade-20 in the survey.",
["G20A", "G20B"], ["seg-g20-a", "seg-g20-b"]);

var runner = new ContextFabricFeasibilityRunner(new ScriptedFabricRuntime(), FabricRunOptions.Default);
var result = runner.BuildExhaustiveAnswer(corpus, question, allCards);

Assert.Multiple(() =>
{
Assert.That(result.Answer?.Answer, Does.Contain("G20A"));
Assert.That(result.Answer?.Answer, Does.Contain("G20B"));
Assert.That(result.Answer?.Answer, Does.Not.Contain("DECOY"));
});
}
}
8 changes: 6 additions & 2 deletions OrchestratorIDE.UnitTests/ModelAdmissionGateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,17 @@ public void ContextFabric_Keeps_Reasoning_Tuned_Model_Provisional()
}

[Test]
public void ContextFabric_Admits_Gemma4_When_Size_Clears_The_Gate()
public void ContextFabric_Downgrades_Gemma4_Despite_Size_Due_To_Known_NoKvSlot_Issue()
{
// Gemma 4's shared-KV-cache architecture hits native NoKvSlot on Context Fabric's
// evidence-heavy prompts regardless of size (docs/CONTEXT_FABRIC_TEST_HARNESS.md §7a) --
// a known, currently-unpatched upstream llama.cpp limitation, not fixable in our own
// code. Size alone is no longer sufficient for Admitted status on this family.
var decision = ModelAdmissionGate.Evaluate(
Asset("gemma-4-12B-it-qat-q4_0.gguf"),
RuntimeWorkloadKind.ContextFabricReader);

Assert.That(decision.Verdict, Is.EqualTo(ModelAdmissionVerdict.Admitted));
Assert.That(decision.Verdict, Is.EqualTo(ModelAdmissionVerdict.Provisional));
}

[Test]
Expand Down
60 changes: 57 additions & 3 deletions OrchestratorIDE/Core/Runtime/AdapterManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,21 @@ private async Task<TrackedConversation> GetOrCreateConversationAsync(
// the threshold's margin below the hard cap absorbs that delay — but only up
// to SequenceHardLimit, where we fail closed with a managed exception rather
// than letting the next mint trip the fatal native assert.
//
// ForceRecycle overrides the threshold entirely: a NoKvSlot on this role (see
// MarkForRecycle) is evidence the pool is already degraded (100-question CF-7
// runs showed near-universal NoKvSlot failure after the first one on an
// executor, not a slow climb toward SequenceRecycleThreshold — consistent with
// disposed conversations not fully returning their cells before the next one
// claims them). Recycling immediately, rather than waiting up to 23 more
// conversations, gives every subsequent conversation a genuinely empty pool
// instead of one still degraded by the conversation that just failed.
var minted = existing.ConversationsCreated;
if (minted < SequenceRecycleThreshold || existing.ActiveCount > 0)
var recycleNow = existing.ForceRecycle
? existing.ActiveCount == 0
: minted >= SequenceRecycleThreshold && existing.ActiveCount == 0;

if (!recycleNow)
{
if (minted >= SequenceHardLimit)
throw new InvalidOperationException(
Expand All @@ -147,13 +160,14 @@ private async Task<TrackedConversation> GetOrCreateConversationAsync(
LogKvDiagnostic(
$"role={binding.Role} served-without-recycle minted={minted} " +
$"activeCount={existing.ActiveCount} threshold={SequenceRecycleThreshold} " +
$"reason={(minted < SequenceRecycleThreshold ? "under-threshold" : "active-conversations-outstanding")}");
$"forceRecycle={existing.ForceRecycle} reason=" +
$"{(existing.ForceRecycle ? "force-recycle-deferred-active" : minted < SequenceRecycleThreshold ? "under-threshold" : "active-conversations-outstanding")}");
return existing.CreateTrackedConversation();
}

LogKvDiagnostic(
$"role={binding.Role} RECYCLING minted={minted} activeCount={existing.ActiveCount} " +
$"threshold={SequenceRecycleThreshold}");
$"threshold={SequenceRecycleThreshold} forced={existing.ForceRecycle}");
_entries.Remove(binding.Role);
// Best-effort, same contract as the stale-binding teardown below: the entry is
// already untracked, so a disposal fault must not block the replacement build.
Expand Down Expand Up @@ -254,6 +268,35 @@ private static bool BindingMatchesCore(RuntimeRoleBinding a, RuntimeRoleBinding
string.Equals(a.BaseModel.Path, b.BaseModel.Path, StringComparison.OrdinalIgnoreCase) &&
string.Equals(a.Adapter?.Path, b.Adapter?.Path, StringComparison.OrdinalIgnoreCase);

/// <summary>
/// Marks the given role's current executor (if any) as degraded, so the next
/// GetOrCreateConversationAsync call for it recycles as soon as the role is idle
/// (ActiveCount == 0) instead of waiting for SequenceRecycleThreshold. Called by
/// IRoleRuntime as soon as it observes a NoKvSlot on a role's conversation — see the
/// ForceRecycle doc comment on RoleEntry for why. A no-op if the role has no tracked entry
/// (already recycled/never built) or the binding has since changed; either way there is
/// nothing degraded left to mark. Fire-and-forget from the caller's perspective is fine:
/// this only ever narrows a future recycle decision, never anything already in flight.
/// </summary>
public async Task MarkForRecycle(RuntimeRole role)
{
// No CancellationToken by design: the observation "this executor produced a NoKvSlot"
// remains true whether or not the observing request is being cancelled, and honoring a
// cancelled token here would let the degraded executor be silently reused by the NEXT
// request (CodeRabbit finding, 2026-07-06). The gate wait is bounded in practice by the
// longest gate hold (one executor build, seconds at worst).
await _gate.WaitAsync().ConfigureAwait(false);
try
{
if (_entries.TryGetValue(role, out var entry))
entry.ForceRecycle = true;
}
finally
{
_gate.Release();
}
}

public async ValueTask DisposeAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
Expand Down Expand Up @@ -283,10 +326,21 @@ private sealed class RoleEntry(BatchedExecutor executor, LoraAdapter? lora, Runt
{
private int _activeCount;
private int _conversationsCreated;
private volatile bool _forceRecycle;

public RuntimeRoleBinding Binding { get; } = binding;
public int ActiveCount => Volatile.Read(ref _activeCount);

/// <summary>Set by <see cref="AdapterManager.MarkForRecycle"/> when a NoKvSlot on this
/// role's executor indicated the pool is already degraded. Read by the recycle check in
/// GetOrCreateConversationAsync; never cleared explicitly — recycling replaces the whole
/// RoleEntry, so a fresh one always starts false.</summary>
public bool ForceRecycle
{
get => _forceRecycle;
set => _forceRecycle = value;
}

/// <summary>Total conversations ever minted by this entry's executor — each consumed a
/// native sequence slot that is never returned (see SequenceRecycleThreshold).</summary>
public int ConversationsCreated => Volatile.Read(ref _conversationsCreated);
Expand Down
46 changes: 43 additions & 3 deletions OrchestratorIDE/Core/Runtime/IRoleRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ private async IAsyncEnumerable<string> StreamRoleCompletionCoreAsync(
var outputBuilder = new StringBuilder();

conversation.Prompt(prompt, addBos: true, special: true);
await InferUntilReadyAsync(conversation, ct).ConfigureAwait(false);
await InferUntilReadyAsync(conversation, role, ct).ConfigureAwait(false);

for (var i = 0; i < Math.Max(0, maxTokens); i++)
{
Expand All @@ -272,7 +272,7 @@ private async IAsyncEnumerable<string> StreamRoleCompletionCoreAsync(
}

conversation.Prompt(token);
await InferUntilReadyAsync(conversation, ct).ConfigureAwait(false);
await InferUntilReadyAsync(conversation, role, ct).ConfigureAwait(false);
}

var elapsed = DateTime.UtcNow - started;
Expand Down Expand Up @@ -313,14 +313,54 @@ private async IAsyncEnumerable<string> StreamRoleCompletionCoreAsync(
onToolCall(tc);
}

private static async Task InferUntilReadyAsync(LLama.Batched.Conversation conversation, CancellationToken ct)
private async Task InferUntilReadyAsync(
LLama.Batched.Conversation conversation, RuntimeRole role, CancellationToken ct)
{
var passes = 0;
var noKvSlotRetries = 0;
while (conversation.RequiresInference)
{
var result = await conversation.Executor.Infer(ct).ConfigureAwait(false);
if (result == DecodeResult.NoKvSlot)
{
// A 100-question CF-7 gate run (docs/CONTEXT_FABRIC_TEST_HARNESS.md §7) showed
// NoKvSlot recurring on ~all subsequent conversations once it first occurred on a
// role's executor -- evidence the pool stays degraded rather than a single
// oversized prompt being the whole story. Mark the role for AdapterManager to
// recycle its executor at the next opportunity (fresh, empty pool) as soon as
// NoKvSlot is seen at all, not just when we give up retrying -- even a
// retry-recovered hit is evidence of degradation worth not compounding further.
// Deliberately NOT passed this request's cancellation token: the mark must
// survive the request being cancelled, or the degraded executor gets reused by
// the next request (CodeRabbit finding, 2026-07-06). Cancellation still
// propagates promptly via the Task.Delay below.
await _orchestrator.MarkRoleDegraded(role).ConfigureAwait(false);

// LLamaSharp documents this as retryable (BatchedExecutor.Infer requeues the
// batch internally rather than consuming it): "there is not enough memory for
// inference, try disposing some conversation threads and running inference
// again." A few cells may free up as other conversations finish disposing --
// give that a bounded chance before failing hard. This is defense-in-depth only;
// it cannot rescue a conversation whose own prompt alone overflows the KV pool --
// that case is expected to still fail here after exhausting retries, just ~1.8s
// later with a diagnostic trail (THEORC_KVCACHE_DIAGNOSTICS=1) instead of
// silently on the first hit.
const int maxNoKvSlotRetries = 8;
if (noKvSlotRetries >= maxNoKvSlotRetries)
throw new InvalidOperationException(
$"Native inference failed while draining a prompt batch: {result} (gave up after {noKvSlotRetries} retries).");
noKvSlotRetries++;
if (Environment.GetEnvironmentVariable("THEORC_KVCACHE_DIAGNOSTICS") == "1")
Console.WriteLine($"[KV-DIAG] NoKvSlot retry {noKvSlotRetries}/{maxNoKvSlotRetries}");
await Task.Delay(TimeSpan.FromMilliseconds(50 * noKvSlotRetries), ct).ConfigureAwait(false);
continue;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (result != DecodeResult.Ok)
throw new InvalidOperationException($"Native inference failed while draining a prompt batch: {result}.");
// A successful decode ends the current NoKvSlot episode: the cap bounds CONSECUTIVE
// failures, not the lifetime total, so a long drain with separately-recovered
// episodes isn't failed by their sum (CodeRabbit finding, 2026-07-04).
noKvSlotRetries = 0;
if (++passes > 1024)
throw new InvalidOperationException("Native inference did not drain the pending prompt batch.");
}
Expand Down
Loading
Loading