diff --git a/apps/albedo/test/albedo/session/queue_test.gleam b/apps/albedo/test/albedo/session/queue_test.gleam new file mode 100644 index 000000000..c1a2f2181 --- /dev/null +++ b/apps/albedo/test/albedo/session/queue_test.gleam @@ -0,0 +1,366 @@ +//// A session's inbox queue: the order rows wait in (`inbox`, `mail`) and the +//// rows a turn or step takes from it (`turn.opening`, `turn.steering`). +//// +//// Defects: a reorder or drop that loses, duplicates, or misplaces a row; a +//// dropped row that is still listed or taken; an edit lost; a batch past 64 +//// rows or 32 MiB; a row read alone that shares its turn; a row skipped ahead +//// of another; ride-along rows read after what started the turn. The +//// end-to-end cases held a turn and drove the queue over HTTP. Here the queue +//// lives in an in-memory store and the rules are pure, so generated histories +//// run against a list model, and the batch rules are checked as the +//// properties their documentation states. + +import albedo/history/conversation +import albedo/session/family +import albedo/session/inbox +import albedo/session/turn.{type Queued, Queued} +import albedo/storage/core_store +import albedo/storage/mail +import albedo_property +import albedo_sdk/letter as mail_value +import albedo_sdk/store +import gleam/int +import gleam/list +import gleam/option.{None, Some} +import qcheck.{type Generator} + +// The batch rules. + +const batch_rows = 64 + +const batch_bytes = 33_554_432 + +fn delivery() -> Generator(mail_value.Delivery) { + qcheck.from_weighted_generators(#(6, qcheck.return(mail_value.Steer)), [ + #(1, qcheck.return(mail_value.AfterTurn)), + #(1, qcheck.return(mail_value.Alone)), + #(2, qcheck.return(mail_value.NextTurn)), + #(2, qcheck.return(mail_value.Attach)), + ]) +} + +/// Queues long enough to pass 64 rows, with rows now and then large enough +/// to pass the byte bound within a few. +fn queued() -> Generator(List(Queued)) { + let bytes = + qcheck.from_weighted_generators(#(12, qcheck.bounded_int(0, 2000)), [ + #(1, qcheck.bounded_int(10_000_000, 40_000_000)), + ]) + let row = qcheck.tuple2(delivery(), bytes) + use rows <- qcheck.map(qcheck.generic_list(row, qcheck.bounded_int(0, 140))) + list.index_map(rows, fn(row, index) { + Queued("r" <> int.to_string(index), mail_value.Message, row.0, row.1) + }) +} + +fn starts(row: Queued) -> Bool { + case row.delivery { + mail_value.Steer | mail_value.AfterTurn | mail_value.Alone -> True + mail_value.NextTurn | mail_value.Attach -> False + } +} + +fn position(queue: List(Queued), id: String) -> Int { + let assert Ok(#(_, index)) = + list.index_map(queue, fn(row, index) { #(row.id, index) }) + |> list.find(fn(entry) { entry.0 == id }) + index +} + +fn rows(queue: List(Queued), ids: List(String)) -> List(Queued) { + list.map(ids, fn(id) { + let assert Ok(row) = list.find(queue, fn(row) { row.id == id }) + row + }) +} + +fn in_queue_order(queue: List(Queued), ids: List(String)) -> Bool { + let positions = list.map(ids, position(queue, _)) + positions == list.sort(positions, int.compare) +} + +/// Whether `batch` is as long a prefix of `candidates` as the bounds allow: +/// at least one row, at most 64, and at most 32 MiB unless it is one row. +fn bounded_prefix(batch: List(Queued), candidates: List(Queued)) -> Bool { + let size = list.length(batch) + let bytes = int.sum(list.map(batch, fn(row) { row.bytes })) + let is_prefix = list.take(candidates, size) == batch + let within = size <= batch_rows && { size <= 1 || bytes <= batch_bytes } + let maximal = case list.drop(candidates, size) { + [] -> True + [next, ..] -> + size == batch_rows || { size >= 1 && bytes + next.bytes > batch_bytes } + } + is_prefix && within && maximal +} + +pub fn a_turn_opens_with_one_bounded_batch_test() -> Nil { + use queue <- albedo_property.run(400, queued()) + let ids = turn.opening(queue) + let opened = rows(queue, ids) + assert list.unique(ids) == ids + // Ride-alongs first, then what started the turn, each in queue order. + let #(along, starting) = list.split_while(opened, fn(row) { !starts(row) }) + assert list.all(starting, starts) + assert in_queue_order(queue, list.map(along, fn(row) { row.id })) + assert in_queue_order(queue, list.map(starting, fn(row) { row.id })) + let first_starter = list.find(queue, starts) + case first_starter { + // Nothing starts a turn: a resting session would not open one. + Error(Nil) -> Nil + Ok(starter) -> { + // The first row that starts a turn is always read. + assert list.contains(ids, starter.id) + case starter.delivery { + // A row read alone takes its turn by itself, and what waits ahead + // of it goes without it. + mail_value.Alone -> + case list.first(queue) { + Ok(first) if first.delivery == mail_value.Alone -> + check(ids == [first.id]) + _ -> { + let ahead = + list.take_while(queue, fn(row) { + row.delivery != mail_value.Alone + }) + case list.any(ahead, starts) { + True -> Nil + False -> check(ids == [starter.id]) + } + } + } + _ -> Nil + } + // Without a row read alone, the batch is the queue's bounded prefix + // up to the first row read alone, plus the first starter when the + // bounds cut it off. + case list.any(opened, fn(row) { row.delivery == mail_value.Alone }) { + True -> check(list.length(ids) == 1) + False -> { + let candidates = + list.take_while(queue, fn(row) { row.delivery != mail_value.Alone }) + let in_order = + list.sort(opened, fn(a, b) { + int.compare(position(queue, a.id), position(queue, b.id)) + }) + // A bounded batch from the front of the candidates, then, only + // when the batch holds no starter, the first starter. That starter + // may be the very next candidate the bounds left out. + let shared = list.length(common_prefix(in_order, candidates)) + let split = fn(size) { + let batch = list.take(in_order, size) + bounded_prefix(batch, candidates) + && case list.drop(in_order, size) { + [] -> True + [extra] -> extra == starter && !list.any(batch, starts) + _ -> False + } + } + assert split(shared) || { shared > 0 && split(shared - 1) } + } + } + } + } +} + +fn common_prefix(a: List(Queued), b: List(Queued)) -> List(Queued) { + case a, b { + [x, ..a], [y, ..b] if x == y -> [x, ..common_prefix(a, b)] + _, _ -> [] + } +} + +pub fn a_running_turn_takes_steering_rows_in_bounded_batches_test() -> Nil { + let generator = qcheck.tuple2(queued(), qcheck.bool()) + use #(queue, exclusive) <- albedo_property.run(400, generator) + let ids = turn.steering(queue, exclusive) + case exclusive { + // A turn read alone is joined by nothing. + True -> check(ids == []) + False -> { + let joining = + list.filter(queue, fn(row) { + case row.delivery { + mail_value.Steer | mail_value.NextTurn | mail_value.Attach -> True + mail_value.AfterTurn | mail_value.Alone -> False + } + }) + assert bounded_prefix(rows(queue, ids), joining) + } + } +} + +// The stored queue, against a list model. + +type Op { + Post(Int) + PostFirst(Int) + /// Number these ids first, in this order. + Arrange(List(Int)) + Drop(List(Int)) + Edit(Int) + /// A turn takes these rows. + Take(List(Int)) +} + +/// Ids from a small domain, so ops hit posted, dropped, taken, and never +/// posted rows. +fn id() -> Generator(Int) { + qcheck.bounded_int(0, 7) +} + +fn op() -> Generator(Op) { + let ids = qcheck.generic_list(id(), qcheck.bounded_int(0, 4)) + qcheck.from_weighted_generators(#(4, qcheck.map(id(), Post)), [ + #(1, qcheck.map(id(), PostFirst)), + #(2, qcheck.map(ids, Arrange)), + #(2, qcheck.map(ids, Drop)), + #(1, qcheck.map(id(), Edit)), + #(2, qcheck.map(ids, Take)), + ]) +} + +fn key(id: Int) -> String { + "input-" <> int.to_string(id) +} + +fn submission(id: Int, text: String) -> turn.Submission { + turn.Submission( + text, + text, + "", + turn.Chat, + [], + Some(key(id)), + None, + None, + [], + None, + ) +} + +/// A row waits in the model as its id and text. `used` holds every id ever +/// stored: an id is never stored twice. +type Model { + Model(waiting: List(#(Int, String)), used: List(Int)) +} + +fn apply(db: store.Store, model: Model, op: Op, step: Int) -> Model { + let text = "message " <> int.to_string(step) + case op { + Post(id) | PostFirst(id) -> { + let first = case op { + PostFirst(_) -> True + _ -> False + } + let posted = case first { + True -> inbox.post_first(db, "s", "you", submission(id, text)) + False -> inbox.post(db, "s", "you", submission(id, text)) + } + case list.contains(model.used, id) { + // A key already stored is not stored again. + True -> { + let assert Error(_) = posted + model + } + False -> { + let assert Ok(_) = posted + let waiting = case first { + True -> [#(id, text), ..model.waiting] + False -> list.append(model.waiting, [#(id, text)]) + } + Model(waiting, [id, ..model.used]) + } + } + } + Arrange(ids) -> { + let ids = list.unique(ids) + let assert Ok(Nil) = + store.query(db, mail.arrange_in(_, "s", list.map(ids, key))) + let front = + list.filter_map(ids, fn(id) { + list.find(model.waiting, fn(row) { row.0 == id }) + }) + let rest = + list.filter(model.waiting, fn(row) { !list.contains(ids, row.0) }) + Model(..model, waiting: list.append(front, rest)) + } + Drop(ids) -> { + let ids = list.unique(ids) + let assert Ok(dropped) = + store.query(db, mail.drop_in(_, "s", list.map(ids, key))) + let expected = + list.filter(ids, fn(id) { list.any(model.waiting, fn(r) { r.0 == id }) }) + assert dropped == list.map(expected, key) + Model( + ..model, + waiting: list.filter(model.waiting, fn(row) { + !list.contains(ids, row.0) + }), + ) + } + Edit(id) -> { + let edited = "edited " <> text + let assert Ok(replaced) = inbox.replace(db, "s", submission(id, edited)) + let waits = list.any(model.waiting, fn(row) { row.0 == id }) + assert replaced == waits + Model( + ..model, + waiting: list.map(model.waiting, fn(row) { + case row.0 == id { + True -> #(id, edited) + False -> row + } + }), + ) + } + Take(ids) -> { + let ids = list.unique(ids) + let assert Ok(taken) = inbox.take(db, "s", list.map(ids, key)) + // The rows that still wait, in the order the caller named them. + let expected = + list.filter_map(ids, fn(id) { + list.find(model.waiting, fn(row) { row.0 == id }) + }) + assert list.map(taken, fn(s) { #(s.submission_id, s.text) }) + == list.map(expected, fn(row) { #(Some(key(row.0)), row.1) }) + let assert Ok(Nil) = + store.query(db, mail.receive( + _, + "s", + list.map(expected, fn(r) { key(r.0) }), + )) + Model( + ..model, + waiting: list.filter(model.waiting, fn(row) { + !list.contains(ids, row.0) + }), + ) + } + } +} + +pub fn the_stored_queue_matches_a_list_test() -> Nil { + let generator = qcheck.generic_list(op(), qcheck.bounded_int(0, 40)) + use ops <- albedo_property.run(150, generator) + let assert Ok(db) = store.start(":memory:", "", core_store.tables()) + let assert Ok(Nil) = conversation.initialise(db) + let assert Ok(Nil) = family.initialise(db) + let _ = + list.index_fold(ops, Model([], []), fn(model, op, step) { + let model = apply(db, model, op, step) + let assert Ok(#(items, total)) = inbox.items(db, "s", 3) + assert total == list.length(model.waiting) + assert list.map(items, fn(item) { item.id }) + == list.take(model.waiting, 3) |> list.map(fn(row) { key(row.0) }) + let assert Ok(all) = mail.queued(db, "s") + assert list.map(all, fn(row) { #(row.letter.id, row.display) }) + == list.map(model.waiting, fn(row) { #(key(row.0), Some(row.1)) }) + model + }) + store.close(db) +} + +fn check(holds: Bool) -> Nil { + assert holds +} diff --git a/e2e/queue_test.py b/e2e/queue_test.py index b61d062a1..644d99f1b 100644 --- a/e2e/queue_test.py +++ b/e2e/queue_test.py @@ -1,9 +1,13 @@ """Every input a session will read waits in its inbox, where people see, -reorder and drop it before the session takes it.""" +reorder and drop it before the session takes it. + +The queue's order under posts, reorders, drops, edits, and takes, and the +batches a turn or step takes, are checked in process by +apps/albedo/test/albedo/session/queue_test.gleam. These cases keep the HTTP +journey and holds, which live in the session actor and survive a crash.""" import base64 import json -import re import threading import time import unittest @@ -122,48 +126,6 @@ class QueueTests(unittest.TestCase): self.assertLess(later.index("last waiting"), later.index("first waiting")) self.assertFalse(any("with an image" in request for request in said)) - def test_clearing_the_queue_cancels_what_waits(self): - session = self.app.session() - self.app.prompt(session, "hold the turn").close() - self.assertTrue(self.started.wait(10)) - waiting = [ - self.put_input(session, {"kind": "message", "text": f"waiting {index}"}) - for index in range(3) - ] - cleared = self.queue(session, method="DELETE") - self.assertEqual(cleared["items"], []) - for input_id in waiting: - with self.app.api(f"/sessions/{session}/inputs/{input_id}") as response: - self.assertEqual(json.load(response)["delivery"], "cancelled") - self.gate.set() - self.app.idle(session) - said = json.dumps([record["request"] for record in self.provider.requests]) - self.assertFalse(any(f"waiting {index}" in said for index in range(3))) - - def test_a_long_queue_reaches_the_model_in_bounded_batches_in_order(self): - session = self.app.session() - self.app.prompt(session, "hold the turn").close() - self.assertTrue(self.started.wait(10)) - for index in range(70): - self.put_input(session, {"kind": "message", "text": f"queued {index:02} ."}) - self.assertEqual(self.queue(session)["total"], 70) - self.gate.set() - self.app.idle(session) - self.assertEqual(self.queue(session)["items"], []) - seen = [] - for record in self.provider.requests: - said = json.dumps(record["request"]["input"]) - present = [ - int(index) for index in re.findall(r"queued ([0-9]{2}) \.", said) - ] - new = [index for index in present if index not in seen] - # No step takes more than one batch from the inbox. - self.assertLessEqual(len(new), 64) - seen.extend(new) - # What a request repeats from history keeps its order. - self.assertEqual(present, sorted(set(present))) - self.assertEqual(seen, list(range(70))) - def test_a_held_message_waits_for_its_edit_and_keeps_its_place(self): def script(request): if len(self.provider.requests) == 1: