Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
using AgentMemory.LongMemEval;
using FluentAssertions;
using Microsoft.Extensions.AI;
using Xunit;

namespace AgentMemory.Tests.Unit.LongMemEval;

/// <summary>
/// The benchmark task procedural memory is measured against (7.6).
/// </summary>
/// <remarks>
/// <para>
/// <b>A benchmark for procedural memory has one hard requirement: the shortest correct path must be
/// discoverable but not guessable.</b> If the task can be completed on a first attempt by calling the
/// obvious tool, there is nothing to learn, both arms score identically, and the harness reports "no
/// benefit" for a reason that has nothing to do with memory.
/// </para>
/// <para>
/// These tests exist to prove the task actually has that property — that it refuses shortcuts, and
/// that the only route to the completion marker is the full chain. Getting this wrong would not look
/// like a broken test; it would look like a feature that does not help.
/// </para>
/// </remarks>
public sealed class ProceduralBenchmarkTaskTests
{
private static async Task<string> InvokeAsync(ProceduralBenchmarkTask task, string tool, object args)
{
var fn = (AIFunction)task.CreateTools().Single(t => ((AIFunction)t).Name.Contains(tool, StringComparison.OrdinalIgnoreCase));
var dict = args.GetType().GetProperties().ToDictionary(p => p.Name, p => (object?)p.GetValue(args));
var result = await fn.InvokeAsync(new AIFunctionArguments(dict));
return result?.ToString() ?? string.Empty;
}

[Fact]
public async Task TheChainCompletesWhenWalkedInOrder()
{
var task = new ProceduralBenchmarkTask();

var lookup = await InvokeAsync(task, "LookUpTraveller", new { traveller = "ruaidhri" });
lookup.Should().Contain("gold");

var hold = await InvokeAsync(task, "PlaceHold", new { connection = "14:05", tier = "gold" });
hold.Should().Contain("HOLD-4417");

var booking = await InvokeAsync(task, "Book", new { holdReference = "HOLD-4417" });
booking.Should().Contain(ProceduralBenchmarkTask.ConfirmationMarker);
Comment on lines +39 to +46
task.IsComplete(booking).Should().BeTrue();
}

[Fact]
public async Task BookingDirectlyIsRefused()
{
// THE property that makes the benchmark measure anything. If the obvious first move worked,
// an agent would succeed cold on attempt one and both arms would tie -- reporting "procedural
// memory does not help" for a reason that is entirely about the task.
var task = new ProceduralBenchmarkTask();

var booking = await InvokeAsync(task, "Book", new { holdReference = "whatever" });

booking.Should().Contain("refused", Exactly.Once());
task.IsComplete(booking).Should().BeFalse();
}

[Fact]
public async Task AHoldWithoutTheTierIsRefused()
{
// The second link. The tier lives behind a lookup the prompt never mentions, so an agent
// meeting this cold has to be refused before it can discover the step -- which is the cost the
// stored procedure removes on later attempts.
var task = new ProceduralBenchmarkTask();

var hold = await InvokeAsync(task, "PlaceHold", new { connection = "14:05", tier = "unknown" });

hold.Should().Contain("refused");
hold.Should().Contain("look up the traveller", Exactly.Once());
}

[Fact]
public async Task ARefusalNamesTheMissingStep()
{
// Refused, not thrown. A hard failure ends the run instead of teaching it, and an agent that
// cannot learn the chain cold makes the control arm measure the harness rather than the agent.
var task = new ProceduralBenchmarkTask();

var hold = await InvokeAsync(task, "PlaceHold", new { connection = "14:05", tier = "bronze" });

hold.Should().NotBeNullOrWhiteSpace();
hold.Should().Contain("tier");
}

[Fact]
public async Task TheEnvironmentAnswersIdenticallyEveryTime()
{
// Deterministic on purpose: the agent is the only nondeterministic part. A varying environment
// would be reported as a memory effect, and three attempts per arm is nowhere near enough
// sample to tell those apart.
var first = await InvokeAsync(new ProceduralBenchmarkTask(), "LookUpTraveller", new { traveller = "ruaidhri" });
var second = await InvokeAsync(new ProceduralBenchmarkTask(), "LookUpTraveller", new { traveller = "ruaidhri" });

second.Should().Be(first);
}

[Fact]
public void CompletionCannotBeClaimedInProse()
{
// An agent that learned a wrong procedure reports success fluently. The marker is emitted only
// by the booking tool, so it cannot be produced by confidence.
var task = new ProceduralBenchmarkTask();

task.IsComplete("I have successfully completed the booking for you!").Should().BeFalse();
task.IsComplete($"{ProceduralBenchmarkTask.ConfirmationMarker} ref HOLD-4417").Should().BeTrue();
}

[Fact]
public void ToolsAreExposedInProcedureOrder()
{
new ProceduralBenchmarkTask().CreateTools().Should().HaveCount(3);
}
}
96 changes: 96 additions & 0 deletions tools/AgentMemory.LongMemEval/ProceduralBenchmarkTask.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System.ComponentModel;
using System.Globalization;
using Microsoft.Extensions.AI;

