diff --git a/robot-docs/compaction.md b/robot-docs/compaction.md index 2730fe9ff..fce8344d3 100644 --- a/robot-docs/compaction.md +++ b/robot-docs/compaction.md @@ -56,7 +56,7 @@ A strategy reads folds another strategy stored through `context.prior(history)`, `lcm` implements the source-backed memory part of [Lossless Context Management](https://arxiv.org/html/2605.04050v1). It stores leaf summaries, condensed parent summaries, child links, and a covered source cursor in SQLite. The durable transcript supplies their source rows. The summary tree belongs to one session. A fork copies complete prefix summaries and their links with remapped row and node IDs. -Below the trigger, `lcm` sends ordinary history without a summarizer call. Within a run, the trigger reads the input and output tokens the provider reported for the previous request, so it follows the model's own tokenizer; the first request of a run, and the request right after a compaction, have no reported count yet and use albedo's byte count. The trigger is `triggerPercent` of the window when it is set. Otherwise it is 80% of a window of 400k tokens or more and 75% of a smaller one, which leaves a small window more room for the reply. At the trigger, `lcm` keeps a verbatim tail: the newest steps within `tailPercent` (default 20%) of the window, always including the newest step. A step is a user message, a model response, or the tool results that follow one, so a cut can fall inside one long agentic turn but never between a tool call and its result. `lcm` folds every step between the frontier and that tail into one depth-0 leaf. The leaf's summarizer is given the frontier's summaries as what the reader already remembers, and asked to continue from them rather than repeat them; merges and the combining of parts are not. A request shows the frontier's nodes and then every transcript row after the leaf cursor, verbatim. The newest user message stays verbatim even once its steps are folded, placed before the first node that reaches past it, so a long agentic turn keeps its task word for word; history holds one input per row, so the cursor need not sit on a user message. The summarizer request carries the evicted history as the conversation it was, after any previous summary and before a closing turn that asks for the summary, through the same wire as a turn: a provider reads its own signed or encrypted reasoning as it would on a turn, and a foreign model's turns replay as that wire replays them. The session's tools ride along, because a provider may refuse tool calls in a request without tool definitions, and `tool_choice` is none. The request asks for no prompt cache write, because nothing sends that prefix again: Claude's wire then places no `cache_control` marks; providers that cache implicitly are unaffected. Size estimates and the verbatim fallback read the same history as text, with each step's readable reasoning, text and calls. Every leaf, merge and combination of parts is written as a spec in the same sections: Task, Settled (verified facts with how they were verified), Contracts (exact signatures, paths with lines, strings and commands), Changes, Plan (the next action first, with a sketch of any tricky logic) and Open. Agents on DeepSWE runs re-read files their prose summaries had already described, and said they trust a summary that reads as settled facts and exact contracts. Summaries have no length budget. The output limit only guards against a runaway reply, so a large window makes a long summary and a small window makes a small leaf. One summarizer request reads at most 200k tokens, measured as the summarizer renders the items. A larger source is summarized in chronological parts of whole steps, and the part summaries are combined into the one node. If the summarizer returns nothing, for example because a transcript note told it to stay idle, the request is retried once with a request for plain prose. A second empty reply keeps the source itself as the node's text, so compaction always makes its node. A provider failure fails the compaction and saves nothing. After the leaf, `lcm` merges only under pressure, never by count. While the request is above half the trigger, the oldest frontier nodes are merged into one parent. Those are the fewest oldest nodes whose text covers the excess, at least two when there are two. Their depths and sizes may differ, and the parent sits one level above the deepest child. Older history therefore grows coarser first, and the newest summaries keep their detail longest. A merge must cut the summary text it replaces by at least a tenth, or it is discarded and relief stops; a frontier that is down to one node is recompressed at most once per compaction; and relief stops after 16 merges. If the request without its summaries (the pinned prompt plus the tail) already reaches half the trigger, relief aims only at the trigger, and if it reaches the trigger, relief does not merge at all, because merging cannot get below that floor. A forced `/compact` without a real window (from the session, the configuration or a catalog), or whose tail would hold the whole history, keeps the newest user turn verbatim and folds everything before it; a session that is a single turn keeps only its newest step. The children stay in SQLite. A session that switches to `lcm` from another strategy is not summarized from its first row. Until `lcm` compacts, the request shows what the other strategy's stored folds made of the history, for example snapcompact's archive pages and the rows after them. The first compaction then writes one pointer node, with no summarizer call, over the rows those folds cover, and it folds the rows that were live after them into one leaf. The original rows remain available. +Below the trigger, `lcm` sends ordinary history without a summarizer call. Within a run, the trigger reads the input and output tokens the provider reported for the previous request, so it follows the model's own tokenizer; the first request of a run, and the request right after a compaction, have no reported count yet and use albedo's byte count. The trigger is `triggerPercent` of the window when it is set. Otherwise it is 80% of a window of 400k tokens or more and 75% of a smaller one, which leaves a small window more room for the reply. At the trigger, `lcm` keeps a verbatim tail: the newest steps within `tailPercent` (default 20%) of the window, always including the newest step. A step is a user message, a model response, or the tool results that follow one, so a cut can fall inside one long agentic turn but never between a tool call and its result. `lcm` folds every step between the frontier and that tail into one depth-0 leaf. The leaf's summarizer is given the frontier's summaries as what the reader already remembers, and asked to continue from them rather than repeat them; merges and the combining of parts are not. A request shows the frontier's nodes and then every transcript row after the leaf cursor, read from the transcript and converted the way a turn's history is for the provider carrying the request. A cut falls between steps, never inside one response's items, so those rows convert to exactly the end of the history whatever providers and protocols wrote it. Only those uncovered rows are decoded, never the folded ones. The newest user message stays verbatim even once its steps are folded, placed before the first node that reaches past it, so a long agentic turn keeps its task word for word. Seeding from another strategy checks that the converted rows from the cut equal that strategy's remaining history; when they do not, nothing is seeded and the compaction folds from the first row instead of failing. The summarizer request carries the evicted history, converted the same way, as the conversation it was, after any previous summary and before a closing turn that asks for the summary, through the same wire as a turn: a provider reads its own signed or encrypted reasoning as it would on a turn, and a foreign model's turns replay as that wire replays them. The session's tools ride along, because a provider may refuse tool calls in a request without tool definitions, and `tool_choice` is none. The request asks for no prompt cache write, because nothing sends that prefix again: Claude's wire then places no `cache_control` marks; providers that cache implicitly are unaffected. Size estimates and the verbatim fallback read the same history as text, with each step's readable reasoning, text and calls. Every leaf, merge and combination of parts is written as a spec in the same sections: Task, Settled (verified facts with how they were verified), Contracts (exact signatures, paths with lines, strings and commands), Changes, Plan (the next action first, with a sketch of any tricky logic) and Open. Agents on DeepSWE runs re-read files their prose summaries had already described, and said they trust a summary that reads as settled facts and exact contracts. Summaries have no length budget. The output limit only guards against a runaway reply, so a large window makes a long summary and a small window makes a small leaf. One summarizer request reads at most 200k tokens, measured as the summarizer renders the items. A larger source is summarized in chronological parts of whole steps, and the part summaries are combined into the one node. If the summarizer returns nothing, for example because a transcript note told it to stay idle, the request is retried once with a request for plain prose. A second empty reply keeps the source itself as the node's text, so compaction always makes its node. A provider failure fails the compaction and saves nothing. After the leaf, `lcm` merges only under pressure, never by count. While the request is above half the trigger, the oldest frontier nodes are merged into one parent. Those are the fewest oldest nodes whose text covers the excess, at least two when there are two. Their depths and sizes may differ, and the parent sits one level above the deepest child. Older history therefore grows coarser first, and the newest summaries keep their detail longest. A merge must cut the summary text it replaces by at least a tenth, or it is discarded and relief stops; a frontier that is down to one node is recompressed at most once per compaction; and relief stops after 16 merges. If the request without its summaries (the pinned prompt plus the tail) already reaches half the trigger, relief aims only at the trigger, and if it reaches the trigger, relief does not merge at all, because merging cannot get below that floor. A forced `/compact` without a real window (from the session, the configuration or a catalog), or whose tail would hold the whole history, keeps the newest user turn verbatim and folds everything before it; a session that is a single turn keeps only its newest step. The children stay in SQLite. A session that switches to `lcm` from another strategy is not summarized from its first row. Until `lcm` compacts, the request shows what the other strategy's stored folds made of the history, for example snapcompact's archive pages and the rows after them. The first compaction then writes one pointer node, with no summarizer call, over the rows those folds cover, and it folds the rows that were live after them into one leaf. The original rows remain available. The default-enabled `lcm-memory` extension provides four read-only tools. `lcm_list` pages through every stored fold in the current session, including nodes absent from the request view. `lcm_grep` searches literal text in raw history and summaries with paged results and optional node scope. `lcm_describe` returns a node's source range, children, child segments with summaries, and summary. `lcm_expand` reads bounded pages of the original text rows covered by a node. These tools remain enabled when the session switches from `lcm` to `rolling`. Image hashes and metadata remain in transcript rows until compaction elides a tool-output image, which leaves a text marker; the text tools show whichever remains. The extension implements hierarchical memory. It does not implement the paper's large-file dispatcher, map operators, or subagent-only expansion. diff --git a/src/albedo/daemon/conversation.gleam b/src/albedo/daemon/conversation.gleam index 1da54bd7a..38d529a0c 100644 --- a/src/albedo/daemon/conversation.gleam +++ b/src/albedo/daemon/conversation.gleam @@ -1220,16 +1220,7 @@ pub fn snapshot( } pub type SourceStats { - SourceStats( - latest_user: Option(Int), - uncovered: Bool, - uncovered_users: Int, - /// Every row after the cursor: the newest history inputs a projection - /// keeps verbatim, one per row. - uncovered_rows: Int, - /// The rows after the newest user row, which locate that row in history. - after_latest_user: Int, - ) + SourceStats(latest_user: Option(Int), uncovered: Bool, uncovered_users: Int) } pub fn source_stats( @@ -1258,7 +1249,7 @@ pub fn source_stats( )) use uncovered <- result.try(store.one( db, - "SELECT COUNT(*) FROM transcript WHERE session=? AND seq>? AND seq<=?", + "SELECT EXISTS(SELECT 1 FROM transcript WHERE session=? AND seq>? AND seq<=?)", [ sqlight.text(snapshot.session), sqlight.int(covered), @@ -1267,18 +1258,7 @@ pub fn source_stats( decode.field(0, decode.int, decode.success), "transcript uncovered rows", )) - use after <- result.try(store.one( - db, - "SELECT COUNT(*) FROM transcript WHERE session=? AND seq>? AND seq<=?", - [ - sqlight.text(snapshot.session), - sqlight.int(option.unwrap(latest, snapshot.upper)), - sqlight.int(snapshot.upper), - ], - decode.field(0, decode.int, decode.success), - "transcript rows after the user boundary", - )) - Ok(SourceStats(latest, uncovered > 0, count, uncovered, after)) + Ok(SourceStats(latest, uncovered == 1, count)) }) } diff --git a/src/albedo/harness/compaction.gleam b/src/albedo/harness/compaction.gleam index 066cc75d6..b3cd4dddb 100644 --- a/src/albedo/harness/compaction.gleam +++ b/src/albedo/harness/compaction.gleam @@ -64,12 +64,8 @@ pub type Context { /// Called once a compaction is about to start, so whoever waits on the /// request can say why it takes longer. compacting: fn() -> Nil, - /// Durable rows, each with the provider that wrote it, as the provider - /// carrying the request reads them: the conversion a turn's history goes - /// through, so another provider's or protocol's output arrives in a shape - /// this one accepts. - project: fn(List(#(Option(String), types.Input))) -> - Result(List(types.Input), String), + /// How this request's provider reads durable rows; see `Project`. + project: Project, ) } @@ -113,10 +109,18 @@ pub type Folds { /// The strategy that writes these folds. It reads its own state directly, /// so the runtime leaves this provider out while that strategy is active. owner: String, - apply: fn(store.Store, String, List(types.Input)) -> Result(Prior, String), + apply: fn(store.Store, String, Project, List(types.Input)) -> + Result(Prior, String), ) } +/// Durable rows, each with the provider that wrote it, as the provider +/// carrying the request reads them: the conversion a turn's history goes +/// through, so another provider's or protocol's output arrives in a shape +/// this one accepts. +pub type Project = + fn(List(#(Option(String), types.Input))) -> Result(List(types.Input), String) + /// `Ok(Nil)` when `condition` holds, else `Error(message)`: the guard every /// strategy and retrieval tool states as a boolean with one error string. pub fn require(condition: Bool, message: String) -> Result(Nil, String) { @@ -238,10 +242,16 @@ pub fn compose_prior( providers: List(Folds), ledger: store.Store, session: String, + project: Project, ) -> fn(List(types.Input)) -> Result(Prior, String) { fn(history) { list.try_fold(providers, Prior([], history), fn(prior, provider) { - use next <- result.try(provider.apply(ledger, session, prior.rest)) + use next <- result.try(provider.apply( + ledger, + session, + project, + prior.rest, + )) Ok(Prior(list.append(prior.folds, next.folds), next.rest)) }) } diff --git a/src/albedo/harness/extensions/lcm/extension.gleam b/src/albedo/harness/extensions/lcm/extension.gleam index d158db37e..4c7d56dcd 100644 --- a/src/albedo/harness/extensions/lcm/extension.gleam +++ b/src/albedo/harness/extensions/lcm/extension.gleam @@ -83,6 +83,7 @@ fn bundle( pub fn stored_prior( ledger: store.Store, session: String, + project: compaction.Project, history: List(types.Input), ) -> Result(compaction.Prior, String) { use available <- result.try(graph.storage_available(ledger)) @@ -100,7 +101,14 @@ pub fn stored_prior( snapshot, covered, )) - Ok(split(frontier, history, stats)) + use uncovered <- result.try(uncovered_of( + ledger, + project, + snapshot, + covered, + stats, + )) + Ok(split(frontier, history, uncovered)) } } } @@ -151,7 +159,8 @@ fn project( context: compaction.Context, history: List(types.Input), ) -> Result(compaction.View, String) { - use Saved(frontier:, stats:, ..) <- result.try(saved(context)) + use Saved(frontier:, ..) as state <- result.try(saved(context)) + use uncovered <- result.try(shown(context, state)) let window = compaction.effective_window(config.context_window_tokens, context, history) // Until the first compaction seeds the graph, the request is what the @@ -160,7 +169,7 @@ fn project( [] -> context.prior(history) |> result.map(fn(prior) { list.append(prior.folds, prior.rest) }) - _ -> Ok(projection(frontier, history, stats)) + _ -> Ok(projection(frontier, history, uncovered)) }) // The provider's count for the previous request, once this run has one. let #(measured, measure) = case context.reported { @@ -265,15 +274,16 @@ fn compact( [] -> Ok(Nil) _ -> summarize_leaf(context, frontier, eligible) }) - use Saved(frontier:, stats:, ..) <- result.try(saved(context)) + use Saved(frontier:, ..) as state <- result.try(saved(context)) + use uncovered <- result.try(shown(context, state)) use frontier <- result.try( - case landing(frontier, history, stats, context, capacity, config) { + case landing(frontier, history, uncovered, context, capacity, config) { Some(landing) -> - relieve(context, frontier, history, stats, landing, pressure_passes) + relieve(context, frontier, history, uncovered, landing, pressure_passes) None -> Ok(frontier) }, ) - let next = projection(frontier, history, stats) + let next = projection(frontier, history, uncovered) use _ <- result.try(compaction.require( context.pinned_tokens + compaction.estimate_inputs(next) < capacity || context.force, @@ -323,7 +333,7 @@ fn before_newest_turn( fn landing( frontier: List(graph.Node), history: List(types.Input), - stats: conversation.SourceStats, + uncovered: Uncovered, context: compaction.Context, capacity: Int, config: Config, @@ -331,7 +341,7 @@ fn landing( let trigger = capacity * trigger_percent(config, capacity) / 100 let floor = context.pinned_tokens - + compaction.estimate_inputs(projection(frontier, history, stats)) + + compaction.estimate_inputs(projection(frontier, history, uncovered)) - compaction.estimate_inputs(list.map(frontier, node_input)) case floor < trigger / 2, floor < trigger { True, _ -> Some(trigger / 2) @@ -349,13 +359,13 @@ fn relieve( context: compaction.Context, frontier: List(graph.Node), history: List(types.Input), - stats: conversation.SourceStats, + uncovered: Uncovered, landing: Int, passes: Int, ) -> Result(List(graph.Node), String) { let estimated = context.pinned_tokens - + compaction.estimate_inputs(projection(frontier, history, stats)) + + compaction.estimate_inputs(projection(frontier, history, uncovered)) use <- bool.guard(estimated <= landing || passes == 0, Ok(frontier)) case oldest_batch(frontier, estimated - landing, 0, []) { [] -> Ok(frontier) @@ -385,7 +395,7 @@ fn relieve( use next <- result.try(graph.frontier(context.store, context.session)) case batch { [_] -> Ok(next) - _ -> relieve(context, next, history, stats, landing, passes - 1) + _ -> relieve(context, next, history, uncovered, landing, passes - 1) } } } @@ -428,35 +438,43 @@ fn seed( ) -> Result(Bool, String) { use compaction.Prior(folds, rest) <- result.try(context.prior(history)) use <- bool.guard(folds == [], Ok(False)) - let unplaced = "the previous strategy's cut does not match the transcript" - use cut <- result.try( - conversation.latest_user_seq( - context.store, - snapshot, - list.count(rest, compaction.is_user), - ) - |> result.try(option.to_result(_, unplaced)), - ) - // `rest` starts at the cut's user message; its row must be that message. - use opening <- result.try( - conversation.fold_sources( - context.store, - snapshot, - cut, - cut, - None, - fn(_, item) { conversation.Stop(Some(item.entry.input)) }, - ), - ) - use _ <- result.try(compaction.require( - opening == option.from_result(list.first(rest)), - unplaced, - )) - use archived <- result.try(conversation.rows_before( + use cut <- result.try(conversation.latest_user_seq( context.store, snapshot, - cut, + list.count(rest, compaction.is_user), )) + // `rest` starts at the cut's user message, and the rows from there, + // projected as a turn's are, must be exactly `rest`. + use placed <- result.try(case cut { + None -> Ok(None) + Some(cut) -> + conversation.fold_sources( + context.store, + snapshot, + cut, + snapshot.upper, + [], + fn(rows, item) { + conversation.Continue([ + #(item.entry.provider, item.entry.input), + ..rows + ]) + }, + ) + |> result.try(fn(rows) { context.project(list.reverse(rows)) }) + |> result.map(fn(projected) { + case projected == rest { + True -> Some(cut) + False -> None + } + }) + }) + use archived <- result.try(case placed { + Some(cut) -> conversation.rows_before(context.store, snapshot, cut) + None -> Ok(None) + }) + // A cut the transcript cannot place seeds nothing: the compaction folds + // from the first row, as for a session that never had another strategy. case archived { None -> Ok(False) Some(#(first, last)) -> @@ -481,6 +499,13 @@ type Saved { ) } +/// What a request shows of the rows the frontier does not cover: those rows +/// as the request's provider reads them, and the newest user message when +/// the frontier has folded it. +type Uncovered { + Uncovered(tail: List(types.Input), task: Option(#(Int, types.Input))) +} + fn saved(context: compaction.Context) -> Result(Saved, String) { use snapshot <- result.try(conversation.snapshot( context.store, @@ -496,6 +521,56 @@ fn saved(context: compaction.Context) -> Result(Saved, String) { Ok(Saved(snapshot, covered, frontier, stats)) } +/// What a request built on `saved` shows of the rows its frontier does not +/// cover; nothing to read while the frontier is empty. +fn shown( + context: compaction.Context, + saved: Saved, +) -> Result(Uncovered, String) { + case saved.frontier { + [] -> Ok(Uncovered([], None)) + _ -> + uncovered_of( + context.store, + context.project, + saved.snapshot, + saved.covered, + saved.stats, + ) + } +} + +/// The rows after `covered`, projected the way a turn projects its history. +/// A cut falls between steps and so never inside one response's items, which +/// a conversion may merge or split: these rows project to exactly the end of +/// the history they belong to, whatever providers wrote it. +fn uncovered_of( + ledger: store.Store, + project: compaction.Project, + snapshot: conversation.Snapshot, + covered: Int, + stats: conversation.SourceStats, +) -> Result(Uncovered, String) { + let rows = fn(first, last) { + conversation.fold_sources(ledger, snapshot, first, last, [], fn(rows, item) { + conversation.Continue([#(item.entry.provider, item.entry.input), ..rows]) + }) + |> result.try(fn(rows) { project(list.reverse(rows)) }) + } + use tail <- result.try(rows(covered + 1, snapshot.upper)) + use task <- result.try(case stats.latest_user { + Some(seq) if seq <= covered -> + rows(seq, seq) + |> result.map(fn(inputs) { + list.first(inputs) + |> option.from_result + |> option.map(fn(input) { #(seq, input) }) + }) + _ -> Ok(None) + }) + Ok(Uncovered(tail, task)) +} + fn view( inputs: List(types.Input), frontier: List(graph.Node), @@ -540,47 +615,36 @@ fn view( fn projection( frontier: List(graph.Node), history: List(types.Input), - stats: conversation.SourceStats, + uncovered: Uncovered, ) -> List(types.Input) { - let compaction.Prior(folds, rest) = split(frontier, history, stats) + let compaction.Prior(folds, rest) = split(frontier, history, uncovered) list.append(folds, rest) } -/// The frontier's nodes, then every row they do not cover, verbatim. History -/// holds one input per transcript row, so the uncovered rows are its newest -/// `uncovered_rows` inputs, wherever the cursor falls inside a turn. When the -/// newest user message is folded, it stays verbatim too, before the first -/// node that reaches past it: a long agentic turn keeps its task word for -/// word however many times its steps fold. +/// The frontier's nodes, then every row they do not cover. When the newest +/// user message is folded, it stays verbatim too, before the first node that +/// reaches past it: a long agentic turn keeps its task word for word however +/// many times its steps fold. fn split( frontier: List(graph.Node), history: List(types.Input), - stats: conversation.SourceStats, + uncovered: Uncovered, ) -> compaction.Prior { - case frontier { - [] -> compaction.Prior([], history) - nodes -> { - let length = list.length(history) - let folds = case - stats.latest_user, - stats.after_latest_user >= stats.uncovered_rows - { - Some(seq), True -> { - let #(before, after) = - list.split_while(nodes, fn(node) { node.last_seq < seq }) - let task = - list.drop(history, length - 1 - stats.after_latest_user) - |> list.take(1) - list.flatten([ - list.map(before, node_input), - task, - list.map(after, node_input), - ]) - } - _, _ -> list.map(nodes, node_input) - } - compaction.Prior(folds, list.drop(history, length - stats.uncovered_rows)) + case frontier, uncovered.task { + [], _ -> compaction.Prior([], history) + nodes, Some(#(seq, task)) -> { + let #(before, after) = + list.split_while(nodes, fn(node) { node.last_seq < seq }) + compaction.Prior( + list.flatten([ + list.map(before, node_input), + [task], + list.map(after, node_input), + ]), + uncovered.tail, + ) } + nodes, None -> compaction.Prior(list.map(nodes, node_input), uncovered.tail) } } diff --git a/src/albedo/harness/extensions/snapcompact/extension.gleam b/src/albedo/harness/extensions/snapcompact/extension.gleam index 455482c9b..d079f2ff6 100644 --- a/src/albedo/harness/extensions/snapcompact/extension.gleam +++ b/src/albedo/harness/extensions/snapcompact/extension.gleam @@ -246,7 +246,11 @@ pub fn memory() -> extension.Extension { extension.FoldPlugin(compaction.Folds( "snapcompact", "snapcompact", - stored_prior, + // The archive cut is counted in user messages, which no provider's + // conversion changes. + fn(ledger, session, _, history) { + stored_prior(ledger, session, history) + }, )), ], initialise, diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index 38fe847ae..b35c96ede 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -506,6 +506,8 @@ fn prepare( |> list.reverse |> list.map(fn(row) { transcript.Entry(row.1, None, row.0, None, None) }) |> projection.for_model(state.profile, state.upstream.protocol) + // The projection answers newest first, as the session keeps history. + |> result.map(list.reverse) }, ) } diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 0dfeac62b..711df8a3b 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -1334,8 +1334,7 @@ pub fn prepare_view_scoped( images: types.ImageLimits, reported: Option(Int), compacting: fn() -> Nil, - project: fn(List(#(Option(String), types.Input))) -> - Result(List(types.Input), String), + project: compaction.Project, ) -> Result(compaction.Prepared, String) { view_scoped( runtime, @@ -1399,8 +1398,7 @@ fn view_scoped( images: types.ImageLimits, reported: Option(Int), compacting: fn() -> Nil, - project: fn(List(#(Option(String), types.Input))) -> - Result(List(types.Input), String), + project: compaction.Project, view: fn(compaction.Strategy, compaction.Context, List(types.Input)) -> Result(compaction.Prepared, String), ) -> Result(compaction.Prepared, String) { @@ -1434,6 +1432,7 @@ fn view_scoped( }), runtime.ledger, session.id, + project, ), reader(info), images, diff --git a/test/daemon/transcript_sources_test.gleam b/test/daemon/transcript_sources_test.gleam index 40141de76..bee0af210 100644 --- a/test/daemon/transcript_sources_test.gleam +++ b/test/daemon/transcript_sources_test.gleam @@ -101,7 +101,7 @@ pub fn metadata_range_and_backfill_resume_test() -> Nil { quarantined |> should.equal([#(260, <<0>>)]) let assert Ok(snapshot) = conversation.snapshot(ledger, "session") let assert Ok(stats) = conversation.source_stats(ledger, snapshot, 128) - stats |> should.equal(conversation.SourceStats(Some(260), True, 132, 132, 0)) + stats |> should.equal(conversation.SourceStats(Some(260), True, 132)) let assert Ok(selected) = conversation.fold_sources(ledger, snapshot, 128, 132, [], fn(acc, row) { conversation.Continue([row.source.seq, ..acc]) diff --git a/test/harness/lcm_preparation_test.gleam b/test/harness/lcm_preparation_test.gleam index cb571f093..d34d251fb 100644 --- a/test/harness/lcm_preparation_test.gleam +++ b/test/harness/lcm_preparation_test.gleam @@ -4,6 +4,7 @@ import albedo/daemon/conversation import albedo/daemon/family import albedo/daemon/store +import albedo/harness/compaction import albedo/harness/extensions import albedo/harness/extensions/lcm/extension as lcm import albedo/harness/extensions/lcm/graph @@ -93,13 +94,15 @@ pub fn below_trigger_and_stored_prior_do_not_decode_archived_payloads_test() -> types.Assistant("tail"), ]) = prepared should.be_true(string.contains(summary, "archived prefix")) - decodes |> should.equal(0) + // Only the two rows after the summary, which the request shows as the + // provider reads them; the archived prefix is never decoded. + decodes |> should.equal(2) let #(prior, decodes) = count_decodes(store.owner(ledger), fn() { - lcm.stored_prior(ledger, "preparation", inputs) + lcm.stored_prior(ledger, "preparation", compaction.unprojected, inputs) }) let assert Ok(_) = prior - decodes |> should.equal(0) + decodes |> should.equal(2) let assert Ok(_) = conversation.commit_from( ledger, @@ -140,7 +143,9 @@ pub fn below_trigger_and_stored_prior_do_not_decode_archived_payloads_test() -> ) }) let assert Ok(_) = compacted - decodes |> should.equal(3) + // The same three rows, then the two the new leaf leaves uncovered, read + // once as the request shows them to size any relief. + decodes |> should.equal(5) graph.last_seq(ledger, "preparation") |> should.equal(Ok(last.source.seq + 2)) runtime.stop(host) } diff --git a/test/harness/lcm_test.gleam b/test/harness/lcm_test.gleam index a947a23e9..64bfa6f08 100644 --- a/test/harness/lcm_test.gleam +++ b/test/harness/lcm_test.gleam @@ -556,7 +556,7 @@ fn archive() -> extension.Extension { [], [ extension.FoldPlugin( - compaction.Folds("archive", "archive", fn(_, _, history) { + compaction.Folds("archive", "archive", fn(_, _, _, history) { let assert Ok(#(_, rest)) = compaction.resume(history, compaction.cut_of(list.take(history, 4))) Ok(compaction.Prior([types.User("[archive pages]")], rest)) @@ -609,6 +609,105 @@ pub fn switching_to_lcm_points_at_the_archive_and_folds_the_live_rows_into_one_l runtime.stop(host) } +/// Another strategy's folds whose rest the transcript cannot be matched to: +/// its first message was rewritten after the cut. +fn mismatched_archive() -> extension.Extension { + extension.Extension( + "archive", + "stand-in whose cut the transcript cannot place", + [], + [ + extension.FoldPlugin( + compaction.Folds("archive", "archive", fn(_, _, _, history) { + let assert Ok(#(_, [_, ..rest])) = + compaction.resume(history, compaction.cut_of(list.take(history, 4))) + Ok( + compaction.Prior([types.User("[archive pages]")], [ + types.User("rewritten"), + ..rest + ]), + ) + }), + ), + ], + fn(_) { Ok(Nil) }, + ) +} + +pub fn an_unplaceable_cut_folds_from_the_first_row_instead_of_failing_test() -> Nil { + let #(host, session) = host_with(2000, [mismatched_archive()]) + let history = [ + types.User("old one"), + types.Assistant("old answer one"), + types.User("old two"), + types.Assistant("old answer two"), + types.User("live one"), + types.Assistant("live answer one"), + types.User("tail"), + ] + save(host, history) + let assert Ok(_) = + compact( + host, + session, + fn(request) { + should.be_true(mentions(request, "old one")) + Ok("everything before the tail") + }, + history, + ) + let assert Ok([leaf]) = graph.frontier(runtime.ledger(host), "lcm-test") + leaf.summary |> should.equal("everything before the tail") + runtime.stop(host) +} + +pub fn the_tail_is_the_uncovered_rows_as_the_provider_reads_them_test() -> Nil { + let #(host, session) = host(100_000) + let history = [ + types.User("the task"), + types.Assistant("first look " <> string.repeat("w", 30_000)), + types.User("next ask"), + types.Assistant("second look"), + ] + save(host, history) + let assert Ok(_) = compact(host, session, fn(_) { Ok("folded") }, history) + // A conversion that is not one input per row, as a protocol switch makes. + let project = fn(rows: List(#(option.Option(String), types.Input))) { + Ok( + list.flat_map(rows, fn(row) { + case row.1 { + types.Assistant(text) -> [types.Assistant("converted " <> text)] + input -> [input, input] + } + }), + ) + } + let assert Ok(prepared) = + runtime.prepare_view_scoped( + host, + session, + "model", + "model", + None, + "", + fn(_) { panic as "no compaction is due" }, + history, + False, + types.any_images, + None, + fn() { Nil }, + project, + ) + let assert [_, ..tail] = prepared.inputs + tail + |> should.equal([ + types.User("next ask"), + types.User("next ask"), + types.Assistant("converted second look"), + ]) + runtime.stop(host) +} + pub fn merges_keep_the_memory_sections_test() -> Nil { list.each(["Settled:", "Contracts:", "Plan:", "Open:"], fn(section) { should.be_true(string.contains(lcm.merge_instructions, section))