diff --git a/robot-docs/compaction.md b/robot-docs/compaction.md index 24c21fba6..605bbe1a3 100644 --- a/robot-docs/compaction.md +++ b/robot-docs/compaction.md @@ -6,7 +6,7 @@ The default session uses `rolling`. Selecting another strategy (`snapcompact` or `/compact` compacts now with the session's strategy. `/compact ` first makes the named strategy the session's own, as `/extensions` would, then compacts with it. Later requests read the projection that strategy saved. For example, `/compact rolling` before switching to a model without image input leaves a text summary that the new model can read. -A strategy returns prepared inputs and an observation for `/context`. The observation describes that preparation. The inspector does not read strategy state. The durable transcript supplies the source rows for each derived view. +A strategy has two halves. `project` returns the request its saved state makes of the history, an observation for `/context`, and whether that request reached the trigger; it only reads, never writing state or calling a model, so a request can be inspected or rebuilt without changing it. `compact` summarizes or archives history into the saved state, and runs only when a projection is due or `/compact` forces it. `compaction.prepare` composes them for every request: project, compact when due or forced, then project again; a request compacts at most once, so the projection after a compaction is sent even if it is still due. A saved state the history no longer matches is ignored by `project` and replaced by the next compaction, not deleted. Layers such as `notes` split the same way: `compact` runs on the request a compaction produced, `project` on every other one. The observation describes that preparation. The inspector does not read strategy state. The durable transcript supplies the source rows for each derived view. ## source references diff --git a/robot-docs/migrations.md b/robot-docs/migrations.md index 09066048a..a467ff751 100644 --- a/robot-docs/migrations.md +++ b/robot-docs/migrations.md @@ -79,7 +79,8 @@ cwd default when absent, then creates `work_cwd_id`; column, `paperclips/migrations/scope.apply` drops the now-unused workspace index left from the cwd-scoped vent era, and `paperclips/migrations/reply.apply` adds the non-null empty-default reply -column that makes a /paperclips answer durable. these upgrades run immediately +column that makes a /paperclips answer durable. `rolling/migrations/observation.apply` +drops the observation table rolling used to write and read straight back. these upgrades run immediately after their owner's table creation, so later extension initialisers can use the upgraded schema. embedding hosts call `runtime.migrate` after preparing core storage and before opening sessions. @@ -142,6 +143,7 @@ the upgraded schema. embedding hosts call | `paperclips/ledger.initialise`: title addition | `paperclips/migrations/title.apply`, contributed by paperclips | | `paperclips/ledger.initialise`: `paperclips_cwd` index creation | dropped from the schema; `paperclips/migrations/scope.apply` removes it from existing stores | | `paperclips/ledger.initialise`: reply column | `paperclips/migrations/reply.apply`, added with the global ledger | +| `rolling.initialise`: `rolling_compaction_observation` creation | dropped from the schema; `rolling/migrations/observation.apply` removes it from existing stores | `images.migrate` and `cells.migrate_images` are removed rather than wrapped: the migration implementations are separate from the live domain readers and diff --git a/src/albedo/harness/compaction.gleam b/src/albedo/harness/compaction.gleam index 62e14b45d..1f8d8d841 100644 --- a/src/albedo/harness/compaction.gleam +++ b/src/albedo/harness/compaction.gleam @@ -98,6 +98,15 @@ pub fn require(condition: Bool, message: String) -> Result(Nil, String) { } } +/// The pinned system prompt, extension context, and tool schemas leave room +/// in `capacity` for any history at all. +pub fn fits_pinned(context: Context, capacity: Int) -> Result(Nil, String) { + require( + context.pinned_tokens < capacity, + "context window is not large enough for pinned system, extension context, and tool schemas", + ) +} + /// The history a strategy sees when no fold provider is enabled. pub fn no_prior(history: List(types.Input)) -> Result(Prior, String) { Ok(Prior([], history)) @@ -289,20 +298,63 @@ pub fn tail_budget( pub type Notes { Notes( name: String, - apply: fn(Context, List(types.Input), Prepared) -> Result(Prepared, String), + /// Adds what the layer keeps to the request, reading only. + project: fn(Context, List(types.Input), Prepared) -> + Result(Prepared, String), + /// The same, right after the strategy compacted: the layer may rewrite + /// what it keeps from the history that just left the request. + compact: fn(Context, List(types.Input), Prepared) -> + Result(Prepared, String), ) } +/// What a strategy would send for one request from its saved state, and +/// whether that request reached its trigger. +pub type View { + View(inputs: List(types.Input), observation: Option(Observation), due: Bool) +} + /// Receives chronological history before each model request. Implementations /// own their summaries/state and must preserve valid tool call/result pairs. /// Failure stops the turn; the full durable transcript is never replaced. pub type Strategy { Strategy( name: String, - prepare: fn(Context, List(types.Input)) -> Result(Prepared, String), + /// The request under the saved state. It never writes state or calls a + /// model, so a request can be inspected or rebuilt without changing it. + project: fn(Context, List(types.Input)) -> Result(View, String), + /// Folds history into the saved state now, because a projection was due + /// or `context.force` asks; answers whether the saved state changed. + compact: fn(Context, List(types.Input)) -> Result(Bool, String), ) } +/// The request `strategy` sends for `history`: its projection, compacted +/// first when forced or due. A request compacts at most once, so the +/// projection after a compaction is sent even if it is still due. +pub fn prepare( + strategy: Strategy, + context: Context, + history: List(types.Input), +) -> Result(Prepared, String) { + let viewing = Context(..context, force: False) + let compacted = fn() { + use changed <- result.try(strategy.compact(context, history)) + use view <- result.try(strategy.project(viewing, history)) + Ok(Prepared(view.inputs, view.observation, changed)) + } + case context.force { + True -> compacted() + False -> { + use view <- result.try(strategy.project(viewing, history)) + case view.due { + True -> compacted() + False -> Ok(Prepared(view.inputs, view.observation, False)) + } + } + } +} + /// A deliberately approximate request-size estimate. It is used only when a /// provider has not supplied a tokenizer for the current request. fn estimate_text(text: String) -> Int { diff --git a/src/albedo/harness/extensions/lcm/extension.gleam b/src/albedo/harness/extensions/lcm/extension.gleam index d709a5d20..c31dbfa08 100644 --- a/src/albedo/harness/extensions/lcm/extension.gleam +++ b/src/albedo/harness/extensions/lcm/extension.gleam @@ -57,10 +57,17 @@ fn bundle( ["lcm-memory"], [ harness_extension.CompactionPlugin( - compaction.Strategy("lcm", fn(context, history) { - use config <- result.try(resolve()) - prepare(config, context, history) - }), + compaction.Strategy( + "lcm", + fn(context, history) { + use config <- result.try(resolve()) + project(config, context, history) + }, + fn(context, history) { + use config <- result.try(resolve()) + compact(config, context, history) + }, + ), ), harness_extension.CleanPlugin(graph.forget_session), ], @@ -117,31 +124,22 @@ fn validate(config: Config) -> Result(Config, String) { |> result.replace(config) } -fn prepare( +/// The stored frontier's summary nodes ahead of a verbatim tail, and whether +/// that request reached the trigger. +fn project( config: Config, context: compaction.Context, history: List(types.Input), -) -> Result(compaction.Prepared, String) { - use snapshot <- result.try(conversation.snapshot( - context.store, - context.session, - )) - use covered <- result.try(graph.last_seq(context.store, context.session)) - use frontier <- result.try(graph.frontier(context.store, context.session)) - use stats <- result.try(conversation.source_stats( - context.store, - snapshot, - covered, - )) +) -> Result(compaction.View, String) { + use Saved(frontier:, stats:, ..) <- result.try(saved(context)) let window = rolling.effective_window(config.context_window_tokens, context, history) - let tail_budget = - option.map(window, fn(window) { window.tokens * config.tail_percent / 100 }) - let current = projection(frontier, history, stats, tail_budget, 1) + let current = + projection(frontier, history, stats, tail_budget(config, window), 1) let estimated = context.pinned_tokens + compaction.estimate_inputs(current) case window { None -> - Ok(prepared( + Ok(view( current, frontier, "unknown", @@ -150,128 +148,141 @@ fn prepare( estimated, config, history, + False, )) Some(compaction.Capacity(tokens: capacity, source: capacity_source)) -> { - use _ <- result.try(compaction.require( - context.pinned_tokens < capacity, - "context window is not large enough for pinned system, extension context, and tool schemas", - )) - case + use _ <- result.try(compaction.fits_pinned(context, capacity)) + Ok(view( + current, + frontier, + case frontier { + [] -> "not_needed" + _ -> "compacted" + }, + "estimated from current request projection; window from " + <> capacity_source, + Some(capacity), + estimated, + config, + history, compaction.triggered( - context.force, + False, estimated, Some(capacity), config.trigger_percent, - ) - { - False -> - Ok(prepared( - current, - frontier, - case frontier { - [] -> "not_needed" - _ -> "compacted" - }, - "estimated from current request projection; window from " - <> capacity_source, - Some(capacity), - estimated, - config, - history, - )) - True -> { - let previous_frontier = frontier - use latest_user <- result.try(option.to_result( - stats.latest_user, - "LCM needs a user message to retain as its tail", - )) - use eligible <- result.try(case covered + 1 < latest_user { - False -> Ok([]) - True -> - conversation.fold_sources( - context.store, - snapshot, - covered + 1, - latest_user - 1, - [], - fn(rows, item) { conversation.Continue([item, ..rows]) }, - ) - }) - let eligible = list.reverse(eligible) - use _ <- result.try(compaction.require( - eligible != [] || frontier != [], - "cannot compact without an older complete conversation unit", - )) - let summary_limit = - int.min( - summary_tokens, - int.max(32, { capacity - context.pinned_tokens } / 4), - ) - use leaves <- result.try(summarize_leaves( - context, - eligible, - summary_limit, - )) - use _ <- result.try(graph.save_leaves( - context.store, - context.session, - leaves, - )) - use frontier <- result.try(graph.frontier( - context.store, - context.session, - )) - use covered <- result.try(graph.last_seq( - context.store, - context.session, - )) - use stats <- result.try(conversation.source_stats( - context.store, - snapshot, - covered, - )) - use frontier <- result.try(condense_until_fit( - context, - frontier, - history, - stats, - tail_budget, - capacity, - summary_limit, - 0, - )) - let next = projection(frontier, history, stats, tail_budget, 1) - let next_estimated = - context.pinned_tokens + compaction.estimate_inputs(next) - use _ <- result.try(compaction.require( - next_estimated < capacity || context.force, - "LCM summaries and the newest conversation/tool unit do not fit the context window", - )) - let prepared = - prepared( - next, - frontier, - "compacted", - "estimated from source-backed summary nodes; window from " - <> capacity_source, - Some(capacity), - next_estimated, - config, - history, - ) - Ok( - compaction.Prepared( - ..prepared, - compacted: frontier != previous_frontier, - ), - ) - } - } + ), + )) } } } -fn prepared( +/// Summarizes the complete units after the frontier into leaves, then +/// condenses the frontier until the request fits; answers whether the +/// frontier changed. +fn compact( + config: Config, + context: compaction.Context, + history: List(types.Input), +) -> Result(Bool, String) { + use Saved(snapshot, covered, frontier, stats) <- result.try(saved(context)) + let window = + rolling.effective_window(config.context_window_tokens, context, history) + use compaction.Capacity(tokens: capacity, ..) <- result.try(option.to_result( + window, + "no configured or catalogued context window to compact against", + )) + use _ <- result.try(compaction.fits_pinned(context, capacity)) + let tail_budget = tail_budget(config, window) + let previous_frontier = frontier + use latest_user <- result.try(option.to_result( + stats.latest_user, + "LCM needs a user message to retain as its tail", + )) + use eligible <- result.try(case covered + 1 < latest_user { + False -> Ok([]) + True -> + conversation.fold_sources( + context.store, + snapshot, + covered + 1, + latest_user - 1, + [], + fn(rows, item) { conversation.Continue([item, ..rows]) }, + ) + }) + let eligible = list.reverse(eligible) + use _ <- result.try(compaction.require( + eligible != [] || frontier != [], + "cannot compact without an older complete conversation unit", + )) + let summary_limit = + int.min( + summary_tokens, + int.max(32, { capacity - context.pinned_tokens } / 4), + ) + use leaves <- result.try(summarize_leaves(context, eligible, summary_limit)) + use _ <- result.try(graph.save_leaves(context.store, context.session, leaves)) + use frontier <- result.try(graph.frontier(context.store, context.session)) + use covered <- result.try(graph.last_seq(context.store, context.session)) + use stats <- result.try(conversation.source_stats( + context.store, + snapshot, + covered, + )) + use frontier <- result.try(condense_until_fit( + context, + frontier, + history, + stats, + tail_budget, + capacity, + summary_limit, + 0, + )) + let next = projection(frontier, history, stats, tail_budget, 1) + use _ <- result.try(compaction.require( + context.pinned_tokens + compaction.estimate_inputs(next) < capacity + || context.force, + "LCM summaries and the newest conversation/tool unit do not fit the context window", + )) + Ok(frontier != previous_frontier) +} + +/// The session's saved graph against its transcript: the append boundary, +/// the last row the graph covers, its frontier, and the rows after it. +type Saved { + Saved( + snapshot: conversation.Snapshot, + covered: Int, + frontier: List(graph.Node), + stats: conversation.SourceStats, + ) +} + +fn saved(context: compaction.Context) -> Result(Saved, String) { + use snapshot <- result.try(conversation.snapshot( + context.store, + context.session, + )) + use covered <- result.try(graph.last_seq(context.store, context.session)) + use frontier <- result.try(graph.frontier(context.store, context.session)) + use stats <- result.try(conversation.source_stats( + context.store, + snapshot, + covered, + )) + Ok(Saved(snapshot, covered, frontier, stats)) +} + +/// The verbatim tail's share of the window, when there is one. +fn tail_budget( + config: Config, + window: Option(compaction.Capacity), +) -> Option(Int) { + option.map(window, fn(window) { window.tokens * config.tail_percent / 100 }) +} + +fn view( inputs: List(types.Input), frontier: List(graph.Node), status: String, @@ -280,8 +291,9 @@ fn prepared( estimated: Int, config: Config, original: List(types.Input), -) -> compaction.Prepared { - compaction.Prepared( + due: Bool, +) -> compaction.View { + compaction.View( inputs, Some(compaction.observation( "lcm", @@ -298,7 +310,7 @@ fn prepared( list.length(original), list.length(inputs), )), - False, + due, ) } diff --git a/src/albedo/harness/extensions/notes/extension.gleam b/src/albedo/harness/extensions/notes/extension.gleam index 09c80bded..72aadd0b3 100644 --- a/src/albedo/harness/extensions/notes/extension.gleam +++ b/src/albedo/harness/extensions/notes/extension.gleam @@ -64,7 +64,17 @@ pub fn extension() -> extension.Extension { "Notes the model writes for itself at every compaction", [], [ - extension.NotesPlugin(compaction.Notes("notes", apply)), + extension.NotesPlugin( + compaction.Notes( + "notes", + fn(context, history, prepared) { + apply(context, history, prepared, False) + }, + fn(context, history, prepared) { + apply(context, history, prepared, True) + }, + ), + ), extension.CleanPlugin(fn(db, session) { store.forget_session(db, ["compaction_notes"], session) }), @@ -84,10 +94,11 @@ fn apply( context: compaction.Context, history: List(types.Input), prepared: compaction.Prepared, + compacted: Bool, ) -> Result(compaction.Prepared, String) { use config <- result.try(load_config()) use saved <- result.try(load(context.store, context.session)) - use #(saved, failure) <- result.try(case prepared.compacted { + use #(saved, failure) <- result.try(case compacted { True -> refresh(config, context, history, prepared.inputs, saved) False -> Ok(#(saved, None)) }) diff --git a/src/albedo/harness/extensions/rolling/extension.gleam b/src/albedo/harness/extensions/rolling/extension.gleam index 958b5287b..72faf54d9 100644 --- a/src/albedo/harness/extensions/rolling/extension.gleam +++ b/src/albedo/harness/extensions/rolling/extension.gleam @@ -4,6 +4,7 @@ import albedo/daemon/store import albedo/harness/compaction import albedo/harness/extension +import albedo/harness/extensions/rolling/migrations/observation import albedo/harness/settings import albedo/harness/tool import albedo/openai_api/types @@ -29,26 +30,6 @@ pub type Config { ) } -type Observation { - Observation( - status: String, - source: String, - capacity_tokens: Option(Int), - estimated_tokens: Int, - trigger_percent: Int, - original_items: Int, - original_bytes: Int, - summary_items: Int, - summary_bytes: Int, - recap_items: Int, - recap_bytes: Int, - tail_items: Int, - tail_bytes: Int, - prepared_items: Int, - prepared_bytes: Int, - ) -} - type State { State(summary: String, cut: compaction.Cut) } @@ -107,12 +88,9 @@ fn bundle(strategy: compaction.Strategy) -> extension.Extension { [], [ extension.CompactionPlugin(strategy), + extension.MigrationPlugin(extension.SchemaMigration(observation.apply)), extension.CleanPlugin(fn(db, session) { - store.forget_session( - db, - ["rolling_compaction_state", "rolling_compaction_observation"], - session, - ) + store.forget_session(db, ["rolling_compaction_state"], session) }), ], initialise, @@ -120,66 +98,191 @@ fn bundle(strategy: compaction.Strategy) -> extension.Extension { } pub fn configured_extension(config: Config) -> extension.Extension { - bundle(strategy(config)) + bundle(strategy(fn() { validate_config(config) })) } pub fn extension() -> extension.Extension { - bundle(compaction.Strategy("rolling", prepare_with_settings)) + bundle(with_settings()) } -/// The rolling projection under the saved settings, for a strategy that falls +/// The rolling strategy under the saved settings, for a strategy that falls /// back to text for a model without image input. -pub fn prepare_with_settings( - context: compaction.Context, - history: List(types.Input), -) -> Result(compaction.Prepared, String) { - use config <- result.try(load_config()) - prepare_view(config, context, history) +pub fn with_settings() -> compaction.Strategy { + strategy(load_config) } -fn strategy(config: Config) -> compaction.Strategy { - compaction.Strategy("rolling", fn(context, history) { - use valid <- result.try(validate_config(config)) - prepare_view(valid, context, history) - }) +/// The strategy under the settings `resolve` answers per request. +fn strategy(resolve: fn() -> Result(Config, String)) -> compaction.Strategy { + compaction.Strategy( + "rolling", + fn(context, history) { + use config <- result.try(resolve()) + project(config, context, history) + }, + fn(context, history) { + use config <- result.try(resolve()) + compact(config, context, history) + }, + ) } -fn prepare_view( +/// The saved summary, recap, and tail this history still matches, or the +/// history itself, and whether it reached the trigger. A saved row the +/// history no longer matches is ignored here and replaced by the next +/// compaction. +fn project( config: Config, context: compaction.Context, history: List(types.Input), -) -> Result(compaction.Prepared, String) { +) -> Result(compaction.View, String) { use compaction.Prior(folds, rest) <- result.try(context.prior(history)) - let folded = list.append(folds, rest) let carries_folds = folds != [] - use #(inputs, compacted) <- result.try(prepare(config, context, folded)) - // Diagnostics must not fail a request after its projection was committed. - let recorded = - observation(context.store, context.session) |> result.unwrap(None) - let observed = - option.map(recorded, fn(recorded) { - compaction.observation( + let history = list.append(folds, rest) + use saved <- result.try(load_state(context.store, context.session)) + let #(resumed, invalidated) = resume(saved, context.source, history) + let current = projection(resumed, history) + let estimated = + context.pinned_tokens + compaction.estimate_inputs(current.inputs) + // A saved projection this history still matches is already a compaction. + let status_of = fn(when_absent) { + case resumed { + Some(_) -> "compacted" + None -> when_absent + } + } + let view = fn(status, source, capacity, due) { + let history_source = case status, carries_folds { + "compacted", True -> + "durable transcript through stored folds, rolling summary, recent user recap, and verbatim tail" + "compacted", False -> + "durable transcript through rolling summary + recent user recap + verbatim tail" + _, True -> + "durable transcript through stored folds and verbatim tail; rolling observation attached" + _, False -> "durable transcript; rolling compaction observation attached" + } + compaction.View( + current.inputs, + Some(compaction.observation( "rolling", - recorded.status, - recorded.source, - case recorded.status, carries_folds { - "compacted", True -> - "durable transcript through stored folds, rolling summary, recent user recap, and verbatim tail" - "compacted", False -> - "durable transcript through rolling summary + recent user recap + verbatim tail" - _, True -> - "durable transcript through stored folds and verbatim tail; rolling observation attached" - _, False -> - "durable transcript; rolling compaction observation attached" - }, - recorded.trigger_percent, - recorded.capacity_tokens, - recorded.estimated_tokens, - recorded.original_items, - recorded.prepared_items, - ) - }) - Ok(compaction.Prepared(inputs, observed, compacted)) + status, + source, + history_source, + config.trigger_percent, + capacity, + estimated, + list.length(history), + list.length(current.inputs), + )), + due, + ) + } + case effective_window(config.context_window_tokens, context, history) { + None -> + // Without a window there is no threshold to compare, but a saved + // projection is still the user's standing instruction: honor it. + Ok(view( + status_of("unknown"), + "estimated; no configured or catalogued context window", + None, + False, + )) + Some(compaction.Capacity(capacity, capacity_source)) -> { + use _ <- result.try(compaction.fits_pinned(context, capacity)) + let source = case invalidated { + True -> + "estimated after the transcript changed under the saved cut; saved projection ignored" + False -> "estimated from current request projection" + } + Ok(view( + status_of("not_needed"), + source <> "; window from " <> capacity_source, + Some(capacity), + compaction.triggered( + False, + estimated, + Some(capacity), + config.trigger_percent, + ), + )) + } + } +} + +/// Summarizes what leaves the request into the saved summary and saves the +/// new cut, keeping a verbatim tail within the tail budget. +fn compact( + config: Config, + context: compaction.Context, + history: List(types.Input), +) -> Result(Bool, String) { + let compaction.Context( + store: ledger, + session:, + model:, + source:, + pinned_tokens:, + force:, + summarize:, + .., + ) = context + use compaction.Prior(folds, rest) <- result.try(context.prior(history)) + let history = list.append(folds, rest) + use compaction.Capacity(capacity, _) <- result.try(option.to_result( + effective_window(config.context_window_tokens, context, history), + "no configured or catalogued context window to compact against", + )) + use _ <- result.try(compaction.fits_pinned(context, capacity)) + use saved <- result.try(load_state(ledger, session)) + let #(previous_summary, evicted, rest) = case resume(saved, source, history) { + #(Some(Resumed(state, evicted, tail)), _) -> #( + Some(state.summary), + evicted, + tail, + ) + #(None, _) -> #(None, [], history) + } + let tail_budget = + compaction.tail_budget( + capacity, + compaction.estimate_inputs(history), + force, + config.tail_percent, + ) + let #(newly_evicted, tail) = compaction.split_tail(rest, tail_budget) + use _ <- result.try(compaction.require( + history != [], + "cannot compact an empty conversation", + )) + use _ <- result.try(compaction.require( + newly_evicted != [], + "cannot compact further without splitting the newest conversation/tool unit", + )) + use summary <- result.try(summarize_chunks( + summarize, + model, + previous_summary, + chunk_units( + list.map(newly_evicted, fn(item) { + #([item], compaction.estimate_input(item)) + }), + int.max(1000, capacity / 2), + ), + int.min(2048, int.max(128, capacity / 10)), + )) + let next = view_of(summary, tail, history) + // The fit guarantee belongs to a real window; a forced compaction's + // synthetic window is a tail budget, so the projection always saves. + use _ <- result.try(compaction.require( + pinned_tokens + compaction.estimate_inputs(next.inputs) < capacity || force, + "summary, recap, and indivisible recent tail do not fit the context window", + )) + let evicted = list.append(evicted, newly_evicted) + use _ <- result.try(save_state( + ledger, + session, + State(summary, compaction.cut_of(evicted)), + )) + Ok(True) } /// The config shape the compaction strategies share: an optional positive @@ -241,7 +344,7 @@ pub fn initialise(ledger: store.Store) -> Result(Nil, String) { store.query(ledger, fn(db) { store.exec( db, - "CREATE TABLE IF NOT EXISTS rolling_compaction_state(session TEXT PRIMARY KEY,summary TEXT NOT NULL,cutoff_count INTEGER NOT NULL CHECK(cutoff_count >= 0),source_hash TEXT NOT NULL); CREATE TABLE IF NOT EXISTS rolling_compaction_observation(session TEXT PRIMARY KEY,status TEXT NOT NULL,source TEXT NOT NULL,capacity_tokens INTEGER,estimated_tokens INTEGER NOT NULL,trigger_percent INTEGER NOT NULL,original_items INTEGER NOT NULL,original_bytes INTEGER NOT NULL,summary_items INTEGER NOT NULL,summary_bytes INTEGER NOT NULL,recap_items INTEGER NOT NULL,recap_bytes INTEGER NOT NULL,tail_items INTEGER NOT NULL,tail_bytes INTEGER NOT NULL,prepared_items INTEGER NOT NULL,prepared_bytes INTEGER NOT NULL);", + "CREATE TABLE IF NOT EXISTS rolling_compaction_state(session TEXT PRIMARY KEY,summary TEXT NOT NULL,cutoff_count INTEGER NOT NULL CHECK(cutoff_count >= 0),source_hash TEXT NOT NULL);", ) }) } @@ -258,53 +361,6 @@ fn read_one( |> result.map(fn(rows) { list.first(rows) |> option.from_result }) } -fn observation( - ledger: store.Store, - session: String, -) -> Result(Option(Observation), String) { - read_one( - ledger, - "SELECT status,source,capacity_tokens,estimated_tokens,trigger_percent,original_items,original_bytes,summary_items,summary_bytes,recap_items,recap_bytes,tail_items,tail_bytes,prepared_items,prepared_bytes FROM rolling_compaction_observation WHERE session=?", - [sqlight.text(session)], - observation_decoder(), - ) -} - -fn observation_decoder() -> decode.Decoder(Observation) { - use status <- decode.field(0, decode.string) - use source <- decode.field(1, decode.string) - use capacity <- decode.field(2, decode.optional(decode.int)) - use estimated <- decode.field(3, decode.int) - use trigger <- decode.field(4, decode.int) - use original_items <- decode.field(5, decode.int) - use original_bytes <- decode.field(6, decode.int) - use summary_items <- decode.field(7, decode.int) - use summary_bytes <- decode.field(8, decode.int) - use recap_items <- decode.field(9, decode.int) - use recap_bytes <- decode.field(10, decode.int) - use tail_items <- decode.field(11, decode.int) - use tail_bytes <- decode.field(12, decode.int) - use prepared_items <- decode.field(13, decode.int) - use prepared_bytes <- decode.field(14, decode.int) - decode.success(Observation( - status, - source, - capacity, - estimated, - trigger, - original_items, - original_bytes, - summary_items, - summary_bytes, - recap_items, - recap_bytes, - tail_items, - tail_bytes, - prepared_items, - prepared_bytes, - )) -} - fn row_decoder() -> decode.Decoder(Row) { use summary <- decode.field(0, decode.string) use cutoff <- decode.field(1, decode.int) @@ -324,188 +380,6 @@ fn load_state( ) } -fn prepare( - config: Config, - context: compaction.Context, - history: List(types.Input), -) -> Result(#(List(types.Input), Bool), String) { - let compaction.Context( - store: ledger, - session:, - model:, - source:, - pinned_tokens:, - force:, - summarize:, - .., - ) = context - let window = effective_window(config.context_window_tokens, context, history) - use saved <- result.try(load_state(ledger, session)) - use #(resumed, invalidated) <- result.try(resume( - ledger, - session, - saved, - source, - history, - )) - use _ <- result.try(case invalidated { - True -> delete_state(ledger, session) - False -> Ok(Nil) - }) - let current = projection(resumed, history) - // A saved projection this history still matches is already a compaction; - // each branch names what to report when there is none. - let status_of = fn(when_absent) { - case resumed { - Some(_) -> "compacted" - None -> when_absent - } - } - // The observation's shape is fixed; only the status, window facts, and the - // projection it describes vary per branch. - let observe = fn(status, provenance, capacity, tokens, view: View) { - observation_for( - status, - provenance, - capacity, - tokens, - config.trigger_percent, - history, - view, - ) - } - // A branch that sends the projection as it stands records what it observed. - let report = fn(status, provenance, capacity, tokens, view: View) { - use _ <- result.try(save_observation( - ledger, - session, - observe(status, provenance, capacity, tokens, view), - )) - Ok(#(view.inputs, False)) - } - case window { - None -> - // Without a window there is no threshold to compare, but a saved - // projection is still the user's standing instruction: honor it. - report( - status_of("unknown"), - "estimated; no configured or catalogued context window", - None, - pinned_tokens + compaction.estimate_inputs(current.inputs), - current, - ) - Some(compaction.Capacity(capacity, capacity_source)) -> { - let estimated = pinned_tokens + compaction.estimate_inputs(current.inputs) - case pinned_tokens >= capacity { - True -> { - let _ = - report( - "limitation", - "estimated pinned system, extension context, and tool schemas; window from " - <> capacity_source, - Some(capacity), - estimated, - current, - ) - Error( - "context window is not large enough for pinned system, extension context, and tool schemas", - ) - } - False -> - case - compaction.triggered( - force, - estimated, - Some(capacity), - config.trigger_percent, - ) - { - False -> { - let source = case invalidated { - True -> - "estimated after the transcript changed under the saved cut; saved projection reset" - False -> "estimated from current request projection" - } - report( - status_of("not_needed"), - source <> "; window from " <> capacity_source, - Some(capacity), - estimated, - current, - ) - } - True -> { - let #(previous_summary, evicted, rest) = case resumed { - Some(Resumed(state, evicted, tail)) -> #( - Some(state.summary), - evicted, - tail, - ) - None -> #(None, [], history) - } - let tail_budget = - compaction.tail_budget( - capacity, - compaction.estimate_inputs(history), - force, - config.tail_percent, - ) - let #(newly_evicted, tail) = - compaction.split_tail(rest, tail_budget) - use _ <- result.try(compaction.require( - history != [], - "cannot compact an empty conversation", - )) - use _ <- result.try(compaction.require( - newly_evicted != [], - "cannot compact further without splitting the newest conversation/tool unit", - )) - use summary <- result.try(summarize_chunks( - summarize, - model, - previous_summary, - chunk_units( - list.map(newly_evicted, fn(item) { - #([item], compaction.estimate_input(item)) - }), - int.max(1000, capacity / 2), - ), - int.min(2048, int.max(128, capacity / 10)), - )) - let evicted = list.append(evicted, newly_evicted) - let next_state = State(summary, compaction.cut_of(evicted)) - let next = view_of(summary, tail, history) - let next_estimated = - pinned_tokens + compaction.estimate_inputs(next.inputs) - // The fit guarantee belongs to a real window; a forced compaction's - // synthetic window is a tail budget, so the projection always saves. - use _ <- result.try(compaction.require( - next_estimated < capacity || force, - "summary, recap, and indivisible recent tail do not fit the context window", - )) - let observation = - observe( - "compacted", - "estimated from current request projection; window from " - <> capacity_source, - Some(capacity), - next_estimated, - next, - ) - use _ <- result.try(save_compaction( - ledger, - session, - next_state, - observation, - )) - Ok(#(next.inputs, True)) - } - } - } - } - } -} - /// Folds evicted history into the summary one chunk at a time, so a long /// eviction, such as a large window's history before a switch to a smaller /// model, never asks the summarizer for more than half its window. @@ -626,24 +500,25 @@ fn recap(history: List(types.Input)) -> List(types.Input) { /// The saved state this history still matches, and whether a saved row was /// invalidated. A legacy row validates the way it was written, by item count -/// under one source, and is rewritten as a user-message cut once it matches. +/// under one source; it resumes as a user-message cut, which the next +/// compaction saves in its place. fn resume( - ledger: store.Store, - session: String, saved: Option(Row), source: String, history: List(types.Input), -) -> Result(#(Option(Resumed), Bool), String) { +) -> #(Option(Resumed), Bool) { case saved { - None -> Ok(#(None, False)) + None -> #(None, False) Some(Row(summary, cutoff, cut_hash)) -> case string.split_once(cut_hash, cut_prefix) { Ok(#("", fingerprint)) -> { let state = State(summary, compaction.Cut(cutoff, fingerprint)) case compaction.resume(history, state.cut) { - Ok(#(evicted, tail)) -> - Ok(#(Some(Resumed(state, evicted, tail)), False)) - Error(Nil) -> Ok(#(None, True)) + Ok(#(evicted, tail)) -> #( + Some(Resumed(state, evicted, tail)), + False, + ) + Error(Nil) -> #(None, True) } } _ -> { @@ -653,17 +528,16 @@ fn resume( && { compaction.fingerprint(#(source, evicted)) == cut_hash // A hash saved before images were stored covered their - // payload bytes; checking it reads them once. + // payload bytes; checking it reads them. || has_images(evicted) && legacy_fingerprint(#(source, evicted)) == Ok(cut_hash) } case matches, tail { True, [types.User(_), ..] | True, [types.UserImage(_, _), ..] -> { let state = State(summary, compaction.cut_of(evicted)) - use _ <- result.try(save_cut(ledger, session, state.cut)) - Ok(#(Some(Resumed(state, evicted, tail)), False)) + #(Some(Resumed(state, evicted, tail)), False) } - _, _ -> Ok(#(None, True)) + _, _ -> #(None, True) } } } @@ -680,124 +554,22 @@ fn has_images(inputs: List(types.Input)) -> Bool { }) } -fn save_cut( +fn save_state( ledger: store.Store, session: String, - cut: compaction.Cut, + state: State, ) -> Result(Nil, String) { store.write( ledger, - "UPDATE rolling_compaction_state SET cutoff_count=?,source_hash=? WHERE session=?", - [ - sqlight.int(cut.users), - sqlight.text(cut_prefix <> cut.fingerprint), - sqlight.text(session), - ], - ) -} - -fn observation_for( - status: String, - source: String, - capacity: Option(Int), - estimated: Int, - trigger_percent: Int, - original: List(types.Input), - view: View, -) -> Observation { - let measure = fn(inputs) { - #(list.length(inputs), compaction.inputs_bytes(inputs)) - } - let #(original_items, original_bytes) = measure(original) - let #(summary_items, summary_bytes) = measure(view.summary) - let #(recap_items, recap_bytes) = measure(view.recap) - let #(tail_items, tail_bytes) = measure(view.tail) - Observation( - status, - source, - capacity, - estimated, - trigger_percent, - original_items, - original_bytes, - summary_items, - summary_bytes, - recap_items, - recap_bytes, - tail_items, - tail_bytes, - summary_items + recap_items + tail_items, - summary_bytes + recap_bytes + tail_bytes, - ) -} - -fn save_observation( - ledger: store.Store, - session: String, - observation: Observation, -) -> Result(Nil, String) { - store.query(ledger, fn(db) { write_observation(db, session, observation) }) -} - -fn save_compaction( - ledger: store.Store, - session: String, - state: State, - observation: Observation, -) -> Result(Nil, String) { - store.query(ledger, fn(db) { - store.transaction(db, fn() { - use _ <- result.try( - store.run( - db, - "INSERT INTO rolling_compaction_state(session,summary,cutoff_count,source_hash) VALUES(?,?,?,?) ON CONFLICT(session) DO UPDATE SET summary=excluded.summary,cutoff_count=excluded.cutoff_count,source_hash=excluded.source_hash", - [ - sqlight.text(session), - sqlight.text(state.summary), - sqlight.int(state.cut.users), - sqlight.text(cut_prefix <> state.cut.fingerprint), - ], - ), - ) - write_observation(db, session, observation) - }) - }) -} - -fn write_observation( - db: sqlight.Connection, - session: String, - observation: Observation, -) -> Result(Nil, String) { - store.run( - db, - "INSERT INTO rolling_compaction_observation(session,status,source,capacity_tokens,estimated_tokens,trigger_percent,original_items,original_bytes,summary_items,summary_bytes,recap_items,recap_bytes,tail_items,tail_bytes,prepared_items,prepared_bytes) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(session) DO UPDATE SET status=excluded.status,source=excluded.source,capacity_tokens=excluded.capacity_tokens,estimated_tokens=excluded.estimated_tokens,trigger_percent=excluded.trigger_percent,original_items=excluded.original_items,original_bytes=excluded.original_bytes,summary_items=excluded.summary_items,summary_bytes=excluded.summary_bytes,recap_items=excluded.recap_items,recap_bytes=excluded.recap_bytes,tail_items=excluded.tail_items,tail_bytes=excluded.tail_bytes,prepared_items=excluded.prepared_items,prepared_bytes=excluded.prepared_bytes", + "INSERT INTO rolling_compaction_state(session,summary,cutoff_count,source_hash) VALUES(?,?,?,?) ON CONFLICT(session) DO UPDATE SET summary=excluded.summary,cutoff_count=excluded.cutoff_count,source_hash=excluded.source_hash", [ sqlight.text(session), - sqlight.text(observation.status), - sqlight.text(observation.source), - sqlight.nullable(sqlight.int, observation.capacity_tokens), - sqlight.int(observation.estimated_tokens), - sqlight.int(observation.trigger_percent), - sqlight.int(observation.original_items), - sqlight.int(observation.original_bytes), - sqlight.int(observation.summary_items), - sqlight.int(observation.summary_bytes), - sqlight.int(observation.recap_items), - sqlight.int(observation.recap_bytes), - sqlight.int(observation.tail_items), - sqlight.int(observation.tail_bytes), - sqlight.int(observation.prepared_items), - sqlight.int(observation.prepared_bytes), + sqlight.text(state.summary), + sqlight.int(state.cut.users), + sqlight.text(cut_prefix <> state.cut.fingerprint), ], ) } -fn delete_state(ledger: store.Store, session: String) -> Result(Nil, String) { - store.write(ledger, "DELETE FROM rolling_compaction_state WHERE session=?", [ - sqlight.text(session), - ]) -} - @external(erlang, "albedo_rolling", "legacy_fingerprint") fn legacy_fingerprint(value: a) -> Result(String, Nil) diff --git a/src/albedo/harness/extensions/rolling/migrations/observation.gleam b/src/albedo/harness/extensions/rolling/migrations/observation.gleam new file mode 100644 index 000000000..13d162924 --- /dev/null +++ b/src/albedo/harness/extensions/rolling/migrations/observation.gleam @@ -0,0 +1,10 @@ +//// Rolling kept a copy of each request's observation in its own table and +//// read it straight back; the observation now travels with the prepared +//// request alone, so existing stores drop the table. + +import albedo/daemon/store +import sqlight + +pub fn apply(db: sqlight.Connection) -> Result(Nil, String) { + store.exec(db, "DROP TABLE IF EXISTS rolling_compaction_observation") +} diff --git a/src/albedo/harness/extensions/snapcompact/extension.gleam b/src/albedo/harness/extensions/snapcompact/extension.gleam index b709f9f87..af44f6b42 100644 --- a/src/albedo/harness/extensions/snapcompact/extension.gleam +++ b/src/albedo/harness/extensions/snapcompact/extension.gleam @@ -297,10 +297,23 @@ fn compaction_plugins() -> List(extension.Plugin) { fn strategy_with( resolve: fn() -> Result(Config, String), ) -> compaction.Strategy { - compaction.Strategy("snapcompact", fn(context, history) { - use valid <- result.try(result.try(resolve(), validate_config)) - prepare_view(valid, context, history) - }) + compaction.Strategy( + "snapcompact", + fn(context, history) { + use valid <- result.try(result.try(resolve(), validate_config)) + case compaction.reads_images(context) { + Some(False) -> text_project(context, history) + _ -> visual_project(valid, context, history) + } + }, + fn(context, history) { + use valid <- result.try(result.try(resolve(), validate_config)) + case compaction.reads_images(context) { + Some(False) -> rolling.with_settings().compact(context, history) + _ -> visual_compact(valid, context, history) + } + }, + ) } /// The text fallback keeps its summary in rolling's tables. @@ -319,28 +332,17 @@ fn initialise(ledger: store.Store) -> Result(Nil, String) { }) } -fn prepare_view( - config: Config, - context: compaction.Context, - history: List(types.Input), -) -> Result(compaction.Prepared, String) { - case compaction.reads_images(context) { - Some(False) -> text_view(context, history) - _ -> visual_view(config, context, history) - } -} - /// A model without image input cannot read frames: rolling's text summary /// stands in, and the frame archive waits for a model that reads images. -fn text_view( +fn text_project( context: compaction.Context, history: List(types.Input), -) -> Result(compaction.Prepared, String) { - use prepared <- result.try(rolling.prepare_with_settings(context, history)) +) -> Result(compaction.View, String) { + use view <- result.try(rolling.with_settings().project(context, history)) Ok( - compaction.Prepared( - ..prepared, - observation: option.map(prepared.observation, fn(observed) { + compaction.View( + ..view, + observation: option.map(view.observation, fn(observed) { compaction.Observation( ..observed, strategy: "snapcompact", @@ -352,25 +354,43 @@ fn text_view( ) } -fn visual_view( +/// One request's archive against its history: the saved archive this history +/// still matches, the request it renders, and the budgets that decide whether +/// more history ages into it. +type Survey { + Survey( + folds: List(types.Input), + folded: List(types.Input), + previous: Option(Archive), + evicted: List(types.Input), + rest: List(types.Input), + current: List(types.Input), + status: String, + shape: Shape, + limit: Int, + capacity: Option(Int), + triggered: Bool, + tail_budget: Int, + ) +} + +fn survey( config: Config, context: compaction.Context, history: List(types.Input), -) -> Result(compaction.Prepared, String) { +) -> Result(Survey, String) { // Other strategies' folds are already summaries: they stay as text ahead // of the archive, so the frame budget only ever drops raw rows. use compaction.Prior(folds, folded) <- result.try(context.prior(history)) use saved <- result.try(load_archive(context.store, context.session)) + // An archive this history no longer matches is ignored until the next + // compaction replaces it. let resumed = option.then(saved, fn(archive) { compaction.resume(folded, archive.cut) |> result.map(fn(split) { #(archive, split.0, split.1) }) |> option.from_result }) - use _ <- result.try(case saved, resumed { - Some(_), None -> delete_archive(context.store, context.session) - _, _ -> Ok(Nil) - }) let shape = fit(shape(context.model), context.images) let capacity = case context.capacity { Some(compaction.Capacity(tokens, _)) -> Some(tokens) @@ -389,13 +409,6 @@ fn visual_view( context.pinned_tokens + compaction.estimate_inputs(folds) + compaction.estimate_inputs(current) - let triggered = - compaction.triggered( - context.force, - estimated, - capacity, - config.trigger_percent, - ) // Without a window the tail budget is a share of what the request holds. let tail_budget = case capacity { Some(tokens) -> @@ -407,33 +420,76 @@ fn visual_view( ) None -> int.max(estimated / 4, 1000) } - let observe = fn(status, prepared) { - observation(status, config, capacity, folds, folded, prepared) - } - use #(prepared, status, compacted) <- result.try( - case triggered, compaction.split_tail(rest, tail_budget) { - // Only a whole unit remains, or nothing is due: keep the saved cut. - True, #([_, ..] as newly_evicted, tail) -> { - let archive = extend(shape, limit, previous, evicted, newly_evicted) - use _ <- result.try(save_archive( - context.store, - context.session, - archive, - )) - let #(prepared, status) = - view(context.store, shape, limit, archive, tail) - Ok(#(prepared, status, True)) - } - _, _ -> Ok(#(current, status, False)) - }, - ) - Ok(compaction.Prepared( - list.append(folds, prepared), - observe(status, prepared), - compacted, + Ok(Survey( + folds:, + folded:, + previous:, + evicted:, + rest:, + current:, + status:, + shape:, + limit:, + capacity:, + triggered: compaction.triggered( + context.force, + estimated, + capacity, + config.trigger_percent, + ), + tail_budget:, + )) +} + +/// The saved archive's frames ahead of the verbatim tail. A compaction is +/// due once the trigger is reached and more than a whole unit remains. +fn visual_project( + config: Config, + context: compaction.Context, + history: List(types.Input), +) -> Result(compaction.View, String) { + use survey <- result.try(survey(config, context, history)) + let #(newly_evicted, _) = + compaction.split_tail(survey.rest, survey.tail_budget) + Ok(compaction.View( + list.append(survey.folds, survey.current), + observation( + survey.status, + config, + survey.capacity, + survey.folds, + survey.folded, + survey.current, + ), + survey.triggered && newly_evicted != [], )) } +/// Ages the history before the verbatim tail into the archive; answers +/// whether anything did, since a whole unit is never split. +fn visual_compact( + config: Config, + context: compaction.Context, + history: List(types.Input), +) -> Result(Bool, String) { + use survey <- result.try(survey(config, context, history)) + case compaction.split_tail(survey.rest, survey.tail_budget) { + #([], _) -> Ok(False) + #(newly_evicted, _) -> { + let archive = + extend( + survey.shape, + survey.limit, + survey.previous, + survey.evicted, + newly_evicted, + ) + use _ <- result.try(save_archive(context.store, context.session, archive)) + Ok(True) + } + } +} + /// The archive after `newly_evicted` ages into it: the previous kept text, /// then the new history, bounded again to the frame budget. fn extend( @@ -922,9 +978,3 @@ fn save_archive( ], ) } - -fn delete_archive(ledger: store.Store, session: String) -> Result(Nil, String) { - store.write(ledger, "DELETE FROM snapcompact_archive WHERE session=?", [ - sqlight.text(session), - ]) -} diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 106e1fb2b..cfec2b0a5 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -3255,9 +3255,16 @@ pub fn prepare_view_scoped( // A strategy that raises fails the turn the way one returning an error // does, naming itself, rather than killing the turn's process. protect.guarded(fn() { - use prepared <- result.try(strategy.prepare(context, history)) + use prepared <- result.try(compaction.prepare( + strategy, + context, + history, + )) list.try_fold(extension.notes(enabled), prepared, fn(prepared, layer) { - layer.apply(context, history, prepared) + case prepared.compacted { + True -> layer.compact(context, history, prepared) + False -> layer.project(context, history, prepared) + } }) }) |> result.map_error(fn(error) { diff --git a/test/harness/compaction_projection_test.gleam b/test/harness/compaction_projection_test.gleam new file mode 100644 index 000000000..30881099b --- /dev/null +++ b/test/harness/compaction_projection_test.gleam @@ -0,0 +1,123 @@ +//// Building a request must not change what the next one builds: every +//// strategy's projection reads its saved state and writes nothing, even when +//// the history no longer matches that state. Only a compaction writes. The +//// E2E harness cannot run a projection apart from the compaction that may +//// follow it, so it cannot tell a read from a write. + +import albedo/daemon/conversation +import albedo/daemon/store +import albedo/harness/extension +import albedo/harness/extensions +import albedo/harness/extensions/lcm/extension as lcm +import albedo/harness/extensions/lcm/memory +import albedo/harness/extensions/rolling/extension as rolling +import albedo/harness/extensions/snapcompact/extension as snapcompact +import albedo/harness/runtime +import albedo/openai_api/types +import gleam/dynamic/decode +import gleam/list +import gleam/option.{None, Some} +import gleam/string +import gleeunit/should +import harness/session_fixture +import sqlight + +pub fn rolling_projection_writes_nothing_test() -> Nil { + projections_write_nothing( + [rolling.configured_extension(rolling.Config(Some(100_000), 90, 25))], + ["rolling"], + ) +} + +pub fn lcm_projection_writes_nothing_test() -> Nil { + projections_write_nothing( + [ + memory.extension(), + lcm.configured_extension(lcm.Config(Some(100_000), 90, 25)), + ], + ["lcm-memory", "lcm"], + ) +} + +pub fn snapcompact_projection_writes_nothing_test() -> Nil { + projections_write_nothing([snapcompact.memory(), snapcompact.extension()], [ + "snapcompact-memory", + "snapcompact", + ]) +} + +/// Compacts once, then prepares requests below the trigger: from the history +/// the compaction saw, and from a rewritten one its saved state no longer +/// matches. Neither may write. +fn projections_write_nothing( + installed: List(extension.Extension), + enabled: List(String), +) -> Nil { + let assert Ok(host) = + runtime.start_with_config(":memory:", extensions.Config(installed, enabled)) + session_fixture.initialise(host) + session_fixture.create(host, "projection", "/tmp") + let ledger = runtime.ledger(host) + let history = conversation_of(["first", "second", "third", "fourth"]) + let assert Ok(_) = + conversation.commit_from( + ledger, + "projection", + history, + conversation.Idle, + Some("provider"), + ) + let assert Ok(session) = runtime.open_session(host, "projection", "/tmp") + let assert Ok(_) = + runtime.compact_history_scoped( + host, + session, + "model", + "model", + None, + "", + fn(_) { Ok("summary of earlier work") }, + history, + ) + let prepare = fn(history) { + let before = changes(ledger) + let assert Ok(inputs) = + runtime.prepare_history_with( + host, + session, + "model", + "", + fn(_) { Error("a projection must not summarize") }, + history, + ) + changes(ledger) |> should.equal(before) + inputs + } + // The saved compaction stands in for the start of the history it covers. + prepare(history) |> should.not_equal(history) + prepare(conversation_of(["rewritten", "second", "third", "fourth"])) + runtime.stop(host) +} + +fn conversation_of(topics: List(String)) -> List(types.Input) { + list.flat_map(topics, fn(topic) { + [ + types.User(topic <> " " <> string.repeat("q", 4000)), + types.Assistant(topic <> " answer " <> string.repeat("a", 4000)), + ] + }) +} + +/// Rows the store's one connection has changed since it opened. +fn changes(ledger: store.Store) -> Int { + let assert Ok([count]) = + store.query(ledger, fn(db) { + sqlight.query( + "SELECT total_changes()", + db, + [], + decode.field(0, decode.int, decode.success), + ) + }) + count +} diff --git a/test/harness/rolling_test.gleam b/test/harness/rolling_test.gleam index 9b8b171c0..7cbdb9308 100644 --- a/test/harness/rolling_test.gleam +++ b/test/harness/rolling_test.gleam @@ -12,6 +12,7 @@ import gleam/erlang/process import gleam/int import gleam/list import gleam/option.{None, Some} +import gleam/result import gleam/string import gleeunit/should import harness/session_fixture @@ -42,12 +43,14 @@ fn long_history() -> List(types.Input) { } /// A row saved before cuts counted user messages validates the old way, by -/// item count under its source, and is rewritten in the portable form. -pub fn legacy_item_count_state_upgrades_in_place_test() -> Nil { +/// item count under its source. A projection only reads it; the next +/// compaction saves the portable form in its place. +pub fn legacy_item_count_state_resumes_and_compaction_upgrades_it_test() -> Nil { let #(host, session) = host(rolling.Config(Some(10_000), 90, 25)) let history = long_history() + let ledger = runtime.ledger(host) let assert Ok(_) = - store.query(runtime.ledger(host), fn(db) { + store.query(ledger, fn(db) { sqlight.query( "INSERT INTO rolling_compaction_state(session,summary,cutoff_count,source_hash) VALUES(?,?,?,?)", db, @@ -73,23 +76,48 @@ pub fn legacy_item_count_state_upgrades_in_place_test() -> Nil { ) string.contains(summary, "legacy facts") |> should.be_true tail |> should.equal(list.drop(history, 4)) - let assert Ok([#(2, cut_hash)]) = - store.query(runtime.ledger(host), fn(db) { - sqlight.query( - "SELECT cutoff_count,source_hash FROM rolling_compaction_state", - db, - [], - { - use users <- decode.field(0, decode.int) - use hash <- decode.field(1, decode.string) - decode.success(#(users, hash)) - }, - ) - }) + let assert Ok([#(4, legacy)]) = saved_cut(ledger) + string.starts_with(legacy, "users:") |> should.be_false + let longer = + list.append(history, [ + types.User("u4 " <> string.repeat("g", 380)), + types.Assistant("a4 " <> string.repeat("h", 380)), + ]) + let assert Ok(_) = + runtime.compact_history_scoped( + host, + session, + "model-a", + "model-a", + None, + "", + fn(request: compaction.SummaryRequest) { + request.previous |> should.equal(Some("legacy facts")) + Ok("folded facts") + }, + longer, + ) + let assert Ok([#(3, cut_hash)]) = saved_cut(ledger) string.starts_with(cut_hash, "users:") |> should.be_true runtime.stop(host) } +fn saved_cut(ledger: store.Store) -> Result(List(#(Int, String)), String) { + store.query(ledger, fn(db) { + sqlight.query( + "SELECT cutoff_count,source_hash FROM rolling_compaction_state", + db, + [], + { + use users <- decode.field(0, decode.int) + use hash <- decode.field(1, decode.string) + decode.success(#(users, hash)) + }, + ) + |> result.map_error(string.inspect) + }) +} + /// A long eviction folds into the summary chunk by chunk, each request under /// half the window, carrying the summary forward. pub fn long_eviction_summarizes_in_chunks_test() -> Nil {