namespace AgentMemory.LongMemEval;

/// <summary>
/// The repeated multi-step task the procedural-benefit harness measures against (7.6).
/// </summary>
/// <remarks>
/// <para>
/// A benchmark for procedural memory has one hard requirement: <b>the shortest correct path must be
/// discoverable but not guessable.</b> If an agent can succeed on its first attempt by calling the
/// obvious tool, there is no procedure to learn and both arms score identically — the measurement
/// returns "no benefit" for a reason that has nothing to do with memory.
/// </para>
/// <para>
/// So the ordering here is enforced rather than suggested. Booking requires a hold, a hold requires
/// the traveller's tier, and the tier lives behind a lookup the task prompt never mentions. An agent
/// meeting this cold must discover that chain by being refused; an agent with the procedure stored
/// walks it. That gap is the entire signal, and it is why <c>book</c> refuses politely with the
/// reason rather than erroring — a hard failure would end the run instead of teaching it.
/// </para>
/// <para>
/// <b>Deterministic tools, on purpose.</b> The agent is the only nondeterministic part; the world it
/// acts on answers identically every time. A benchmark whose environment varied would report the
/// variance as a memory effect, and with three attempts per arm there is nowhere near the sample size
/// to tell those apart.
/// </para>
/// </remarks>
internal sealed class ProceduralBenchmarkTask
{
/// <summary>Marker the agent can only emit by completing the real chain.</summary>
/// <remarks>
/// Completion is checked against this rather than against the agent saying it finished. An agent
/// that learned a <i>wrong</i> procedure reports success fluently, and that failure is invisible
/// to every efficiency number the harness collects.
/// </remarks>
internal const string ConfirmationMarker = "BOOKING-CONFIRMED";

private const string Traveller = "ruaidhri";
private const string RequiredTier = "gold";
private const string HoldReference = "HOLD-4417";
Comment on lines +39 to +43

/// <summary>Records what was called, so a test can assert the chain without a model.</summary>
internal List<string> Calls { get; } = [];

internal string Prompt =>
$"Book the 14:05 rail connection for traveller '{Traveller}'. "
+ $"Reply with the confirmation reference exactly as the booking tool returns it.";

internal bool IsComplete(string response) =>
response.Contains(ConfirmationMarker, StringComparison.Ordinal);

/// <summary>The tools, in the order a correct procedure uses them.</summary>
internal IReadOnlyList<AITool> CreateTools() =>
[
AIFunctionFactory.Create(LookUpTraveller),
AIFunctionFactory.Create(PlaceHold),
AIFunctionFactory.Create(Book),
];

[Description("Looks up a traveller's loyalty tier. Required before a hold can be placed.")]
private string LookUpTraveller(
[Description("The traveller's name.")] string traveller)
{
Calls.Add(nameof(LookUpTraveller));
return string.Equals(traveller, Traveller, StringComparison.OrdinalIgnoreCase)
? $"traveller={Traveller}; tier={RequiredTier}"
: $"no traveller named '{traveller}'";
}

[Description("Places a hold on a connection. Requires the traveller's loyalty tier.")]
private string PlaceHold(
[Description("The connection time, e.g. 14:05.")] string connection,
[Description("The traveller's loyalty tier, from the traveller lookup.")] string tier)
{
Calls.Add(nameof(PlaceHold));
// Refused, not thrown. A hard failure ends the run; a refusal that names what is missing is
// what an agent without the procedure can actually learn from -- and learning it cold, once,
// is precisely the cost the stored procedure is supposed to remove.
return string.Equals(tier, RequiredTier, StringComparison.OrdinalIgnoreCase)
? $"hold placed on {connection}; reference={HoldReference}"
: $"refused: a hold needs the traveller's loyalty tier; look up the traveller first";
}

[Description("Confirms a booking. Requires a hold reference.")]
private string Book(
[Description("The hold reference returned by the hold tool.")] string holdReference)
{
Calls.Add(nameof(Book));
return string.Equals(holdReference, HoldReference, StringComparison.OrdinalIgnoreCase)
? string.Create(CultureInfo.InvariantCulture, $"{ConfirmationMarker} ref {HoldReference}")
: "refused: booking needs a valid hold reference; place a hold first";
}
}