From 6ccc8d39dbd3370de0cef79e875bd8eef00442bd Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 15:22:54 -0500 Subject: [PATCH] test(compaction): check prepare's contract with a recording strategy A fake strategy and notes layers record how compaction.prepare calls them over every combination of forced, cached, due, failing projections and compaction outcomes, against the rules in prepare's doc comments: at most one compaction, projections never forced, the cached request offered only while the cache holds, a forced compaction kept when its replay projection fails, and layers rewriting notes only when the state changed. Deleted summary_replay_test.test_a_lapsed_cache_summarizes_separately (a 1.2 s wall-clock sleep): a lapsed cache sending a separate summary is the replayable=False path of the new property, and the lapse is cache_ttl.lifetime's (albedo_sdk cache_ttl_test). The cached replay stays as the one wiring scenario. --- .../composition/compaction_prepare_test.gleam | 267 ++++++++++++++++++ e2e/summary_replay_test.py | 24 +- 2 files changed, 276 insertions(+), 15 deletions(-) create mode 100644 apps/albedo/test/albedo/composition/compaction_prepare_test.gleam diff --git a/apps/albedo/test/albedo/composition/compaction_prepare_test.gleam b/apps/albedo/test/albedo/composition/compaction_prepare_test.gleam new file mode 100644 index 000000000..1bdbe20c0 --- /dev/null +++ b/apps/albedo/test/albedo/composition/compaction_prepare_test.gleam @@ -0,0 +1,267 @@ +//// `compaction.prepare` against its documented contract, with a strategy and +//// notes layers that only record how they were called. Catches a request +//// that compacts twice, a projection that runs forced, a summary offered the +//// cached request when the cache has lapsed (or denied it while cached), a +//// forced compaction given up because the replay projection failed, a layer +//// that rewrites its notes when the strategy changed nothing, and a cache +//// question asked when no compaction runs. Every real strategy reaches these +//// rules only through `prepare`, so a fake strategy sees them all; the +//// summary_replay e2e scenario checked one path of them through a daemon. + +import albedo/storage/core_store +import albedo_model as types +import albedo_model/size +import albedo_property +import albedo_sdk/compaction.{type Context, type Prepared} +import albedo_sdk/extension +import albedo_sdk/store +import gleam/erlang/process.{type Subject} +import gleam/int +import gleam/list +import gleam/option.{type Option, None, Some} +import gleeunit/should +import qcheck + +/// What the fakes saw, in order. +type Call { + Projected(force: Bool, current: Option(List(types.Input))) + Compacted(force: Bool, current: Option(List(types.Input))) + AskedCache + LayerProjected(layer: Int) + LayerCompacted(layer: Int) +} + +type Scenario { + Scenario( + force: Bool, + replayable: Bool, + due: Bool, + /// Which projections fail, counting from 1. + failing: List(Int), + /// What the compaction answers: changed, unchanged, or an error. + compacts: Result(Bool, Nil), + layers: Int, + ) +} + +fn scenario_generator() -> qcheck.Generator(Scenario) { + use force <- qcheck.bind(qcheck.bool()) + use replayable <- qcheck.bind(qcheck.bool()) + use due <- qcheck.bind(qcheck.bool()) + use failing <- qcheck.bind(qcheck.generic_list( + qcheck.bounded_int(1, 3), + qcheck.bounded_int(0, 2), + )) + use compacts <- qcheck.bind( + qcheck.from_generators(qcheck.return(Ok(True)), [ + qcheck.return(Ok(False)), + qcheck.return(Error(Nil)), + ]), + ) + use layers <- qcheck.map(qcheck.bounded_int(0, 2)) + Scenario(force, replayable, due, failing, compacts, layers) +} + +const history = [types.User("old"), types.User("new")] + +/// The strategy's own projection, and what each layer adds after it. +fn view_inputs() -> List(types.Input) { + [types.User("view")] +} + +fn layer_input(layer: Int) -> types.Input { + types.User("layer " <> int.to_string(layer)) +} + +fn shown(layers: Int) -> List(types.Input) { + list.append(view_inputs(), list.map(int_range(layers), layer_input)) +} + +fn int_range(count: Int) -> List(Int) { + list.repeat(Nil, count) |> list.index_map(fn(_, index) { index }) +} + +fn run( + scenario: Scenario, + ledger: store.Store, +) -> #(Result(Prepared, String), List(Call)) { + let log = process.new_subject() + let projections = process.new_subject() + process.send(projections, 0) + let strategy = + compaction.Strategy( + name: "fake", + project: fn(context: Context, _) { + process.send(log, Projected(context.force, context.current)) + let assert Ok(count) = process.receive(projections, 0) + process.send(projections, count + 1) + case list.contains(scenario.failing, count + 1) { + True -> Error("projection failed") + False -> Ok(compaction.View(view_inputs(), None, scenario.due, 0)) + } + }, + compact: fn(context: Context, _) { + process.send(log, Compacted(context.force, context.current)) + case scenario.compacts { + Ok(changed) -> Ok(changed) + Error(Nil) -> Error("compaction failed") + } + }, + notes: True, + ) + let layers = + list.map(int_range(scenario.layers), fn(layer) { + compaction.Notes( + name: "layer", + project: fn(_, _, prepared) { + process.send(log, LayerProjected(layer)) + Ok(add(prepared, layer)) + }, + compact: fn(_, _, prepared) { + process.send(log, LayerCompacted(layer)) + Ok(add(prepared, layer)) + }, + ) + }) + let result = + compaction.prepare( + strategy, + layers, + context(scenario, ledger, log), + history, + ) + #(result, drain(log, [])) +} + +fn add(prepared: Prepared, layer: Int) -> Prepared { + compaction.Prepared( + ..prepared, + inputs: list.append(prepared.inputs, [layer_input(layer)]), + ) +} + +fn drain(log: Subject(Call), calls: List(Call)) -> List(Call) { + case process.receive(log, 0) { + Ok(call) -> drain(log, [call, ..calls]) + Error(Nil) -> list.reverse(calls) + } +} + +fn context( + scenario: Scenario, + ledger: store.Store, + log: Subject(Call), +) -> Context { + compaction.Context( + session: "prepare", + model: "model", + source: "model", + capacity: None, + session_window: Some(1000), + force: scenario.force, + summarize: fn(_) { Ok(compaction.Summary("summary", False, None)) }, + prior: fn(history) { Ok(compaction.Prior([], history)) }, + reader: None, + images: types.any_images, + compacting: fn(_) { Nil }, + project: compaction.unprojected, + replayable: fn() { + process.send(log, AskedCache) + scenario.replayable + }, + current: None, + storage: extension.unscoped(ledger), + sizing: compaction.estimated_sizing( + size.Route("", "prepare-test", size.by_bytes), + "", + [], + ), + ) +} + +/// The calls the contract allows, worked out from the doc comments on +/// `prepare`, `Context.replayable`, `Context.current` and `Notes`. +fn expected(scenario: Scenario) -> #(Result(Prepared, Nil), List(Call)) { + let Scenario(force:, replayable:, due:, failing:, compacts:, layers:) = + scenario + let fails = fn(n) { list.contains(failing, n) } + let layer_projections = list.map(int_range(layers), LayerProjected) + let layer_compactions = list.map(int_range(layers), LayerCompacted) + // A compaction, then the projection the provider has not seen, numbered + // `n`: the layers rewrite their notes only when the state changed. + let compact = fn(current, n, before) { + let calls = list.append(before, [Compacted(force, current)]) + case compacts { + Error(Nil) -> #(Error(Nil), calls) + Ok(changed) -> { + let calls = list.append(calls, [Projected(False, None)]) + case fails(n), changed { + True, _ -> #(Error(Nil), calls) + False, True -> #( + Ok(compaction.Prepared(shown(layers), None, True, 0)), + list.append(calls, layer_compactions), + ) + False, False -> #( + Ok(compaction.Prepared(shown(layers), None, False, 0)), + list.append(calls, layer_projections), + ) + } + } + } + } + case force, replayable { + True, False -> compact(None, 1, [AskedCache]) + True, True -> + case fails(1) { + True -> compact(None, 2, [AskedCache, Projected(False, None)]) + False -> + compact( + Some(shown(layers)), + 2, + list.flatten([ + [AskedCache, Projected(False, None)], + layer_projections, + ]), + ) + } + False, _ -> { + let first = [Projected(False, None), ..layer_projections] + case fails(1), due { + True, _ -> #(Error(Nil), [Projected(False, None)]) + False, False -> #( + Ok(compaction.Prepared(shown(layers), None, False, 0)), + first, + ) + False, True -> { + let current = case replayable { + True -> Some(shown(layers)) + False -> None + } + compact(current, 2, list.append(first, [AskedCache])) + } + } + } + } +} + +pub fn prepare_follows_its_contract_test() -> Nil { + let assert Ok(ledger) = store.start(":memory:", "", core_store.tables()) + use scenario <- albedo_property.run(200, scenario_generator()) + let #(result, calls) = run(scenario, ledger) + let #(want, want_calls) = expected(scenario) + calls |> should.equal(want_calls) + case result, want { + Ok(prepared), Ok(want) -> prepared |> should.equal(want) + Error(_), Error(Nil) -> Nil + _, _ -> + should.equal(result |> option.from_result, want |> option.from_result) + } + // A request compacts at most once. + list.count(calls, fn(call) { + case call { + Compacted(..) -> True + _ -> False + } + }) + |> fn(compactions) { { compactions <= 1 } |> should.be_true } +} diff --git a/e2e/summary_replay_test.py b/e2e/summary_replay_test.py index 5b491a987..5e193c57e 100644 --- a/e2e/summary_replay_test.py +++ b/e2e/summary_replay_test.py @@ -1,10 +1,16 @@ """A compaction whose session's last request is still cached asks for its summaries at the end of that request, so the provider reads the history it -summarizes from cache; once the cache has lapsed, the summary goes out as a -request of its own.""" +summarizes from cache. + +Catches a replayed summary request that differs from the last turn's in its +input prefix, tools, tool choice or instructions, and a cache table that never +reaches the strategy. Only the assembled daemon has the loop, the cache table, +the strategy and the summarizer together. When a summary is offered the cached +request, and when it is not, is `compaction.prepare`'s contract, checked in +`apps/albedo/test/albedo/composition/compaction_prepare_test.gleam`; the lapse +itself is `cache_ttl.lifetime`'s.""" import json -import time import unittest from harness import Albedo, Provider, exclusive, text @@ -38,8 +44,6 @@ def reply(request): return text("replayed leaf") if NOTES in sent: return text("replayed notes") - if EVICTED in sent: - return text("separate summary") return text("ordinary answer") @@ -93,16 +97,6 @@ class SummaryReplayTests(unittest.TestCase): self.assertIn("replayed leaf", shown) self.assertIn("replayed notes", shown) - def test_a_lapsed_cache_summarizes_separately(self): - session = self.converse(1) - # The lifetime counts with a tenth spare, so 0.9s is already too late. - time.sleep(1.2) - calls = self.compact(session) - self.assertFalse(any(LEAF in json.dumps(call["input"]) for call in calls)) - separate = [call for call in calls if EVICTED in json.dumps(call["input"])] - self.assertTrue(separate, calls) - self.assertEqual(separate[0].get("tool_choice"), "none") - if __name__ == "__main__": unittest.main() -- knotmirror 0.0.1