diff --git a/apps/albedo/test/albedo/observation/tool_event_test.gleam b/apps/albedo/test/albedo/observation/tool_event_test.gleam new file mode 100644 index 000000000..d024dafa5 --- /dev/null +++ b/apps/albedo/test/albedo/observation/tool_event_test.gleam @@ -0,0 +1,210 @@ +//// The live `tool` event (`events.encode` of `events.Tool`), which ACP +//// editors render without fetching history. The rule lives in +//// `events.tool`; docs/openapi.yaml `FileDiff` describes the snapshot texts +//// and `ContentReference` the fallback. The event carries the arguments, result +//// and trace inline when the arguments fit 64 KiB and the whole document +//// fits 64 KiB plus the trace's file snapshots, which have their own +//// allowance of at most 256 KiB. Otherwise all three are null and the event +//// points at the durable history entry instead. +//// +//// The defects are a one-line edit of a large file forced through history +//// (snapshots not allowed for), an unbounded snapshot allowance, sizes +//// measured in characters or raw bytes rather than encoded JSON (multibyte +//// and escape-heavy text), and a partial event that keeps some fields. The +//// end-to-end cases edited a 1300-line file and wrote files around the +//// budget through a real kernel. + +import albedo/observation/events +import albedo_model as types +import albedo_property +import albedo_sdk/transcript +import gleam/dynamic/decode +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/string +import qcheck.{type Generator} + +const inline_bytes = 65_536 + +const snapshot_allowance = 262_144 + +type Change { + /// `old_text` is absent, null, or a string; `new_text` is absent or a string. + Change(old: Option(Option(String)), new: Option(String)) +} + +type Case { + Case(arguments: String, changes: List(Change), slack: Int) +} + +fn text() -> Generator(String) { + // ASCII, two-byte, four-byte, and characters JSON escapes. + let unit = + qcheck.from_generators(qcheck.constant("a"), [ + qcheck.constant("é"), + qcheck.constant("😀"), + qcheck.constant("\""), + qcheck.constant("\n"), + qcheck.constant("\u{01}"), + ]) + let count = + qcheck.from_generators(qcheck.constant(0), [ + qcheck.constant(1), + qcheck.constant(1000), + qcheck.constant(40_000), + qcheck.constant(70_000), + ]) + qcheck.map2(unit, count, string.repeat) +} + +fn change() -> Generator(Change) { + let old = + qcheck.from_generators(qcheck.constant(None), [ + qcheck.constant(Some(None)), + qcheck.map(text(), fn(value) { Some(Some(value)) }), + ]) + let new = + qcheck.from_generators(qcheck.constant(None), [qcheck.map(text(), Some)]) + qcheck.map2(old, new, Change) +} + +fn arguments() -> Generator(String) { + // `{"code":"..."}` is 11 bytes around the padding. + qcheck.map( + qcheck.from_generators(qcheck.constant(10), [ + qcheck.constant(inline_bytes - 11), + qcheck.constant(inline_bytes - 10), + qcheck.constant(inline_bytes / 2), + ]), + fn(size) { "{\"code\":\"" <> string.repeat("x", size) <> "\"}" }, + ) +} + +fn case_() -> Generator(Case) { + qcheck.map3( + arguments(), + qcheck.generic_list(change(), qcheck.bounded_int(0, 3)), + qcheck.bounded_int(-2, 2), + Case, + ) +} + +fn trace(changes: List(Change)) -> json.Json { + json.object([ + #("activities", json.preprocessed_array([])), + #( + "changes", + json.preprocessed_array( + list.map(changes, fn(change) { + let old = case change.old { + None -> [] + Some(value) -> [#("old_text", json.nullable(value, json.string))] + } + let new = case change.new { + None -> [] + Some(value) -> [#("new_text", json.string(value))] + } + json.object([ + #("path", json.string("/w/f")), + #("kind", json.string("diff")), + ..list.append(old, new) + ]) + }), + ), + ), + #("truncated", json.bool(False)), + ]) +} + +fn size(value: json.Json) -> Int { + string.byte_size(json.to_string(value)) +} + +/// The encoded snapshot texts: each `old_text` and `new_text` value present. +fn snapshots(changes: List(Change)) -> Int { + list.fold(changes, 0, fn(total, change) { + let old = case change.old { + None -> 0 + Some(value) -> size(json.nullable(value, json.string)) + } + let new = case change.new { + None -> 0 + Some(value) -> size(json.string(value)) + } + total + old + new + }) +} + +pub fn the_live_tool_event_inlines_within_its_budget_test_() -> albedo_property.Timed { + use <- albedo_property.within(120) + use generated <- albedo_property.run(60, case_()) + let trace = trace(generated.changes) + let arguments_bytes = size(transcript.argument_json(generated.arguments)) + let budget = + inline_bytes + int.min(snapshots(generated.changes), snapshot_allowance) + // A result that puts the document `slack` bytes either side of the budget. + let result_length = + int.max(0, budget - arguments_bytes - size(trace) - 2 + generated.slack) + let output = string.repeat("r", result_length) + let complete = + string.byte_size(generated.arguments) <= inline_bytes + && arguments_bytes + result_length + 2 + size(trace) <= budget + let encoded = + events.encode( + "s", + 1, + events.Tool( + types.ToolCall("call", "python", generated.arguments), + output, + Some(trace), + "progress", + 0, + False, + ), + ) + |> json.to_string + // Whether a field holds a non-null value. + let present = fn(field, next) { + decode.optional_field( + field, + False, + decode.optional(decode.dynamic) |> decode.map(option.is_some), + next, + ) + } + let assert Ok(seen) = + json.parse(encoded, { + use data <- decode.field("data", { + use complete <- decode.field("content_complete", decode.bool) + use result <- decode.field("result", decode.optional(decode.string)) + use arguments <- present("arguments") + use reference <- present("reference") + decode.success(#(complete, result, arguments, reference)) + }) + decode.success(data) + }) + let #(seen_complete, seen_result, seen_arguments, seen_reference) = seen + let seen_trace = + json.parse( + encoded, + decode.at(["data", "trace"], decode.optional(decode.dynamic)), + ) + assert seen_complete == complete + assert seen_reference == !complete + assert seen_arguments == complete + case complete { + True -> { + assert seen_result == Some(output) + // The trace comes through unchanged. + let assert Ok(expected) = + json.parse(json.to_string(trace), decode.dynamic) + assert seen_trace == Ok(Some(expected)) + } + False -> { + assert seen_result == None + assert seen_trace == Ok(None) + } + } +} diff --git a/test/harness/trace_snapshots_test.py b/test/harness/trace_snapshots_test.py new file mode 100644 index 000000000..32b1597ef --- /dev/null +++ b/test/harness/trace_snapshots_test.py @@ -0,0 +1,128 @@ +"""File snapshots in a cell's trace (`albedo_trace.Trace.finish`). + +ACP editors show a change from the trace's whole-file snapshots. A file whose +before or after is binary, not UTF-8, or over 128 KiB is reported +`unavailable` with a reason. Every other change is a diff, and the changes +carry `old_text` and `new_text` in write order until the next pair would pass +the 256 KiB snapshot budget; from there on no change carries snapshots, so a +reader never sees a later file's snapshot without an earlier one's. + +The defects are a snapshot past the budget, a later small file filling the +gap after a large one was skipped, a binary or oversized file read as text, +and an unchanged file reported. The end-to-end cases wrote files around these +limits through a real kernel. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import os +from pathlib import Path +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python")) +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import hypothesis_profiles # noqa: E402 +from hypothesis import given, settings, strategies as st # noqa: E402 +import albedo_trace # noqa: E402 + +LIMIT = 128 * 1024 +BUDGET = 256 * 1024 + +# Sizes in UTF-8 bytes around the per-file limit and the budget. +SIZES = [7, 60_000, 100_000, LIMIT, LIMIT + 1] +TEXT = st.builds( + lambda unit, size: (unit * (size // len(unit.encode()))).encode(), + st.sampled_from(["a", "\u00e9", "\U0001f600"]), + st.sampled_from(SIZES), +) +# Mostly text, so several files compete for the budget. +CONTENT = st.one_of( + st.sampled_from([None, b"\x00binary", b"\xff\xfe"]), # missing, binary, not UTF-8 + TEXT, + TEXT, + TEXT, +) + + +@dataclass(frozen=True) +class File: + before: bytes | None + after: bytes | None + + +def readable(content: bytes | None) -> bool: + if content is None: + return True + if len(content) > LIMIT or b"\0" in content: + return False + try: + content.decode("utf-8") + except UnicodeDecodeError: + return False + return True + + +class TraceSnapshotsTest(unittest.TestCase): + @settings(max_examples=hypothesis_profiles.cases(60)) + @given(st.lists(st.builds(File, CONTENT, CONTENT), min_size=2, max_size=5)) + def test_snapshots_follow_write_order_within_the_budget(self, files): + with tempfile.TemporaryDirectory() as root: + # A checkout, so writes under the temporary directory are edits. + os.mkdir(os.path.join(root, ".git")) + trace = albedo_trace.Trace(snapshots=True) + paths = [] + for index, file in enumerate(files): + path = os.path.join(root, f"f{index}") + paths.append(path) + if file.before is not None: + Path(path).write_bytes(file.before) + trace.writing(path) + if file.after is None: + if os.path.exists(path): + os.remove(path) + else: + Path(path).write_bytes(file.after) + changes = trace.finish()["changes"] + assert isinstance(changes, list) + + expected = [] + spent = False + used = 0 + for path, file in zip(paths, files): + if not (readable(file.before) and readable(file.after)): + expected.append((path, "unavailable", None)) + continue + if file.before == file.after: + continue + old = None if file.before is None else file.before.decode() + new = "" if file.after is None else file.after.decode() + size = len((old or "").encode()) + len(new.encode()) + snapshot = None + if not spent and used + size <= BUDGET: + snapshot = (old, new) + used += size + else: + spent = True + expected.append((path, "diff", snapshot)) + + actual = [] + for change in changes: + if change["kind"] == "unavailable": + self.assertTrue(change["reason"]) + actual.append((change["path"], "unavailable", None)) + continue + self.assertEqual("old_text" in change, "new_text" in change) + snapshot = ( + (change["old_text"], change["new_text"]) + if "new_text" in change + else None + ) + actual.append((change["path"], change["kind"], snapshot)) + self.assertEqual(actual, expected) + + +if __name__ == "__main__": + unittest.main()