diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index 364fd4e5..a59087b0 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -1055,13 +1055,9 @@ private async Task CompleteTurnAsync( _events.RaiseDiagnostic(CallEventKind.EmptyReply, _time.GetUtcNow(), turn.Index); } - // §7's ask is charged only for a turn whose own words reached the caller. The clarification - // rides an instruction injected before the run, so a run that ended in the fallback reply, or - // one moderation refused, never put the question — and a slot recorded as asked is silent for - // the rest of the call. if (failure is null && !refused) { - _clarifications.CommitAsks(); + _clarifications.CommitAsks(reply); } // What this turn adds to the transcript. It is built here and written at the end of the diff --git a/src/AgentCore.Application/Runtime/ClarificationText.cs b/src/AgentCore.Application/Runtime/ClarificationText.cs index 54f60454..903333ea 100644 --- a/src/AgentCore.Application/Runtime/ClarificationText.cs +++ b/src/AgentCore.Application/Runtime/ClarificationText.cs @@ -47,20 +47,21 @@ internal static string Instruction( { var confirm = first ? "One thing is not yet confirmed" : "Another thing is not yet confirmed"; return $"{confirm}: {description} Everything found is for {candidates[0]}. " - + "Ask the caller whether that is what they have before giving advice specific to it."; + + "Answer what the caller just said; where that calls for advice specific to it, ask the " + + "caller first whether that is what they have."; } var known = first ? "One thing is not yet known" : "Another thing is not yet known"; if (candidates.Count > maxCandidates) { - return $"{known}: {description} Ask the caller, and do not give advice specific to one until " - + "they answer."; + return $"{known}: {description} Answer what the caller just said; where that calls for advice " + + "specific to one, ask the caller first."; } - return $"{known}: {description} It is one of {JoinAlternatives(candidates)}. Ask the caller, and do " - + "not give advice that is specific to one until they answer. Anything that applies to all of " - + "them is still fair game."; + return $"{known}: {description} It is one of {JoinAlternatives(candidates)}. Answer what the caller " + + "just said; where that calls for advice specific to one, ask the caller which first. Anything " + + "that applies to all of them is still fair game."; } /// Renders channel 2's sentence: the probe's note, as a search result. diff --git a/src/AgentCore.Application/Runtime/Clarifications.cs b/src/AgentCore.Application/Runtime/Clarifications.cs index ab90d9f5..ef005ad2 100644 --- a/src/AgentCore.Application/Runtime/Clarifications.cs +++ b/src/AgentCore.Application/Runtime/Clarifications.cs @@ -101,9 +101,12 @@ internal void Ask(string name, LastNamed named, bool spendsReset) } } - /// Makes every ask this turn staged permanent (see ). - internal void CommitAsks() + /// Makes the asks this turn staged and put permanent (see ). + /// The words the caller heard, which decide which staged asks were put. + internal void CommitAsks(string reply) { + ArgumentNullException.ThrowIfNull(reply); + lock (_gate) { foreach (var state in _slots.Values) @@ -113,6 +116,11 @@ internal void CommitAsks() continue; } + if (!SpokenAsk.NamedIn(reply, ask.Named)) + { + continue; + } + state.LastNamed = ask.Named; state.NamedAsks = ask.NamedAsks; state.ResetSpent = ask.ResetSpent; diff --git a/src/AgentCore.Application/Runtime/SpokenAsk.cs b/src/AgentCore.Application/Runtime/SpokenAsk.cs new file mode 100644 index 00000000..f359b393 --- /dev/null +++ b/src/AgentCore.Application/Runtime/SpokenAsk.cs @@ -0,0 +1,41 @@ +using AgentCore.Application.State; + +namespace AgentCore.Application.Runtime; + +/// +/// Whether a turn's own reply actually put the question channel 1 staged for it. +/// +internal static class SpokenAsk +{ + /// Whether put the question staged. + /// The words the caller heard. + /// What the staged ask offered. + /// + /// where the reply names one of the offered values. A record naming no + /// values — the over-cap form, whose instruction lists none — carries nothing to look for, so it + /// counts as asked rather than being dropped on every turn alike. + /// + internal static bool NamedIn(string reply, Clarifications.LastNamed named) + { + ArgumentNullException.ThrowIfNull(reply); + + if (named.Kind != Clarifications.LastNamedKind.Set || named.Values is not { } values) + { + return true; + } + + var folded = VocabularyFold.Fold(reply); + + foreach (var value in values) + { + var candidate = VocabularyFold.Fold(value); + + if (candidate.Length > 0 && folded.Contains(candidate, StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } +} diff --git a/src/AgentCore.Application/State/ExactStateValueLinker.cs b/src/AgentCore.Application/State/ExactStateValueLinker.cs index ab74602b..f22680c6 100644 --- a/src/AgentCore.Application/State/ExactStateValueLinker.cs +++ b/src/AgentCore.Application/State/ExactStateValueLinker.cs @@ -81,34 +81,24 @@ public LinkResult Link(string mention, VocabularyView vocabulary, IReadOnlySet - /// Every value whose normalised key has as a strict prefix, in the - /// collection's own spelling. + /// Every value whose normalised key has as a strict prefix and that + /// does not rule out, in the collection's own spelling. /// - /// - /// Under ordinal order every strict prefix extension of sorts after it - /// and the extensions are contiguous, so this is a binary search plus a walk over the matches - /// rather than a scan of the whole vocabulary. - /// - private static List PrefixedSiblings(VocabularyView vocabulary, string key) + private static List PrefixedSiblings( + VocabularyView vocabulary, string key, IReadOnlyList extensions) { var ordered = KeysInOrder.GetValue( vocabulary, @@ -120,12 +110,91 @@ private static List PrefixedSiblings(VocabularyView vocabulary, string k List siblings = []; for (; scan < ordered.Length && ordered[scan].StartsWith(key, StringComparison.Ordinal); scan++) { - siblings.Add(vocabulary.NormalisedToOriginal[ordered[scan]]); + if (!RuledOut(ordered[scan], key, extensions)) + { + siblings.Add(vocabulary.NormalisedToOriginal[ordered[scan]]); + } } return siblings; } + /// + /// Every candidate spelling the mention offers that begins where the matched value begins and + /// runs past its end — what the caller spelled around the hit, rather than what the collection + /// holds. + /// + /// Every spelling the mention admits, from . + /// The token spans the matched value was read from. + /// The extended spellings, each carrying the matched key as a strict prefix. + private static List Extensions( + Dictionary> candidates, + HashSet<(int Start, int End)> matched) + { + List extensions = []; + + foreach (var (key, spans) in candidates) + { + if (spans.Any(span => matched.Any(hit => hit.Start == span.Start && span.End > hit.End))) + { + extensions.Add(key); + } + } + + return extensions; + } + + /// + /// Whether the caller's own spelling rules this sibling out: they spelled a peer of the + /// sibling's own tail — as long, and of the same character class — that is not it. + /// + /// The sibling's normalised key. + /// The matched value's normalised key, a strict prefix of both sides. + /// What the caller spelled past the match. + /// to drop the sibling. + private static bool RuledOut(string sibling, string key, IReadOnlyList extensions) + { + var tail = sibling[key.Length..]; + var ruledOut = false; + + foreach (var extension in extensions) + { + // The caller is still spelling toward this sibling, so nothing they said rules it out — + // and no other extension of the same mention can overturn that. + if (sibling.StartsWith(extension, StringComparison.Ordinal)) + { + return false; + } + + ruledOut = ruledOut || IsPeer(extension[key.Length..], tail); + } + + return ruledOut; + } + + /// Whether two tails are alternatives: the same length, and both all numbers or both all letters. + private static bool IsPeer(string left, string right) + => left.Length == right.Length + && ((All(left, IsNumber) && All(right, IsNumber)) || (All(left, Rune.IsLetter) && All(right, Rune.IsLetter))); + + private static bool All(string text, Func predicate) + { + if (text.Length == 0) + { + return false; + } + + foreach (var rune in text.EnumerateRunes()) + { + if (!predicate(rune)) + { + return false; + } + } + + return true; + } + /// /// Discards a hit whose every span sits inside a span of some longer hit (K10) — tested per /// span, so different spans of one hit may be swallowed by different longer hits, and no longer diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionOffTopicTurnTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionOffTopicTurnTests.cs new file mode 100644 index 00000000..6e955e5e --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/CallSessionOffTopicTurnTests.cs @@ -0,0 +1,101 @@ +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Validation; +using AgentCore.Application.Runtime; +using AgentCore.Application.State; +using AgentCore.Application.Tests.Fakes; +using AgentCore.TestSupport; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// Channel 1 across a turn the caller spent on something else. The instruction rides every turn +/// after the near-tie, whatever that turn says, so the reply — not the injection — is what charges +/// the ask: a turn answered with sympathy rather than the question must leave the slot free to ask +/// on the next turn that calls for it. +/// +public sealed class CallSessionOffTopicTurnTests +{ + private const string AppliesToDescription = "The model, as printed on the machine."; + + private const string Yaml = + """ + apiVersion: agentcore/v1 + name: clarification-off-topic + state: + applies_to: + type: string + writer: extractor + description: "The model, as printed on the machine." + vocabulary: { from: knowledge } + extractor: + model: { ref: fill } + when: after_reply + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + knowledge: + kind: qdrant + collection: kb + fields: { body: text } + scope: + template: "facets.{key}" + fromState: [applies_to] + wildcard: { value: "*", facets: [applies_to] } + ambiguity: { maxCandidates: 6, maxAsks: 2 } + agents: + items: + - id: only + """; + + [Fact] + public async Task AnOffTopicTurn_DoesNotSpendTheQuestion() + { + using SequencedChatClient reply = new( + "I can help with that.", + """{"applies_to":"the CT900"}""", + "I'm sorry to hear that. What is going wrong?", + "{}", + "Is it the ct900 or the ct900ent?", + "{}", + "Happy to help.", + "{}"); + + var session = Build(reply); + var instruction = ClarificationText.Instruction( + AppliesToDescription, ["ct900", "ct900ent"], 6, first: true); + + await session.RunTurnAsync("I have a CT900 and a CT900ENT", TestContext.Current.CancellationToken); + Assert.Equal(string.Empty, reply.SystemText(0)); + + await session.RunTurnAsync("i hate you", TestContext.Current.CancellationToken); + Assert.Equal(instruction, reply.SystemText(2)); + + // The turn answered the caller instead of putting the question, so the ask went uncharged and + // the same instruction rides the next turn rather than the slot falling silent under K37. + await session.RunTurnAsync("which belt does mine take?", TestContext.Current.CancellationToken); + Assert.Equal(instruction, reply.SystemText(4)); + + // That reply named both candidates, so the ask is charged and K37 suppresses the repeat. + await session.RunTurnAsync("thanks", TestContext.Current.CancellationToken); + Assert.Equal(string.Empty, reply.SystemText(6)); + } + + private static CallSession Build(SequencedChatClient reply) + { + var chatClients = new FakeChatClientFactory(reply); + var compiled = ConfigurationCompiler.Compile( + ConfigurationLoader.LoadYaml(Yaml), new AgentCompilationContext(chatClients)); + + var extractor = CallSessionFactory.CreateExtractor(compiled, chatClients); + VocabularyCache vocabulary = new(); + vocabulary.Replace("applies_to", ["ct900", "ct900ent"], maxValues: 2000); + + return new CallSessionFactory( + compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor, vocabulary: vocabulary) + .Create("call-1"); + } +} diff --git a/tests/AgentCore.Application.Tests/Runtime/ClarificationProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/ClarificationProviderTests.cs index 4c233603..8f0b19c6 100644 --- a/tests/AgentCore.Application.Tests/Runtime/ClarificationProviderTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ClarificationProviderTests.cs @@ -289,7 +289,7 @@ public async Task TheUnchangedSet_IsNotAskedAgain_UntilItChanges() var turn1 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); Assert.NotNull(turn1.Messages); Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); - clarifications.CommitAsks(); + clarifications.CommitAsks("Is it a ct900 or a ct900ent?"); // Turn 2: the same set. namedAsks is at the cap (1), but K37 suppresses before the cap is // even reached, because nothing changed. @@ -298,7 +298,7 @@ public async Task TheUnchangedSet_IsNotAskedAgain_UntilItChanges() Assert.Null(turn2.Messages); Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); Assert.False(clarifications.Read("applies_to").ResetSpent); - clarifications.CommitAsks(); + clarifications.CommitAsks("okay."); // Turn 3: the set changes. namedAsks is at the cap and differs from lastNamed, so the one // reset fires: namedAsks returns to 1 (not 0), and the reset is spent. @@ -306,7 +306,7 @@ public async Task TheUnchangedSet_IsNotAskedAgain_UntilItChanges() clarifications.Update("applies_to", s => s.Pending = ["ct800", "ct800ent"]); var turn3 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); Assert.NotNull(turn3.Messages); - clarifications.CommitAsks(); + clarifications.CommitAsks("Is it a ct800 or a ct800ent?"); var afterReset = clarifications.Read("applies_to"); Assert.Equal(1, afterReset.NamedAsks); Assert.True(afterReset.ResetSpent); @@ -340,7 +340,7 @@ public async Task TwoDifferentOverCapSets_AreNotBothSpoken() var turn1 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); Assert.NotNull(turn1.Messages); Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); - clarifications.CommitAsks(); + clarifications.CommitAsks("Which model is it?"); clarifications.BeginTurn(); clarifications.Update("applies_to", s => s.Pending = ["h", "i", "j", "k", "l", "m", "n"]); diff --git a/tests/AgentCore.Application.Tests/Runtime/ClarificationTextTests.cs b/tests/AgentCore.Application.Tests/Runtime/ClarificationTextTests.cs index f01154dc..ef4f04f2 100644 --- a/tests/AgentCore.Application.Tests/Runtime/ClarificationTextTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ClarificationTextTests.cs @@ -23,8 +23,8 @@ public void Instruction_TwoCandidates_FirstMessage_RendersTheBaseSentence() Assert.Equal( "One thing is not yet known: The model, as printed on the machine. It is one of ct900 or " - + "ct900ent. Ask the caller, and do not give advice that is specific to one until they answer. " - + "Anything that applies to all of them is still fair game.", + + "ct900ent. Answer what the caller just said; where that calls for advice specific to one, ask " + + "the caller which first. Anything that applies to all of them is still fair game.", text); } @@ -36,8 +36,8 @@ public void Instruction_ThreeCandidates_JoinsWithAnOxfordComma() Assert.Equal( "One thing is not yet known: The model, as printed on the machine. It is one of ct800, ct900, " - + "or ct900ent. Ask the caller, and do not give advice that is specific to one until they answer. " - + "Anything that applies to all of them is still fair game.", + + "or ct900ent. Answer what the caller just said; where that calls for advice specific to one, " + + "ask the caller which first. Anything that applies to all of them is still fair game.", text); } @@ -49,7 +49,8 @@ public void Instruction_OneCandidate_RendersTheConfirmSentence() Assert.Equal( "One thing is not yet confirmed: The model, as printed on the machine. Everything found is for " - + "ct900. Ask the caller whether that is what they have before giving advice specific to it.", + + "ct900. Answer what the caller just said; where that calls for advice specific to it, ask the " + + "caller first whether that is what they have.", text); } @@ -63,8 +64,8 @@ public void Instruction_OverMaxCandidates_OmitsTheList() first: true); Assert.Equal( - "One thing is not yet known: The model, as printed on the machine. Ask the caller, and do not " - + "give advice specific to one until they answer.", + "One thing is not yet known: The model, as printed on the machine. Answer what the caller just " + + "said; where that calls for advice specific to one, ask the caller first.", text); } @@ -96,9 +97,9 @@ public void Instruction_DescriptionFallsBackToTheSlotName_WhenTheCallerPassesIt( var text = ClarificationText.Instruction("applies_to", ["ct900", "ct900ent"], maxCandidates: 6, first: true); Assert.Equal( - "One thing is not yet known: applies_to It is one of ct900 or ct900ent. Ask the caller, and do " - + "not give advice that is specific to one until they answer. Anything that applies to all of " - + "them is still fair game.", + "One thing is not yet known: applies_to It is one of ct900 or ct900ent. Answer what the caller " + + "just said; where that calls for advice specific to one, ask the caller which first. Anything " + + "that applies to all of them is still fair game.", text); } diff --git a/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs b/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs index 223ca23b..3239d9e9 100644 --- a/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs @@ -266,7 +266,7 @@ public void CommitAsks_KeepsTheAsk_AcrossTheTurnBoundary() var named = Clarifications.LastNamed.Of(new HashSet(StringComparer.Ordinal) { "ct900" }); clarifications.Ask("applies_to", named, spendsReset: false); - clarifications.CommitAsks(); + clarifications.CommitAsks("Is it a ct900?"); clarifications.BeginTurn(); var kept = clarifications.Read("applies_to"); diff --git a/tests/AgentCore.Application.Tests/Runtime/SpokenAskTests.cs b/tests/AgentCore.Application.Tests/Runtime/SpokenAskTests.cs new file mode 100644 index 00000000..7ee2f532 --- /dev/null +++ b/tests/AgentCore.Application.Tests/Runtime/SpokenAskTests.cs @@ -0,0 +1,67 @@ +using AgentCore.Application.Runtime; +using Xunit; + +namespace AgentCore.Application.Tests.Runtime; + +/// +/// and the gate it drives: the ask +/// is charged to the slot only where the turn's own reply actually put the question. +/// +public sealed class SpokenAskTests +{ + [Fact] + public void NamedIn_ReplyNamesOneOfTheCandidates_IsTrue() + => Assert.True(SpokenAsk.NamedIn("Is it the ct900 or the ct900ent?", Named("ct900", "ct900ent"))); + + [Fact] + public void NamedIn_ReplyNamesNone_IsFalse() + => Assert.False(SpokenAsk.NamedIn("I'm sorry to hear that. What is going wrong?", Named("ct900", "ct900ent"))); + + [Fact] + public void NamedIn_ReplyRespellsACandidate_IsTrue() + { + // The fold drops separators, so a model that writes the value back with a space where the + // collection has a hyphen still counts as having asked. + Assert.True(SpokenAsk.NamedIn("Is it the F63 2013?", Named("F63-2013", "F63-2023"))); + } + + [Fact] + public void NamedIn_AnOverCapRecord_IsTrue() + { + // The over-cap instruction lists nothing, so there is no name to look for. Charging it is + // the only outcome that does not drop the ask on every turn alike. + Assert.True(SpokenAsk.NamedIn("I'm sorry to hear that.", Clarifications.LastNamed.TooMany)); + } + + [Fact] + public void CommitAsks_AReplyThatNeverPutTheQuestion_LeavesTheAskUncharged() + { + var clarifications = new Clarifications(); + + clarifications.Ask("applies_to", Named("ct900", "ct900ent"), spendsReset: false); + clarifications.CommitAsks("I'm sorry to hear that. What is going wrong?"); + clarifications.BeginTurn(); + + var slot = clarifications.Read("applies_to"); + Assert.Equal(0, slot.NamedAsks); + Assert.Equal(Clarifications.LastNamedKind.None, slot.LastNamed.Kind); + } + + [Fact] + public void CommitAsks_AReplyThatPutTheQuestion_ChargesTheAsk() + { + var clarifications = new Clarifications(); + var named = Named("ct900", "ct900ent"); + + clarifications.Ask("applies_to", named, spendsReset: false); + clarifications.CommitAsks("Is it the ct900 or the ct900ent?"); + clarifications.BeginTurn(); + + var slot = clarifications.Read("applies_to"); + Assert.Equal(1, slot.NamedAsks); + Assert.True(named.Names(slot.LastNamed)); + } + + private static Clarifications.LastNamed Named(params string[] values) + => Clarifications.LastNamed.Of(new HashSet(values, StringComparer.Ordinal)); +} diff --git a/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerSiblingNarrowingTests.cs b/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerSiblingNarrowingTests.cs new file mode 100644 index 00000000..3bbd896e --- /dev/null +++ b/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerSiblingNarrowingTests.cs @@ -0,0 +1,90 @@ +using AgentCore.Application.State; +using Xunit; + +namespace AgentCore.Application.Tests.State; + +/// +/// The prefixed-sibling narrowing rule: what the caller spelled after the matched value decides +/// which of its longer siblings are still plausible. A sibling whose own extension is a peer of the +/// caller's — same length, same character class — and is not the one the caller said, is ruled out +/// by the caller's own words rather than offered back as a near-tie. +/// +public sealed class ExactStateValueLinkerSiblingNarrowingTests +{ + private static readonly HashSet NothingNamed = new(StringComparer.Ordinal); + + private static readonly string[] DatedCatalogue = ["F63", "F63-2013", "F63-2023", "F63-2026"]; + + private static readonly ExactStateValueLinker Linker = new(); + + [Fact] + public void Link_ExtensionIsAPeerOfEverySibling_LinksTheBareValue() + { + var result = Linker.Link("f63 2016", Vocabulary(DatedCatalogue), NothingNamed); + + AssertLinked(result, "F63"); + } + + [Fact] + public void Link_ExtensionIsAPeerOfOnlySomeSiblings_KeepsTheRest() + { + var result = Linker.Link("f63 2016", Vocabulary("F63", "F63-2013", "F63-2016B"), NothingNamed); + + AssertAmbiguous(result, "F63", "F63-2016B"); + } + + [Fact] + public void Link_ExtensionOfADifferentCharacterClass_DecidesNothing() + { + var result = Linker.Link("f63 console", Vocabulary(DatedCatalogue), NothingNamed); + + AssertAmbiguous(result, "F63", "F63-2013", "F63-2023", "F63-2026"); + } + + [Fact] + public void Link_ExtensionOfADifferentLength_DecidesNothing() + { + var result = Linker.Link("a CT800 please", Vocabulary("ct800", "ct800ent"), NothingNamed); + + AssertAmbiguous(result, "ct800", "ct800ent"); + } + + [Fact] + public void Link_NoExtensionAtAll_LeavesEverySiblingStanding() + { + var result = Linker.Link("f63", Vocabulary(DatedCatalogue), NothingNamed); + + AssertAmbiguous(result, "F63", "F63-2013", "F63-2023", "F63-2026"); + } + + [Fact] + public void Link_ExtensionThatStartsASibling_KeepsThatSibling() + { + var result = Linker.Link("f63 20", Vocabulary(DatedCatalogue), NothingNamed); + + AssertAmbiguous(result, "F63", "F63-2013", "F63-2023", "F63-2026"); + } + + private static VocabularyView Vocabulary(params string[] values) + { + Dictionary normalisedToOriginal = new(StringComparer.Ordinal); + foreach (var value in values) + { + normalisedToOriginal[VocabularyFold.Fold(value)] = value; + } + + return new VocabularyView { NormalisedToOriginal = normalisedToOriginal, Originals = values }; + } + + private static void AssertLinked(LinkResult result, string expected) + { + Assert.Equal(LinkOutcome.Linked, result.Outcome); + Assert.Equal([expected], result.Candidates); + } + + private static void AssertAmbiguous(LinkResult result, params string[] expectedSortedAscending) + { + Assert.Equal(LinkOutcome.Ambiguous, result.Outcome); + Assert.Equal(expectedSortedAscending, result.Candidates); + } +} diff --git a/tests/AgentCore.Application.Tests/State/VocabularyCacheTests.cs b/tests/AgentCore.Application.Tests/State/VocabularyCacheTests.cs index 5156f2d2..b1d5612b 100644 --- a/tests/AgentCore.Application.Tests/State/VocabularyCacheTests.cs +++ b/tests/AgentCore.Application.Tests/State/VocabularyCacheTests.cs @@ -180,7 +180,10 @@ public async Task Snapshot_ReadWhileARefreshIsReplacing_NeverThrows() using ManualResetEventSlim reading = new(); using CancellationTokenSource stop = new(); - var reader = Task.Run( + // Its own thread (LongRunning), never a pooled one: the reader spins for the whole test and + // the wait below has no timeout, so a reader left queued behind a busy thread pool — the + // rest of the suite running in parallel — would hang the test rather than fail it. + var reader = Task.Factory.StartNew( () => { reading.Set(); @@ -190,7 +193,9 @@ public async Task Snapshot_ReadWhileARefreshIsReplacing_NeverThrows() _ = snapshot["machine"].Originals.Count; } }, - TestContext.Current.CancellationToken); + TestContext.Current.CancellationToken, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); reading.Wait(TestContext.Current.CancellationToken); @@ -250,12 +255,22 @@ void RaceWithTag(string prefix) } } - var threadA = Task.Run(() => RaceWithTag("A"), TestContext.Current.CancellationToken); - var threadB = Task.Run(() => RaceWithTag("B"), TestContext.Current.CancellationToken); + // Each racer gets its own thread (LongRunning), never a pooled one: a Barrier only makes + // progress while both participants are running at once, and under a full thread pool — the + // rest of the suite running in parallel — the second Task.Run can wait longer for a thread + // than the barrier timeout allows, which fails the round rather than the invariant. + var threadA = StartRacer("A"); + var threadB = StartRacer("B"); start.Set(); await Task.WhenAll(threadA, threadB); Assert.Equal(Rounds * 2, provider.Calls.Count); + + Task StartRacer(string prefix) => Task.Factory.StartNew( + () => RaceWithTag(prefix), + TestContext.Current.CancellationToken, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); } private static void AssertQuiescentAgreement(TaggingTimeProvider provider, VocabularyCache cache)