From ca46d2b3cdd8d324afba921fb8dcdc3a32094c2a Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Sun, 1 Nov 2026 13:16:06 -0500 Subject: [PATCH] notice a turn whose steps keep calling the same bindings with nearly the same code --- cli/internal/daemon/protocol/api.gen.go | 9 +- docs/openapi.yaml | 8 + priv/python/albedo_cells.py | 31 +++- robot-docs/kernel.md | 5 + robot-docs/sessions.md | 30 ++++ robot-docs/settings.md | 2 + src/albedo/daemon/core_settings.gleam | 5 + src/albedo/daemon/session_run.gleam | 2 + src/albedo/harness/albedo_similarity.erl | 93 ++++++++++ .../harness/extensions/python/cells.gleam | 6 +- src/albedo/harness/loop.gleam | 87 ++++++++-- src/albedo/harness/repetition.gleam | 164 ++++++++++++++++++ test/e2e/repetition_test.py | 99 +++++++++++ web/src/lib/api.gen.d.ts | 2 + 14 files changed, 524 insertions(+), 19 deletions(-) create mode 100644 src/albedo/harness/albedo_similarity.erl create mode 100644 src/albedo/harness/repetition.gleam create mode 100644 test/e2e/repetition_test.py diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 41bf17af2..b0d6020f0 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -3599,9 +3599,12 @@ type ToolProgress struct { // ToolTrace defines model for ToolTrace. type ToolTrace struct { - Activities []ToolActivity `json:"activities"` - Changes []json.RawMessage `json:"changes"` - Truncated bool `json:"truncated"` + Activities []ToolActivity `json:"activities"` + + // Calls The session bindings the cell's code calls (`files.find`, `run`), sorted. Absent for a cell replayed from inside another. + Calls []string `json:"calls,omitempty"` + Changes []json.RawMessage `json:"changes"` + Truncated bool `json:"truncated"` } // TraceContent defines model for TraceContent. diff --git a/docs/openapi.yaml b/docs/openapi.yaml index a5d4b2f08..eac27cd34 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -9623,6 +9623,14 @@ components: maxItems: 16 truncated: type: boolean + calls: + type: array + description: The session bindings the cell's code calls (`files.find`, `run`), sorted. + Absent for a cell replayed from inside another. + items: + type: string + maxLength: 1000 + maxItems: 64 required: [activities, changes, truncated] additionalProperties: false ActiveOutput: diff --git a/priv/python/albedo_cells.py b/priv/python/albedo_cells.py index 0d07ed697..fc931177f 100644 --- a/priv/python/albedo_cells.py +++ b/priv/python/albedo_cells.py @@ -1444,8 +1444,35 @@ async def serve_job_view(message: dict[str, object]) -> None: send({**answer, "type": message["type"], "id": message["id"]}) -def deliver_trace(capture: Capture) -> None: +def called_bindings(source: str) -> list[str]: + """The injected bindings a cell's code calls, as dotted names such as + `files.find` or `run`, sorted; the loop compares them across steps.""" + try: + tree = ast.parse(source) + except (SyntaxError, ValueError): + return [] + names: set[str] = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + parts: list[str] = [] + target = node.func + while isinstance(target, ast.Attribute): + parts.append(target.attr) + target = target.value + if ( + isinstance(target, ast.Name) + and target.id in INJECTED + and not target.id.startswith("_") + ): + names.add(".".join([target.id, *reversed(parts)][:3])) + return sorted(names)[:64] + + +def deliver_trace(capture: Capture, source: str | None = None) -> None: payload = capture.trace.finish() + if source is not None: + payload["calls"] = called_bindings(source) send({"type": "trace", "id": capture.id, "trace": payload}) capture.trace.release() @@ -1542,7 +1569,7 @@ async def execute_cell( moved = albedo_spill.relieve(NAMESPACE, INJECTED) if moved: capture.write("\n" + moved) - deliver_trace(capture) + deliver_trace(capture, message["code"]) result = { "type": "done", "id": capture.id, diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 2f8fbbb79..7b6baa3a0 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -69,6 +69,11 @@ before/after text in `cell_traces` for editor diff rendering and replay: a small can store roughly twice the file size, up to 256 KiB of snapshot text per trace, until session deletion. Ordinary sessions do not produce or store these snapshots. +A cell the model ran also records `calls`, the injected bindings its code calls +as dotted names (`files.find`, `run`, `agents.self.spawn`), sorted, at most 64, +read from its syntax tree (`albedo_cells.called_bindings`) rather than from what +ran. The loop compares them between steps ([sessions](sessions.md#repeating-steps)). + ## images `show_image(source, *sources)` returns PNG, JPEG, or WebP bytes or paths with the diff --git a/robot-docs/sessions.md b/robot-docs/sessions.md index 8f52cdcf7..b71094e7f 100644 --- a/robot-docs/sessions.md +++ b/robot-docs/sessions.md @@ -187,6 +187,36 @@ pads every short line to the longest line, which can span thousands of columns in a capability update. Long notes use the same click-to-expand fold as user messages. Folding changes only the display, not the stored or model-facing text. +## Repeating steps + +A model can loop across the steps of a turn while each reply looks fine on its +own. After each step that ran python cells, the loop (`harness/repetition.gleam`, +called from `harness/loop.gleam`) compares the step with the one before it: the +same set of bindings called (the union of the step's cells' trace `calls`, see +[kernel](kernel.md#file-change-traces)) and cell code, joined and cut to 8192 +scalars, whose `difflib.SequenceMatcher` ratio is at least `similarity` percent +(`albedo_similarity.erl` is a port that matches Python's, autojunk included, +and tries the cheap upper bounds first). When `steps` consecutive steps +match, it commits a note from origin `repetition` beside the step's tool +results: the model reads it at its next call, and the user sees the same note +in the transcript. The turn goes on, and the count starts again, so a model +that keeps repeating hears it once per `steps` steps. It holds only the +previous step and a count. + +These steps never count and end a run: a step with no python cell, a step +whose cells called no binding or only ones that wait or read back earlier work +(`cells.info/read/trace/list`, `output.read/list`, `mail.open`, +`agents.self.children/siblings`). A backgrounded cell adds no calls, since its +trace arrives after the step. The watch belongs to one turn, so heartbeat +and wake turns, a step or two each, never add up. + +The daemon's own `repetition` section of `extensions.json` holds `steps` +(default 8, 2 to 1000, -1 never notes) and `similarity` (default 80, 1 to +100), read at the first step of the turn that ran a cell. The defaults are the rule from dawn's +agent on Strata, which flagged 13 of 30 SWE runs on a bad LoRA and none of 30 +on the control. `test/e2e/repetition_test.py` covers a repeating turn, one +whose code changes, and one that only waits. + ## Loaded sessions and unloading A session is loaded while its actor runs; only a loaded session has a stream diff --git a/robot-docs/settings.md b/robot-docs/settings.md index 9ebad9d6f..01a9bc42f 100644 --- a/robot-docs/settings.md +++ b/robot-docs/settings.md @@ -40,6 +40,8 @@ The `extension_settings` group lists every declared section of `extensions.json` The daemon's own `subagents` section holds the limits `daemon/family.gleam` checks for every new child, however it is created: `maxOpenChildren` (default 12), how many open children one session may have, and `maxDepth` (default 3), how many generations below a root. Each takes 1 to 1000, or -1 for no limit. They are read for each new child, so a save applies to the next spawn. Lowering one closes nothing: existing children stay, and new ones are refused until the family fits. A family's root is found by walking parents until one has no family row, so it does not depend on `maxDepth`. +The daemon's own `repetition` section (`harness/repetition.gleam`) holds `steps` (default 8, 2 to 1000, or -1 to never note) and `similarity` (default 80, 1 to 100): how many consecutive steps calling the same bindings with code that similar tell the model it may be repeating itself ([sessions](sessions.md#repeating-steps)). A turn reads it at its first step that ran a cell. + ## Session configuration and catalog Configuration contains explicit nullable `name`, workspace, provider profile, model, effort, fast mode (boolean, default off), preferences, selection overrides, and configuration revision. Fast mode is a per-session provider capability toggle and never inherited by subagents. It is exposed at `GET /sessions/{id}/fast-mode` and conditionally changed with `PATCH` and `{"state": "on"|"off"|"toggle"}` against the session configuration ETag. `/fast` uses `toggle` with no arguments; inversion uses the matched configuration and a replay with its old ETag is refused. Name overrides preserve the automatic title. The automatic title follows every prompt, so it lives on the session and summary representations (`name`, `automatic_name`) and stays out of the configuration and its `ETag`: a prompt never makes a client's observed configuration stale. Preferences contain `pinned`, nullable `pin_order`, and `archived`; summaries also include shared opening counts. diff --git a/src/albedo/daemon/core_settings.gleam b/src/albedo/daemon/core_settings.gleam index 8a49e753b..363078629 100644 --- a/src/albedo/daemon/core_settings.gleam +++ b/src/albedo/daemon/core_settings.gleam @@ -3,6 +3,7 @@ //// no extension may take their names. import albedo/daemon/family +import albedo/harness/repetition import albedo/harness/settings import albedo/harness/settings/declared import gleam/list @@ -13,6 +14,10 @@ pub fn declared() -> List(declared.Declared) { "How many agents a session may keep open, and how deep they may nest.", settings.declaration(family.limits_section()), ), + declared.Declared( + "When the model is told it seems to repeat the same calls step after step.", + settings.declaration(repetition.section()), + ), ] } diff --git a/src/albedo/daemon/session_run.gleam b/src/albedo/daemon/session_run.gleam index f4bc24801..3a90693e4 100644 --- a/src/albedo/daemon/session_run.gleam +++ b/src/albedo/daemon/session_run.gleam @@ -12,6 +12,7 @@ import albedo/daemon/turn import albedo/daemon/usage import albedo/harness/extension import albedo/harness/loop +import albedo/harness/repetition import albedo/harness/runtime import albedo/openai_api/types import gleam/erlang/process.{type Subject} @@ -544,6 +545,7 @@ pub fn start( ) }, turn.exclusive(state.active_submissions), + repetition.new(), ) let pid = process.spawn_unlinked(fn() { diff --git a/src/albedo/harness/albedo_similarity.erl b/src/albedo/harness/albedo_similarity.erl new file mode 100644 index 000000000..19601bc7c --- /dev/null +++ b/src/albedo/harness/albedo_similarity.erl @@ -0,0 +1,93 @@ +-module(albedo_similarity). +-export([at_least/3]). + +%% Whether difflib.SequenceMatcher(None, A, B).ratio() >= Threshold, over +%% Unicode scalars with autojunk on, as Python computes it. The cheap upper +%% bounds (real_quick_ratio, quick_ratio) answer first, as get_close_matches +%% does, so dissimilar code never pays for the full match. +at_least(A0, B0, Threshold) -> + A = unicode:characters_to_list(A0), + B = unicode:characters_to_list(B0), + LA = length(A), + LB = length(B), + Total = LA + LB, + Bound = fun(Matches) -> Total =:= 0 orelse 2.0 * Matches / Total >= Threshold end, + Bound(min(LA, LB)) andalso Bound(common(A, B)) andalso + Bound(matched(list_to_tuple(A), list_to_tuple(B), LA, LB)). + +%% The size of the multiset intersection of A and B. +common(A, B) -> + Counts = lists:foldl(fun(C, M) -> maps:update_with(C, fun(N) -> N + 1 end, 1, M) end, #{}, B), + {_, Shared} = lists:foldl( + fun(C, {M, N}) -> + case maps:get(C, M, 0) of + 0 -> {M, N}; + K -> {M#{C := K - 1}, N + 1} + end + end, {Counts, 0}, A), + Shared. + +%% The total size of the matching blocks (get_matching_blocks). +matched(A, B, LA, LB) -> + blocks(A, B, index(B, LB), [{0, LA, 0, LB}], 0). + +%% b2j: each element of B to its ascending positions, without the popular +%% ones once B has 200 or more elements (autojunk). +index(B, LB) -> + Positions = lists:foldl( + fun(J, M) -> maps:update_with(element(J + 1, B), fun(Js) -> [J | Js] end, [J], M) end, + #{}, lists:seq(LB - 1, 0, -1)), + case LB >= 200 of + false -> Positions; + true -> + Popular = LB div 100 + 1, + maps:filter(fun(_, Js) -> length(Js) =< Popular end, Positions) + end. + +blocks(_, _, _, [], Sum) -> Sum; +blocks(A, B, B2J, [{Alo, Ahi, Blo, Bhi} | Queue], Sum) -> + case longest(A, B, B2J, Alo, Ahi, Blo, Bhi) of + {_, _, 0} -> blocks(A, B, B2J, Queue, Sum); + {I, J, K} -> + Left = [{Alo, I, Blo, J} || Alo < I, Blo < J], + Right = [{I + K, Ahi, J + K, Bhi} || I + K < Ahi, J + K < Bhi], + blocks(A, B, B2J, Left ++ Right ++ Queue, Sum + K) + end. + +%% find_longest_match without an isjunk function: the longest run among +%% non-popular elements, then extended over equal neighbours of any kind. +longest(A, B, B2J, Alo, Ahi, Blo, Bhi) -> + {I, J, K} = scan(A, B2J, Alo, Ahi, Blo, Bhi, #{}, {Alo, Blo, 0}), + {I1, J1, K1} = back(A, B, Alo, Blo, I, J, K), + {I1, J1, forward(A, B, Ahi, Bhi, I1, J1, K1)}. + +scan(_, _, I, Ahi, _, _, _, Best) when I >= Ahi -> Best; +scan(A, B2J, I, Ahi, Blo, Bhi, Lengths, Best) -> + {Next, Best1} = row(maps:get(element(I + 1, A), B2J, []), I, Blo, Bhi, Lengths, #{}, Best), + scan(A, B2J, I + 1, Ahi, Blo, Bhi, Next, Best1). + +row([], _, _, _, _, Next, Best) -> {Next, Best}; +row([J | _], _, _, Bhi, _, Next, Best) when J >= Bhi -> {Next, Best}; +row([J | Js], I, Blo, Bhi, Lengths, Next, Best) when J < Blo -> + row(Js, I, Blo, Bhi, Lengths, Next, Best); +row([J | Js], I, Blo, Bhi, Lengths, Next, {_, _, Size} = Best) -> + K = maps:get(J - 1, Lengths, 0) + 1, + Best1 = case K > Size of + true -> {I - K + 1, J - K + 1, K}; + false -> Best + end, + row(Js, I, Blo, Bhi, Lengths, Next#{J => K}, Best1). + +back(A, B, Alo, Blo, I, J, K) when I > Alo, J > Blo -> + case element(I, A) =:= element(J, B) of + true -> back(A, B, Alo, Blo, I - 1, J - 1, K + 1); + false -> {I, J, K} + end; +back(_, _, _, _, I, J, K) -> {I, J, K}. + +forward(A, B, Ahi, Bhi, I, J, K) when I + K < Ahi, J + K < Bhi -> + case element(I + K + 1, A) =:= element(J + K + 1, B) of + true -> forward(A, B, Ahi, Bhi, I, J, K + 1); + false -> K + end; +forward(_, _, _, _, _, _, K) -> K. diff --git a/src/albedo/harness/extensions/python/cells.gleam b/src/albedo/harness/extensions/python/cells.gleam index 40195d12b..7c6c13265 100644 --- a/src/albedo/harness/extensions/python/cells.gleam +++ b/src/albedo/harness/extensions/python/cells.gleam @@ -389,6 +389,11 @@ pub fn save_trace( } pub fn trace(storage: store.Store, id: String) -> Option(Json) { + saved_trace(storage, id) |> option.map(types.encode_value) +} + +/// The trace saved for cell `id`, as the kernel sent it. +pub fn saved_trace(storage: store.Store, id: String) -> Option(Dynamic) { store.read( storage, "SELECT payload FROM cell_traces WHERE id=?", @@ -398,7 +403,6 @@ pub fn trace(storage: store.Store, id: String) -> Option(Json) { |> result.replace_error(Nil) |> result.try(list.first) |> result.try(unpack_trace) - |> result.map(types.encode_value) |> option.from_result } diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index 46f1c00d1..b9264212b 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -5,6 +5,7 @@ import albedo/daemon/conversation import albedo/daemon/events as view import albedo/daemon/image_fit import albedo/daemon/message_content +import albedo/daemon/note import albedo/daemon/projection import albedo/daemon/requests import albedo/daemon/store @@ -19,9 +20,11 @@ import albedo/harness/compaction import albedo/harness/extension import albedo/harness/extensions/python/cells as journal import albedo/harness/hook +import albedo/harness/repetition import albedo/harness/runtime import albedo/openai_api/types import albedo/text_scalars +import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/int import gleam/io @@ -113,6 +116,9 @@ pub type Loop { refresh: fn() -> Result(Option(Selection), String), /// Editor prompts may finish successfully without assistant text. allow_empty_reply: Bool, + /// Whether this turn's steps keep calling the same bindings with nearly + /// the same code. + repeats: repetition.Watch, ) } @@ -371,7 +377,17 @@ fn converse( }), ) let results = list.map(ran, fn(item) { item.0 }) - let added = list.flat_map(ran, fn(item) { item.1 }) + let #(repeats, repeated) = + repetition.step( + state.repeats, + list.filter_map(ran, fn(item) { item.2 }), + ) + let added = + list.append( + list.flat_map(ran, fn(item) { item.1 }), + repeating(repeated), + ) + let state = Loop(..state, repeats:) use _ <- result.try(commit_hooked(state, added, conversation.Tool)) use steering <- result.try(state.drain_steering()) use _ <- result.try(state.commit([], conversation.Model, None, None)) @@ -541,7 +557,7 @@ pub fn background( /// Start a tool only after its running projection is acknowledged. Remove /// that projection before committing and publishing the tool result. Hooks /// may refuse the call or rewrite its arguments; what they add for the model -/// comes back beside the result. +/// comes back beside the result, and so does the cell a python call ran. fn run_tool( state: Loop, run_id: String, @@ -549,7 +565,10 @@ fn run_tool( attempt: Int, output_index: Int, call: types.ToolCall, -) -> Result(#(types.Input, List(types.Input)), String) { +) -> Result( + #(types.Input, List(types.Input), Result(repetition.Cell, Nil)), + String, +) { let progress_id = tool_progress.progress_id( generation: state.generation, @@ -576,17 +595,10 @@ fn run_tool( failed, )), )) + let saved = saved_trace(state, output) let _ = case output { types.ToolOutput(_, body, _) -> { - let trace = - json.parse( - body, - decode.field("cell_id", decode.string, decode.success), - ) - |> result.map(fn(cell) { - journal.trace(runtime.ledger(state.host), cell) - }) - |> result.unwrap(None) + let trace = option.map(saved, types.encode_value) case position { Some(position) -> state.publish(view.Tool( @@ -609,9 +621,58 @@ fn run_tool( } case halt { Some(reason) -> Error("stopped by a hook: " <> reason) - None -> Ok(#(output, added)) + None -> Ok(#(output, added, ran_cell(call, saved))) + } + } + } +} + +/// The trace the kernel saved for the cell a tool result names. +fn saved_trace(state: Loop, output: types.Input) -> Option(Dynamic) { + case output { + types.ToolOutput(_, body, _) -> + json.parse(body, decode.field("cell_id", decode.string, decode.success)) + |> option.from_result + |> option.then(journal.saved_trace(runtime.ledger(state.host), _)) + _ -> None + } +} + +/// The cell a python call ran, for the repetition watch: its code and the +/// bindings its saved trace says it called. +fn ran_cell( + call: types.ToolCall, + saved: Option(Dynamic), +) -> Result(repetition.Cell, Nil) { + case call.name { + "python" -> { + use code <- result.map( + json.parse( + call.arguments, + decode.field("code", decode.string, decode.success), + ) + |> result.replace_error(Nil), + ) + let calls = case saved { + Some(trace) -> + decode.run(trace, decode.at(["calls"], decode.list(decode.string))) + |> result.unwrap([]) + None -> [] } + repetition.Cell(code, calls) } + _ -> Error(Nil) + } +} + +/// The note that tells the model, and the user who sees it in the +/// transcript, that the turn's steps keep repeating. +fn repeating(repeated: Option(repetition.Repeated)) -> List(types.Input) { + case repeated { + None -> [] + Some(repeated) -> [ + types.User(note.wrap("repetition", repetition.note(repeated))), + ] } } diff --git a/src/albedo/harness/repetition.gleam b/src/albedo/harness/repetition.gleam new file mode 100644 index 000000000..83c0ea15e --- /dev/null +++ b/src/albedo/harness/repetition.gleam @@ -0,0 +1,164 @@ +//// Notices a model repeating itself: consecutive steps of a turn that call +//// the same kernel bindings with nearly the same cell code. Each step only +//// compares with the one before it, so a turn keeps one step and a count. +//// See robot-docs/sessions.md, "Repeating steps". + +import albedo/harness/settings +import albedo/text_scalars +import gleam/dynamic/decode +import gleam/int +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/string + +pub type Settings { + Settings(steps: settings.Limit, similarity: Int) +} + +/// A python cell one step ran: its code and the bindings its trace says it +/// called. +pub type Cell { + Cell(code: String, calls: List(String)) +} + +/// A run of `steps` repeating steps, all calling `calls`. +pub type Repeated { + Repeated(steps: Int, calls: List(String)) +} + +pub opaque type Watch { + Watch(settings: Option(Settings), last: Option(Step), streak: Int) +} + +type Step { + Step(calls: List(String), code: String) +} + +/// A turn's watch before its first step; it reads the settings at that step. +pub fn new() -> Watch { + Watch(None, None, 0) +} + +/// Bindings that only wait for or read back earlier work: a step that calls +/// nothing else is waiting, not repeating, and ends a run. +const waiting = [ + "agents.self.children", "agents.self.siblings", "cells.info", "cells.list", + "cells.read", "cells.trace", "mail.open", "output.list", "output.read", +] + +/// How much of a step's code is compared, which bounds the comparison to +/// about 20 ms. +const compared = 8192 + +/// The watch after a step that ran `cells`, and the run it completed, if +/// any. Once a run is reported the count starts again, so a model that goes +/// on repeating hears about it once per `steps` steps. +pub fn step(watch: Watch, cells: List(Cell)) -> #(Watch, Option(Repeated)) { + let found = option.lazy_unwrap(watch.settings, load) + let reset = Watch(Some(found), None, 0) + case found.steps, signature(cells) { + settings.Unlimited, _ | _, None -> #(reset, None) + settings.Limited(steps), Some(step) -> { + let streak = case watch.last { + Some(last) -> + case last.calls == step.calls && similar(last, step, found) { + True -> watch.streak + 1 + False -> 1 + } + None -> 1 + } + case streak >= steps { + True -> #(reset, Some(Repeated(steps, step.calls))) + False -> #(Watch(Some(found), Some(step), streak), None) + } + } + } +} + +/// What the model is told; the user sees the same note in the transcript. +pub fn note(repeated: Repeated) -> String { + "Your last " + <> int.to_string(repeated.steps) + <> " steps called the same bindings (" + <> string.join(repeated.calls, ", ") + <> ") with nearly the same code each time, so you may be repeating yourself. " + <> "Check whether the last results changed anything; if they did not, try a different approach, " + <> "or stop and say what is blocking you." +} + +/// A step's bindings and code, or `None` when its cells called no binding +/// that does more than wait. +fn signature(cells: List(Cell)) -> Option(Step) { + let calls = + list.flat_map(cells, fn(cell) { cell.calls }) + |> list.unique + |> list.sort(string.compare) + case list.all(calls, list.contains(waiting, _)) { + True -> None + False -> { + let code = + list.map(cells, fn(cell) { cell.code }) + |> string.join("\n") + |> text_scalars.take(compared) + Some(Step(calls, code)) + } + } +} + +fn similar(last: Step, step: Step, found: Settings) -> Bool { + at_least(last.code, step.code, int.to_float(found.similarity) /. 100.0) +} + +/// Whether Python's `difflib.SequenceMatcher(None, a, b).ratio()` is at +/// least `threshold`. +@external(erlang, "albedo_similarity", "at_least") +fn at_least(a: String, b: String, threshold: Float) -> Bool + +fn load() -> Settings { + case settings.load_section(section()) { + Ok(found) -> found + Error(_) -> Settings(settings.Limited(default_steps), default_similarity) + } +} + +const default_steps = 8 + +const default_similarity = 80 + +fn steps_setting() -> settings.Setting(settings.Limit) { + settings.limit( + "steps", + "Repeating steps", + "How many consecutive steps of a turn that call the same bindings with nearly the same code tell the model it may be repeating itself. -1 never tells it.", + settings.Limited(default_steps), + 2, + 1000, + ) +} + +fn similarity_setting() -> settings.Setting(Int) { + settings.whole( + "similarity", + "Code similarity", + "How alike, in percent, one step's code must be to the step before it to count as a repeat (difflib's ratio).", + default_similarity, + 1, + 100, + ) +} + +/// The `repetition` section, which the daemon declares itself. +pub fn section() -> settings.Section(Settings) { + settings.section( + "repetition", + "Repeating steps", + settings.Agents, + [settings.field(steps_setting()), settings.field(similarity_setting())], + { + use steps <- settings.value(steps_setting()) + use similarity <- settings.value(similarity_setting()) + decode.success(Settings(steps, similarity)) + }, + Ok, + ) +} diff --git a/test/e2e/repetition_test.py b/test/e2e/repetition_test.py new file mode 100644 index 000000000..05d48e282 --- /dev/null +++ b/test/e2e/repetition_test.py @@ -0,0 +1,99 @@ +"""A turn whose steps keep calling the same bindings with nearly the same code. + +Catches: a model looping across the steps of one turn (each reply fine on its +own) going unnoticed, and the opposite, a note for a turn whose steps change +their code or only wait. Only the real loop, kernel and trace together decide +which bindings a step called and when a run of repeats is long enough. +""" + +import difflib +import unittest + +from harness import Albedo, Provider, python, text + +NOTE = "you may be repeating yourself" + + +def repeating(step): + return ( + f"found = await files.find('needle', '.', max_results=5)\n" + f"print('pass', {step}, len(str(found)))" + ) + + +# Each step searches too, but in code too different from the one before it. +VARIED = [ + "\n".join( + [f"{name} = await files.find({name!r}, '.', max_results={step + 1})"] + + [f"print({name!r} * {k}, len(str({name})))" for k in range(step % 3 + 1)] + ) + for step, name in enumerate( + ["alpha", "brook", "cinder", "dune", "ember", "fjord", "grove", "heath"] + ) +] + + +class RepetitionTest(unittest.TestCase): + def run_turn(self, cells): + def script(request): + done = sum( + 1 for item in request["input"] if item.get("type") == "function_call" + ) + if done < len(cells): + return python(cells[done]) + return text("done") + + provider = Provider(script) + try: + with Albedo(provider, protocol="responses") as app: + session = app.session() + app.prompt(session, "find the needle").close() + app.idle(session) + history = app.history(session)["items"] + finally: + provider.close() + notes = [ + [ + item["content"] + for item in entry["request"]["input"] + if item.get("role") == "user" and NOTE in str(item.get("content")) + ] + for entry in provider.requests + ] + # The note is a transcript entry, so the user sees it too. + shown = [ + part["text"] + for entry in history + if entry["kind"] == "note" + for part in entry["content"] + if part["kind"] == "text" and NOTE in part["text"] + ] + return notes, shown + + def test_eight_repeating_steps_tell_the_model_and_the_user(self): + notes, shown = self.run_turn([repeating(step) for step in range(8)]) + self.assertEqual(len(notes), 9) + # Only the request after the eighth step carries the note. + self.assertEqual([bool(found) for found in notes], [False] * 8 + [True]) + self.assertIn("files.find", notes[8][0]) + self.assertTrue(shown, "the user sees no repetition note") + + def test_steps_whose_code_changes_are_not_repeats(self): + for before, after in zip(VARIED, VARIED[1:]): + self.assertLess(difflib.SequenceMatcher(None, before, after).ratio(), 0.8) + notes, shown = self.run_turn(VARIED) + self.assertEqual(len(notes), 9) + self.assertFalse(any(notes)) + self.assertEqual(shown, []) + + def test_steps_that_only_wait_are_not_repeats(self): + notes, shown = self.run_turn( + [f"print(len(await cells.list()), {step})" for step in range(8)] + ) + self.assertEqual(len(notes), 9) + self.assertFalse(any(notes)) + self.assertEqual(shown, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index fa0788f4d..ab760d382 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -3352,6 +3352,8 @@ export interface components { activities: components["schemas"]["ToolActivity"][]; changes: (components["schemas"]["FileDiff"] | components["schemas"]["FileUnavailable"])[]; truncated: boolean; + /** @description The session bindings the cell's code calls (`files.find`, `run`), sorted. Absent for a cell replayed from inside another. */ + calls?: string[]; }; /** @description Ordered unfinished output captured with the session cursor. Exactly one of text or reference is non-null. References retain a fixed byte cutoff through their short snapshot lease. A run retains at most 64 MiB of unfinished output across at most 256 descriptors. Inline output is limited to 64 KiB encoded; larger content uses references. */ ActiveOutput: { -- knotmirror 0.0.1