replay.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. """The replay bundle (moved verbatim from the pre-split web_stack_test.py;
  2. see test/harness.py for the shared machinery and the runner)."""
  3. from harness import * # noqa: F401,F403 — the shared wire helpers
  4. # =============================================================================
  5. # Bundle: replay — plan 13 B1/B2 shapes, rebuilt on the plan-17 ledger:
  6. # the idempotent events push (UNIQUE(session_id, seq) — database state,
  7. # so it survives a web restart), the session-churn redelivery shape, and
  8. # repeated failure pushes that must still project exactly once.
  9. # =============================================================================
  10. def run(ctx):
  11. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  12. app = ctx.app
  13. def rows_for(session):
  14. conn = db()
  15. try:
  16. return conn.execute(
  17. "select count(*) from events where session_id = ?",
  18. (session,)).fetchone()[0]
  19. finally:
  20. conn.close()
  21. def open_session_on_fake(task_id):
  22. """A fixture open session row on the shard's saddle (the churn
  23. shape: a fresh web-side run row the daemon never really drove)."""
  24. conn = db()
  25. try:
  26. conn.execute(
  27. "insert into sessions (task_id, saddle_id, started_at)"
  28. " values (?, ?, strftime('%s','now'))", (task_id, fake_id))
  29. conn.commit()
  30. return conn.execute(
  31. "select max(id) from sessions where task_id = ?",
  32. (task_id,)).fetchone()[0]
  33. finally:
  34. conn.close()
  35. print("== plan 17 §7.2: event pushes are idempotent per session ==")
  36. # A first task runs to completion; its session is the replay source.
  37. first = create_queued(auth, {"project_id": "1", "title": "Replay source task",
  38. "priority": "2"})
  39. check(wait_task_done(auth, first, timeout=60) is not None,
  40. "the replay-source task completes")
  41. conn = db()
  42. src_session = conn.execute(
  43. "select max(id) from sessions where task_id = ?", (first,)).fetchone()[0]
  44. conn.close()
  45. # The outbox batch: two events the daemon already delivered once.
  46. burst = [
  47. {"seq": 5001, "kind": "tool_call", "actor": "model",
  48. "payload": {"turn": 7, "tool": "run_command",
  49. "args": {"command": "make test"}}},
  50. {"seq": 5002, "kind": "tool_result", "actor": "harness",
  51. "payload": {"turn": 7, "stdout": "ok", "exit_code": 0}},
  52. ]
  53. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  54. {"session_id": src_session, "events": burst})
  55. check(status == 200 and int(body.get("stored") or 0) == 2,
  56. "the event batch stores under its session")
  57. stored_once = rows_for(src_session)
  58. # Redelivery under the SAME session: consumed, nothing new.
  59. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  60. {"session_id": src_session, "events": burst})
  61. check(status == 200 and int(body.get("stored") or 0) == 0
  62. and rows_for(src_session) == stored_once,
  63. "a same-session redelivery stores nothing new (consumed silently)")
  64. # Session churn: a mis-keyed outbox send under a brand-new session
  65. # id replays the SAME seqs. The ledger's idempotency key is
  66. # (session_id, seq) — the churned session is a different key, so
  67. # the events store under it (the daemon contract makes the session
  68. # id part of the key; the old daemon-global entry dedup is gone).
  69. conn = db()
  70. conn.execute(
  71. "insert into tasks (project_id, title, status, priority, created_at,"
  72. " completed_at) values (1, 'Churn target task', 'done', 5,"
  73. " strftime('%s','now'), strftime('%s','now'))")
  74. conn.commit()
  75. churn_task = conn.execute(
  76. "select max(id) from tasks where title = 'Churn target task'").fetchone()[0]
  77. conn.close()
  78. churn_session = open_session_on_fake(churn_task)
  79. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  80. {"session_id": churn_session, "events": burst})
  81. check(status == 200 and int(body.get("stored") or 0) == 2
  82. and rows_for(churn_session) == 2,
  83. "a churned-session replay stores under the new key (per-session seq)")
  84. # Web restart: the idempotency survives (database constraint, not
  85. # memory) — the same-session redelivery still stores nothing.
  86. app.terminate()
  87. app.wait(timeout=10)
  88. app = start_app()
  89. auth = login("admin", "adminpass123")
  90. ctx.app = app # teardown tracks the restarted process
  91. ctx.auth = auth
  92. # The restart wiped the in-memory ask bookkeeping; the daemon
  93. # re-establishes sleeping with a fresh ask (the real daemon's
  94. # idle-awake ask / 15-minute safety self-ask).
  95. fake.ask_now()
  96. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  97. {"session_id": churn_session, "events": burst})
  98. check(status == 200 and int(body.get("stored") or 0) == 0
  99. and rows_for(churn_session) == 2,
  100. "a post-restart redelivery still stores nothing (persistent)")
  101. print("== plan 13 B2: duplicate failed pushes project once (task) ==")
  102. # The post-mortem's honest burst, rebuilt on the state channel: the
  103. # failed state redelivered repeatedly — one transition, one
  104. # summary, ever (terminal pushes are consumed silently).
  105. def agent_comments(task_id, body=None):
  106. conn = db()
  107. try:
  108. if body is None:
  109. return conn.execute(
  110. "select count(*) from task_comments"
  111. " where task_id = ? and author = 'agent'",
  112. (task_id,)).fetchone()[0]
  113. return conn.execute(
  114. "select count(*) from task_comments"
  115. " where task_id = ? and author = 'agent' and body = ?",
  116. (task_id, body)).fetchone()[0]
  117. finally:
  118. conn.close()
  119. conn = db()
  120. conn.execute(
  121. "insert into tasks (project_id, title, status, priority, created_at)"
  122. " values (1, 'Burst failure task', 'working', 5, strftime('%s','now'))")
  123. conn.commit()
  124. burst_task = conn.execute(
  125. "select max(id) from tasks where title = 'Burst failure task'").fetchone()[0]
  126. conn.close()
  127. burst_session = open_session_on_fake(burst_task)
  128. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  129. {"session_id": burst_session, "state": "failed",
  130. "summary": "bash -n rejected the script"})
  131. check(status == 200
  132. and task_state(auth, burst_task)["status"] == "failed",
  133. "the failure state push fails the task")
  134. check(agent_comments(burst_task, "bash -n rejected the script") == 0
  135. and "bash -n rejected the script"
  136. in (task_state(auth, burst_task).get("summary") or ""),
  137. "the failure explanation lives ONCE — in tasks.summary, the terminal cache (S4: no duplicate agent comment)")
  138. # The burst: the same failure redelivered under the session AND a
  139. # churned session — nothing re-runs.
  140. churned_burst = open_session_on_fake(burst_task)
  141. for target in (burst_session, churned_burst):
  142. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  143. {"session_id": target, "state": "failed",
  144. "summary": "bash -n rejected the script"})
  145. check(status == 200,
  146. "the failed-state push under %s is consumed, not rejected" % (
  147. "its session" if target == burst_session else "a churned session"))
  148. check(task_state(auth, burst_task)["status"] == "failed"
  149. and agent_comments(burst_task) == 0
  150. and "bash -n rejected the script"
  151. in (task_state(auth, burst_task).get("summary") or ""),
  152. "duplicate failed pushes leave one transition, one summary, zero agent comments (S4)")
  153. print("== plan 13 B2: goal failure projects once ==")
  154. # Goal context: `saddle failure` fails the goal ONCE — the 115
  155. # goal-failed events of the live failure are structurally gone.
  156. def goal_failed_events(goal_id):
  157. # Plan 15 C3: the narrative derives at read time — the
  158. # failed-goal row IS the goal-failed record (one row, ever).
  159. return len([e for e in goal_state(goal_id)["events"]
  160. if e["kind"] == "goal-failed"])
  161. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  162. "project_id": "1", "title": "Burst goal", "brief": "Fails honestly.",
  163. "branch_name": "goal/burst"})
  164. conn = db()
  165. burst_goal = conn.execute(
  166. "select id from goals where title = 'Burst goal'").fetchone()[0]
  167. conn.close()
  168. fake.goal_script = [("suspend",)]
  169. act(auth, goal_state(burst_goal)["start"], {})
  170. conn = db()
  171. run_task = conn.execute(
  172. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  173. (burst_goal,)).fetchone()[0]
  174. conn.close()
  175. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  176. or False, timeout=60, what="burst goal agent parks") is not None,
  177. "the burst goal's agent parks first")
  178. conn = db()
  179. run_session = conn.execute(
  180. "select max(id) from sessions where task_id = ?",
  181. (run_task,)).fetchone()[0]
  182. conn.close()
  183. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  184. {"session_id": run_session, "state": "failed",
  185. "summary": "the harness collapsed"})
  186. check(status == 200 and goal_state(burst_goal)["status"] == "failed",
  187. "the goal agent's failure fails the goal")
  188. check(goal_failed_events(burst_goal) == 1,
  189. "the failure push records exactly one goal-failed event")
  190. # Redeliveries — under the run's session AND a churned session —
  191. # plus the bare failed state again: still one.
  192. churned_run = open_session_on_fake(run_task)
  193. for target in (run_session, churned_run):
  194. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  195. {"session_id": target, "state": "failed",
  196. "summary": "the harness collapsed"})
  197. check(status == 200, "the goal-failure redelivery under %s is consumed"
  198. % ("its session" if target == run_session else "a churned session"))
  199. check(goal_state(burst_goal)["status"] == "failed"
  200. and goal_failed_events(burst_goal) == 1,
  201. "redelivered failures never re-run the goal failure (one event, ever)")
  202. check(task_state(auth, run_task)["status"] == "failed",
  203. "the goal-run task stays failed after the replays")
  204. conn = db()
  205. burst_blocks = conn.execute(
  206. "select count(*) from task_blocks where task_id = ?", (run_task,)
  207. ).fetchone()[0]
  208. conn.close()
  209. check(burst_blocks == 0,
  210. "the goal-failed path raises ZERO blocks (nothing pins the pile)")
  211. print("== plan 17: agent remarks ride the ledger as comment events ==")
  212. # The heredoc `cat << 'EOF' | saddle comment` shape: the daemon
  213. # emits a comment event carrying the body. The body is the record —
  214. # no command echo ever renders, and the goal page's current-activity
  215. # line reads the newest remark.
  216. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  217. "project_id": "1", "title": "Comment goal", "brief": "Reports cleanly.",
  218. "branch_name": "goal/comment"})
  219. conn = db()
  220. comment_goal = conn.execute(
  221. "select id from goals where title = 'Comment goal'").fetchone()[0]
  222. conn.close()
  223. fake.goal_script = [("suspend",)]
  224. act(auth, goal_state(comment_goal)["start"], {})
  225. conn = db()
  226. comment_run = conn.execute(
  227. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  228. (comment_goal,)).fetchone()[0]
  229. conn.close()
  230. check(wait_for(lambda: task_state(auth, comment_run)["status"] == "suspended"
  231. or False, timeout=60, what="comment goal agent parks") is not None,
  232. "the comment goal's agent parks")
  233. conn = db()
  234. comment_session = conn.execute(
  235. "select max(id) from sessions where task_id = ?",
  236. (comment_run,)).fetchone()[0]
  237. conn.close()
  238. comment_body = "The flange weld holds. First sentence carries the information."
  239. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  240. {"session_id": comment_session,
  241. "events": [{
  242. "seq": 8001, "kind": "comment",
  243. "actor": "model",
  244. "payload": {"body": comment_body}}]})
  245. check(status == 200 and int(body.get("stored") or 0) == 1,
  246. "the comment event stores on the ledger")
  247. conn = db()
  248. tables = {r[0] for r in conn.execute(
  249. "select name from sqlite_master where type = 'table'").fetchall()}
  250. comment_events = conn.execute(
  251. "select count(*) from events where scope_id = ? and kind = 'comment'",
  252. (comment_run,)).fetchone()[0]
  253. conn.close()
  254. check(comment_events == 1
  255. and "goal_comments" not in tables,
  256. "the ledger carries the remark (the goal_comments table is gone)")
  257. narrative_comments = [e["text"] for e in goal_state(comment_goal)["events"]
  258. if e["kind"] == "comment"]
  259. check(len(narrative_comments) == 1
  260. and narrative_comments[0].startswith("The flange weld holds.")
  261. and "saddle comment" not in narrative_comments[0]
  262. and "EOF" not in narrative_comments[0],
  263. "the derived narrative's comment rows carry the body text")
  264. state = goal_state(comment_goal)
  265. check(state["current_command"] == comment_body,
  266. "the goal page's current-activity line shows the remark body")
  267. check(any(e["kind"] == "comment"
  268. and e["text"].startswith("The flange weld holds.")
  269. for e in state["events"]),
  270. "the goal slot carries the remark in its narrative")
  271. page = http_get_page(auth, "/goals/%d" % comment_goal)
  272. check("saddle comment" not in page,
  273. "the rendered goal page never shows the command echo")
  274. check("event.kind == 'comment' ? ' footnote'" in page,
  275. "the narrative's comment events render with footnote styling")
  276. # Drain: nothing queued remains for the shard's shutdown.
  277. check(queued_count() == 0, "the replay shard drains its queue")