From e144355c8b2be95b4f171c3359ff9d3dc00d72ff Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Sat, 21 Nov 2026 02:34:24 -0500 Subject: [PATCH] test(session): check visit receipts and configuration edits in process visit_receipts_test replays generated histories of visits, deletions and store reopens over two sessions, a missing one and four identities against a map. configuration_candidate_test drives the session actor with generated edits (name, pin, archive, model, effort, pin moves that fail inside the commit, stale revisions) and races of two or three writers on one revision, and requires all or nothing and one winner. Deleted from e2e/settings_test.py, with the defects now caught here: - test_concurrent_visits_and_preferences_keep_every_receipt: a replayed visit counting again or answering another count, a receipt reused under another session (visit_receipts_test). - test_preferences_and_visits_survive_restart_and_session_deletion: receipts and counts lost across a reopen or a deletion (visit_receipts_test). Pin and archive columns are plain session columns; ui settings persistence is the settings model's. - test_session_configuration_is_one_conditional_candidate (atomicity and 412 half; the reload half moved in c3457fb95): a refused candidate leaving fields saved, two writers on one revision both winning, a stale edit applied (configuration_candidate_test). Dropped: the skill-selection field of the refused candidate. Selection is committed by the same transaction the generated pin-move failures roll back. --- .../configuration_candidate_test.gleam | 284 ++++++++++++++++++ .../albedo/session/visit_receipts_test.gleam | 243 +++++++++++++++ e2e/settings_test.py | 140 --------- 3 files changed, 527 insertions(+), 140 deletions(-) create mode 100644 apps/albedo/test/albedo/session/configuration_candidate_test.gleam diff --git a/apps/albedo/test/albedo/session/configuration_candidate_test.gleam b/apps/albedo/test/albedo/session/configuration_candidate_test.gleam new file mode 100644 index 000000000..3da146cc0 --- /dev/null +++ b/apps/albedo/test/albedo/session/configuration_candidate_test.gleam @@ -0,0 +1,284 @@ +//// A session's configuration edit is one conditional candidate +//// (`session.change_configuration`, the configuration PATCH with If-Match). +//// +//// The contract (docs/http-sessions.md, robot-docs/session.md): an edit +//// names the revision it read; a stale one changes nothing and is +//// `ConfigurationChanged` (412); a refused edit changes nothing, even when +//// the refusal comes after the session row was written (a pin moved before +//// a session that is not pinned); an accepted edit applies every field and +//// moves the revision once; of several writers that read the same +//// revision, exactly one wins. +//// +//// Defects: a refused candidate that leaves its name, pin or archive +//// saved; two writers that both win; a stale edit applied. Generated +//// histories mix fields that always validate (name, pin, archive) with +//// ones the provider catalog may refuse (model, effort) and pin moves that +//// fail inside the commit, and some steps send two or three edits at once +//// from separate processes. The oracle does not restate the catalog's +//// effort rules: it requires all or nothing, and a result only where the +//// contract fixes one. + +import albedo/history/conversation +import albedo/refusal +import albedo/runtime +import albedo/session +import albedo/session/session_configuration as config +import albedo/support/turn_harness as h +import albedo_model as types +import albedo_property +import gleam/erlang/process +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/string +import qcheck.{type Generator} + +type Edit { + Edit( + stale: Bool, + name: Option(String), + pinned: Option(Bool), + archived: Option(Bool), + model: Option(String), + effort: Option(String), + /// Some(None): last among the pinned. Some(Some(_)): before a session + /// that is never pinned. + pin_before: Option(Option(String)), + ) +} + +type Op { + One(Edit) + /// Two or three edits of the current revision, sent at once. + Race(names: List(String)) +} + +fn catalog() -> h.Catalog { + h.Catalog( + [ + #("first", [types.Low, types.High]), + #("second", [types.Medium, types.High]), + #("third", [types.Low, types.Medium]), + ], + Some("high"), + ) +} + +fn maybe(generator: Generator(a)) -> Generator(Option(a)) { + qcheck.from_weighted_generators(#(1, qcheck.map(generator, Some)), [ + #(1, qcheck.return(None)), + ]) +} + +fn name() -> Generator(String) { + qcheck.from_generators(qcheck.return("north"), [ + qcheck.return("south"), + qcheck.return(" spaced out "), + ]) +} + +fn edit() -> Generator(Edit) { + use stale <- qcheck.bind( + qcheck.from_weighted_generators(#(1, qcheck.return(True)), [ + #(5, qcheck.return(False)), + ]), + ) + use #(name, pinned, archived) <- qcheck.bind(qcheck.tuple3( + maybe(name()), + maybe(qcheck.bool()), + maybe(qcheck.bool()), + )) + use #(model, effort, pin_before) <- qcheck.map(qcheck.tuple3( + qcheck.from_weighted_generators(#(3, qcheck.return(None)), [ + #( + 2, + qcheck.map( + qcheck.from_generators(qcheck.return("first"), [ + qcheck.return("second"), + qcheck.return("third"), + ]), + Some, + ), + ), + ]), + qcheck.from_weighted_generators(#(3, qcheck.return(None)), [ + #( + 2, + qcheck.map( + qcheck.from_generators(qcheck.return("low"), [ + qcheck.return("medium"), + qcheck.return("high"), + qcheck.return("inherit"), + qcheck.return("unsupported-effort"), + ]), + Some, + ), + ), + ]), + qcheck.from_weighted_generators(#(4, qcheck.return(None)), [ + #(1, qcheck.return(Some(None))), + #(1, qcheck.return(Some(Some("never-pinned")))), + ]), + )) + Edit(stale, name, pinned, archived, model, effort, pin_before) +} + +fn op() -> Generator(Op) { + qcheck.from_weighted_generators(#(6, qcheck.map(edit(), One)), [ + #( + 1, + qcheck.map(qcheck.bounded_int(2, 3), fn(count) { + list.take(["racer 1", "racer 2", "racer 3"], count) + }) + |> qcheck.map(Race), + ), + ]) +} + +pub fn an_edit_is_all_or_nothing_and_one_writer_wins_test_() -> albedo_property.Timed { + use <- albedo_property.within(120) + let harness = h.start_with_catalog([], [], catalog()) + use history <- albedo_property.run( + 60, + albedo_property.sequence([#(1, op())], 1, 16), + ) + list.each(history, step(harness, _)) +} + +fn step(harness: h.Harness, op: Op) -> Nil { + let before = configuration(harness) + case op { + One(edit) -> { + let got = change(harness, before, edit) + let after = configuration(harness) + let what = string.inspect(edit) <> " answered " <> string.inspect(got) + case got { + Ok(_) -> { + assert !must_fail(edit, before) as what + assert after.revision == before.revision + 1 as what + assert applied(before, edit, after) as what + } + Error(reason) -> { + assert !must_succeed(edit) as what + assert after == before as what + assert !edit.stale || reason == refusal.ConfigurationChanged as what + } + } + } + Race(names) -> { + let answers = process.new_subject() + list.each(names, fn(name) { + let racer = + Edit( + stale: False, + name: Some(name), + pinned: None, + archived: None, + model: None, + effort: None, + pin_before: None, + ) + process.spawn(fn() { + process.send(answers, #(name, change(harness, before, racer))) + }) + }) + let outcomes = + list.map(names, fn(_) { + let assert Ok(outcome) = process.receive(answers, 30_000) + outcome + }) + let winners = + list.filter_map(outcomes, fn(outcome) { + case outcome.1 { + Ok(_) -> Ok(outcome.0) + Error(reason) -> { + assert reason == refusal.ConfigurationChanged + as string.inspect(outcomes) + Error(Nil) + } + } + }) + let after = configuration(harness) + let assert [winner] = winners as string.inspect(outcomes) + assert after.name == Some(winner) + assert after.revision == before.revision + 1 + } + } +} + +/// Fields the contract always accepts on a current revision. +fn must_succeed(edit: Edit) -> Bool { + !edit.stale + && edit.model == None + && edit.effort == None + && edit.pin_before == None +} + +fn must_fail(edit: Edit, before: config.Configuration) -> Bool { + let pinned = option.unwrap(edit.pinned, before.preferences.pinned) + edit.stale + || case edit.pin_before { + None -> False + Some(Some(_)) -> True + Some(None) -> !pinned + } +} + +/// Every field the edit names is saved, and the rest kept. +fn applied( + before: config.Configuration, + edit: Edit, + after: config.Configuration, +) -> Bool { + let name = case edit.name { + Some(name) -> config.clean_name(name) + None -> before.name + } + let pinned = option.unwrap(edit.pinned, before.preferences.pinned) + after.name == name + && after.preferences.pinned == pinned + && { after.preferences.pin_order != None } == pinned + && after.preferences.archived + == option.unwrap(edit.archived, before.preferences.archived) + && after.model == option.unwrap(edit.model, before.model) + && after.effort == option.or(edit.effort, before.effort) + && after.workspace == before.workspace + && after.preferences.opens == before.preferences.opens +} + +fn change( + harness: h.Harness, + read: config.Configuration, + edit: Edit, +) -> Result(Nil, refusal.Refusal) { + let revision = case edit.stale { + True -> read.revision - 1 + False -> read.revision + } + session.change_configuration( + harness.session, + config.Version(revision, read.family.revision), + config.Patch( + name: option.map(edit.name, Some), + provider_profile: None, + model: edit.model, + effort: option.map(edit.effort, Some), + fast: None, + cyber_access: None, + context_window: None, + pinned: edit.pinned, + archived: edit.archived, + pin_before: edit.pin_before, + selection: config.SelectionPatch(None, None, None, None), + catalog_revision: None, + ), + None, + ) + |> result.map(fn(_) { Nil }) +} + +fn configuration(harness: h.Harness) -> config.Configuration { + let assert Ok(captured) = + conversation.capture(runtime.ledger(harness.host), harness.id) + captured.configuration +} diff --git a/apps/albedo/test/albedo/session/visit_receipts_test.gleam b/apps/albedo/test/albedo/session/visit_receipts_test.gleam index 4c16c13e8..495b6ced1 100644 --- a/apps/albedo/test/albedo/session/visit_receipts_test.gleam +++ b/apps/albedo/test/albedo/session/visit_receipts_test.gleam @@ -1,4 +1,20 @@ //// Visit receipts (`session_configuration.visit`, the `recordVisit` route). +//// +//// The contract (docs/http-sessions.md, `recordVisit` in docs/openapi.yaml): +//// a new visit identity counts one opening and records the count it +//// reached; the same identity again returns that count and counts nothing, +//// even after later visits, a store reopen, or the session's deletion; the +//// identity under another session is a conflict that counts nothing; an +//// invalid or expired identity counts nothing; a missing session is not +//// found. +//// +//// Defects: a replay that counts again (a lost acknowledgement retried by +//// the client), a replay that answers the current count instead of its +//// own, a receipt reused across sessions, a deletion or a restart that +//// drops receipts, and a refused visit that still counts. Generated +//// histories over two sessions, a missing one, and four identities replay +//// against the store and a map, with the store closed and reopened between +//// operations; the end-to-end suite could only try a few orders. import albedo/history/conversation import albedo/refusal @@ -6,10 +22,73 @@ import albedo/session/family import albedo/session/session_configuration as config import albedo/storage/core_store import albedo/support/uuid +import albedo_bytes/digest +import albedo_clock import albedo_model as types +import albedo_property import albedo_sdk/session_info import albedo_sdk/store +import gleam/crypto +import gleam/dict.{type Dict} +import gleam/dynamic/decode +import gleam/int +import gleam/list import gleam/option.{None} +import gleam/string +import qcheck.{type Generator} +import sqlight + +type Identity { + /// One of four identities shared by the whole history. + Known(Int) + /// A well-formed identity older than the retention window. + Expired + Malformed +} + +type Op { + /// Session 0 and 1 exist until deleted; 2 never does. + Visit(session: Int, identity: Identity) + Delete(session: Int) + Reopen +} + +type Model { + Model( + opens: Dict(Int, Int), + receipts: Dict(Int, #(Int, Int)), + events: Dict(String, Int), + ) +} + +fn op() -> Generator(Op) { + let session = qcheck.bounded_int(0, 2) + let identity = + qcheck.from_weighted_generators( + #(8, qcheck.map(qcheck.bounded_int(0, 3), Known)), + [ + #(1, qcheck.return(Expired)), + #(1, qcheck.return(Malformed)), + ], + ) + qcheck.from_weighted_generators(#(10, qcheck.map2(session, identity, Visit)), [ + #(1, qcheck.map(qcheck.bounded_int(0, 1), Delete)), + #(2, qcheck.return(Reopen)), + ]) +} + +pub fn visits_count_once_per_identity_and_keep_their_receipt_test_() -> albedo_property.Timed { + use <- albedo_property.within(60) + use history <- albedo_property.run( + 60, + albedo_property.sequence([#(1, op())], 1, 40), + ) + let path = "/tmp/albedo-visit-receipts-" <> uuid.v7() <> ".db" + let #(ledger, _) = replay(open(path), path, history) + store.close(ledger) + let _ = delete_file(path) + Nil +} /// A visit to a session that does not exist answered `Unavailable`, which /// the route sends as a retryable 503, so a client retried a visit that @@ -28,6 +107,110 @@ pub fn a_visit_to_a_missing_session_is_not_found_test() -> Nil { Nil } +/// One history on its own sessions and identities. +fn replay( + ledger: store.Store, + path: String, + history: List(Op), +) -> #(store.Store, Model) { + let sessions = list.map([0, 1, 2], fn(_) { uuid.v7() }) + let identities = list.map([0, 1, 2, 3], fn(_) { uuid.v7() }) + list.each([0, 1], fn(index) { create(ledger, at(sessions, index)) }) + let model = Model(dict.from_list([#(0, 0), #(1, 0)]), dict.new(), dict.new()) + list.fold(history, #(ledger, model), fn(state, op) { + let #(ledger, model) = state + let #(ledger, model) = case op { + Reopen -> { + store.close(ledger) + #(open(path), count(model, "reopen")) + } + Delete(index) -> { + case dict.has_key(model.opens, index) { + True -> delete(ledger, at(sessions, index)) + False -> Nil + } + #(ledger, Model(..model, opens: dict.delete(model.opens, index))) + } + Visit(index, identity) -> { + let session = at(sessions, index) + let id = case identity { + Known(k) -> at(identities, k) + Expired -> expired_id() + Malformed -> "visit-" <> session + } + let got = config.visit(ledger, session, id) + #( + ledger, + expect(model, index, identity, got) + |> fn(pair) { + let #(expected, model) = pair + assert got == expected + as { string.inspect(op) <> " answered " <> string.inspect(got) } + model + }, + ) + } + } + // Every living session's count is what the model says, after every step. + dict.each(model.opens, fn(index, opens) { + assert opens_of(ledger, at(sessions, index)) == opens + as { "opens of session " <> int.to_string(index) } + }) + #(ledger, model) + }) +} + +/// What the contract answers for a visit, and the model after it. +fn expect( + model: Model, + index: Int, + identity: Identity, + got: Result(#(config.Visit, Bool), refusal.Refusal), +) -> #(Result(#(config.Visit, Bool), refusal.Refusal), Model) { + let echo_ = fn(opens) { + case got { + Ok(#(visit, _)) -> config.Visit(visit.visit_id, visit.session_id, opens) + Error(_) -> config.Visit("", "", opens) + } + } + case identity { + Expired -> #(Error(refusal.IdExpired), model) + Malformed -> #(Error(refusal.IdInvalid), model) + Known(k) -> + case dict.get(model.receipts, k) { + Ok(#(owner, opens)) if owner == index -> { + let event = case dict.has_key(model.opens, index) { + True -> "replay" + False -> "replay after delete" + } + #(Ok(#(echo_(opens), False)), count(model, event)) + } + Ok(_) -> #(Error(refusal.IdConflict), count(model, "conflict")) + Error(Nil) -> + case dict.get(model.opens, index) { + Ok(opens) -> #( + Ok(#(echo_(opens + 1), True)), + Model( + ..count(model, "fresh"), + opens: dict.insert(model.opens, index, opens + 1), + receipts: dict.insert(model.receipts, k, #(index, opens + 1)), + ), + ) + Error(Nil) -> #(Error(refusal.SessionNotFound), model) + } + } + } +} + +fn count(model: Model, event: String) -> Model { + Model( + ..model, + events: dict.upsert(model.events, event, fn(n) { option.unwrap(n, 0) + 1 }), + ) +} + +// ---- store --------------------------------------------------------------- + fn open(path: String) -> store.Store { // The extensions table belongs to the extension runtime, which a // configuration read joins. @@ -63,5 +246,65 @@ fn create(ledger: store.Store, id: String) -> Nil { Nil } +/// Deletes the session as the deletion route does: a claim, then the +/// claimed removal of its records. +fn delete(ledger: store.Store, id: String) -> Nil { + let assert Ok(current) = store.snapshot(ledger, config.read_in(_, id)) + let assert Ok(claim) = + family.claim_deletion( + ledger, + family.DeletionRequest( + id, + current.revision, + current.family.revision, + False, + ), + uuid.v7(), + albedo_clock.monotonic_ms() + 10_000, + ) + let assert Ok(Nil) = conversation.delete_claimed(ledger, id, claim, []) + Nil +} + +fn opens_of(ledger: store.Store, id: String) -> Int { + let assert Ok([opens]) = + store.read( + ledger, + "SELECT opens FROM sessions WHERE id=?", + [sqlight.text(id)], + { decode.field(0, decode.int, decode.success) }, + ) + opens +} + +/// A UUIDv7 stamped nine days ago, past the seven-day retention. +fn expired_id() -> String { + let timestamp = albedo_clock.system_ms() - 9 * 86_400_000 + let assert <> = + crypto.strong_random_bytes(10) + let hex = + digest.hex(<< + timestamp:size(48), + 7:size(4), + a:size(12), + 2:size(2), + b:size(62), + >>) + string.slice(hex, 0, 8) + <> "-" + <> string.slice(hex, 8, 4) + <> "-" + <> string.slice(hex, 12, 4) + <> "-" + <> string.slice(hex, 16, 4) + <> "-" + <> string.slice(hex, 20, 12) +} + +fn at(values: List(String), index: Int) -> String { + let assert Ok(value) = list.drop(values, index) |> list.first + value +} + @external(erlang, "file", "delete") fn delete_file(path: String) -> Result(Nil, Nil) diff --git a/e2e/settings_test.py b/e2e/settings_test.py index 233136320..0be19f151 100644 --- a/e2e/settings_test.py +++ b/e2e/settings_test.py @@ -224,146 +224,6 @@ class SettingsTest(unittest.TestCase): path.write_text(f"---\nname: {name}\ndescription: {description}\n---\nbody\n") return path - # exclusive: global group revisions are independent, session visits are idempotent - @exclusive - def test_concurrent_visits_and_preferences_keep_every_receipt(self): - ids = [self.session, self.app.session()] - with ThreadPoolExecutor(max_workers=4) as pool: - list( - pool.map( - lambda sid: self.change({"preferences": {"pinned": True}}, sid), ids - ) - ) - visits = [operation_id() for _ in range(12)] - - def visit(identity): - with self.app.api( - f"/sessions/{ids[0]}/visits/{identity}", {}, method="PUT" - ) as response: - return json.load(response) - - receipts = list(pool.map(visit, visits)) - # After other visits, a lost acknowledgement returns its original count. - first = next(receipt for receipt in receipts if receipt["opens"] == 1) - self.assertEqual(visit(first["visit_id"]), first) - self.assertEqual(self.read(f"/sessions/{ids[0]}")["preferences"]["opens"], 12) - with self.assertRaises(urllib.error.HTTPError) as caught: - self.app.api( - f"/sessions/{ids[1]}/visits/{first['visit_id']}", {}, method="PUT" - ) - self.assertEqual(caught.exception.code, 409) - self.assertEqual(self.read(f"/sessions/{ids[1]}")["preferences"]["opens"], 0) - self.assertTrue( - all(self.read(f"/sessions/{sid}")["preferences"]["pinned"] for sid in ids) - ) - - def test_session_configuration_is_one_conditional_candidate(self): - self.write_skill("compound-config", "COMPOUND_CONFIG_SKILL") - self.assertIn("COMPOUND_CONFIG_SKILL", self.turn()) - discovery = self.discovery(kind="skills") - skill = next( - row - for row in discovery["candidates"] - if row["preference_key"] == "compound-config" - ) - route = f"/sessions/{self.session}/configuration" - with self.app.api(route) as response: - before = json.load(response) - observed = response.headers["ETag"] - model = before["model"] or self.read(f"/sessions/{self.session}")["model"] - candidate = { - "name": "must not partially save", - "preferences": {"pinned": True, "archived": True}, - "model": model, - "effort": "unsupported-effort", - "selection": {"skills": {skill["id"]: False}}, - "catalog_revision": discovery["revision"], - } - with self.assertRaises(urllib.error.HTTPError) as caught: - self.app.api( - route, candidate, method="PATCH", headers={"If-Match": observed} - ) - self.assertEqual(caught.exception.code, 400) - self.assertEqual(self.read(route), before) - self.assertIn( - "/compound-config", {row["slash_name"] for row in self.commands()} - ) - - del candidate["effort"] - barrier = threading.Barrier(3) - - def save(name): - barrier.wait() - try: - with self.app.api( - route, - {**candidate, "name": name}, - method="PATCH", - headers={"If-Match": observed}, - ) as response: - return response.status, json.load(response) - except urllib.error.HTTPError as error: - return error.code, json.load(error) - - with ThreadPoolExecutor(max_workers=2) as pool: - futures = [ - pool.submit(save, name) - for name in ("first compound writer", "second compound writer") - ] - barrier.wait() - outcomes = [future.result(timeout=10) for future in futures] - self.assertEqual(sorted(status for status, _ in outcomes), [200, 412]) - winner = next(body for status, body in outcomes if status == 200) - with self.app.api(route) as response: - saved = json.load(response) - observed = response.headers["ETag"] - resource = winner["resource"] - self.assertEqual(saved, resource["value"]) - self.assertEqual((resource["url"], resource["etag"]), (route, observed)) - self.assertNotIn("session", winner) - self.assertIn("application", winner) - self.assertTrue(saved["preferences"]["pinned"]) - self.assertTrue(saved["preferences"]["archived"]) - self.assertEqual(saved["model"], model) - - # exclusive: restarts and deletes a session with persisted preferences - @exclusive - def test_preferences_and_visits_survive_restart_and_session_deletion(self): - picker = self.app.home / "picker.json" - picker.write_text(json.dumps({"unrelated": {"keep": True}})) - self.patch("ui", {"thinking": True, "assistant_name": "Luna"}) - self.change({"preferences": {"pinned": True, "archived": True}}) - for _ in range(3): - self.app.api( - f"/sessions/{self.session}/visits/{operation_id()}", {}, method="PUT" - ).close() - self.app.restart() - self.assertEqual(json.loads(picker.read_text())["unrelated"], {"keep": True}) - session = self.read(f"/sessions/{self.session}") - ui = self.group("ui") - self.assertTrue(ui["thinking"]) - self.assertEqual(ui["assistant_name"], "Luna") - self.assertEqual( - ( - session["preferences"]["pinned"], - session["preferences"]["archived"], - session["preferences"]["opens"], - ), - (True, True, 3), - ) - resource = session["configuration_resource"] - self.app.api( - resource["url"].removesuffix("/configuration"), - method="DELETE", - headers={"If-Match": resource["etag"]}, - ).close() - self.assertNotIn( - self.session, - [item["id"] for item in self.read("/sessions?archived=true")["items"]], - ) - stored = json.loads(picker.read_text()) - self.assertNotIn(self.session, json.dumps(stored)) - def declared(self, name, key): section = next( section -- knotmirror 0.0.1