Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_template_runner.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_template_runner.py · 29.5 KB · 706 lines
1"""The template runner: hold the money, run the job, settle exactly once.
2
3Slice 1 of plan/template-runner-spec.md, and the money model is the part
4that cannot be retrofitted, so it is the part this file leans on:
5
6THE GATE FIRES AT COMMITMENT. The hold is a negative wallet entry placed
7at queue time through hook_wallet_entries, so a user with five cents
8cannot queue four hundred runs and present the provider bill later. The
9four-hundredth hold fails the gate.
10
11SETTLEMENT IS RELEASE + ORDINARY DEBIT, EXACTLY ONCE. Success releases
12the hold in full and charges a plain debit for the stamped price; failure
13releases alone. Idempotent by provenance marker checked against the
14ENTRIES, never run.status, because the crash worth designing for is the
15one between writing money and updating status.
16
17A STALE RUN IS NEVER RETRIED. The provider call is not idempotent and is
18not ours; abandoned is a terminal status with no exits in the declared
19transition map, and the sweeper releases the hold and stops.
20"""
21
22import json
23import pathlib
24import shutil
25
26import pytest
27from conftest import stage_collection
28
29import object_execution
30import object_records
31import object_template_runs
32import python_object_runtime
33
34REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
35PACKAGES = REPO_ROOT / "packages"
36RUNNER_OBJECTS = PACKAGES / "app-runner" / "objects"
37BILLING_OBJECTS = PACKAGES / "app-billing" / "objects"
38RUNTIME = python_object_runtime.PythonObjectRuntime()
39
40
41# --- the pure module -----------------------------------------------------------
42
43def template(**fields):
44 # dan's own template: action_run_template asks the permission engine
45 # whether the caller may read it (owner, is_public, admin).
46 row = {"id": "t1", "name": "Greeting", "handler": "echo",
47 "body": "Hello {name}, welcome to {place}.",
48 "run_cost_cents": "50", "owner_id": "dan",
49 "schema": json.dumps({"properties": {"name": {"title": "Name"},
50 "place": {}},
51 "required": ["name"]})}
52 row.update({k: str(v) for k, v in fields.items()})
53 return row
54
55
56def test_placeholders_fill_from_the_form_and_unknown_ones_survive():
57 """A brace in prose must not kill a run, and a silently emptied
58 placeholder is a prompt that quietly lost its subject -- the worst
59 outcome, because the provider answers SOMETHING and charges for it."""
60 out = object_template_runs.render("Hi {name}, re: {TBD}", {"name": "Ada"})
61 assert out == "Hi Ada, re: {TBD}"
62
63
64def test_every_missing_required_field_is_reported_together():
65 found = object_template_runs.problems(template(handler=""), {})
66 joined = " ".join(found)
67 assert len(found) == 2, found
68 assert "declares no handler" in joined
69 assert "'Name' is required" in joined
70
71
72def test_the_stamp_carries_everything_execution_needs():
73 """The run must be immune to every future edit of the template --
74 including re-rendering, because rendering reads the template and by
75 execution time the template may say something else."""
76 stamped = object_template_runs.stamp(template(), {"name": "Ada",
77 "place": "the shop"},
78 model="anthropic:claude-sonnet-4-5")
79 assert stamped["rendered_body"] == "Hello Ada, welcome to the shop."
80 assert stamped["price_cents"] == "50"
81 assert stamped["handler"] == "echo"
82 assert stamped["model"] == "anthropic:claude-sonnet-4-5"
83 assert json.loads(stamped["form_data"]) == {"name": "Ada",
84 "place": "the shop"}
85
86
87def run_row(**fields):
88 row = {"id": "r1", "price_cents": "50", "wallet_id": "w1",
89 "owner_id": "dan", "template_name": "Greeting",
90 "status": "claimed"}
91 row.update({k: str(v) for k, v in fields.items()})
92 return row
93
94
95def test_success_settles_as_an_ordinary_debit_then_the_release():
96 """Debit first: written release-first, the hold's money was free for one
97 write and a hold placed in it spent the money twice
98 (tests/test_wallet_debit_claims.py)."""
99 entries = object_template_runs.settlement(run_row(), succeeded=True)
100 assert [e["kind"] for e in entries] == ["debit", "release"]
101 assert [int(e["amount_minor"]) for e in entries] == [-50, 50]
102 assert entries[0]["generated_from"] == "template_run/r1/charge"
103 assert entries[1]["generated_from"] == "template_run/r1/release"
104
105
106def test_failure_settles_as_release_alone():
107 """The user pays nothing for a run that did not do the thing,
108 whatever it cost US at the provider."""
109 entries = object_template_runs.settlement(run_row(), succeeded=False)
110 assert [e["kind"] for e in entries] == ["release"]
111 assert int(entries[0]["amount_minor"]) == 50
112
113
114def test_a_free_run_touches_no_wallet_at_all():
115 assert object_template_runs.settlement(run_row(price_cents="0"),
116 succeeded=True) == []
117 assert object_template_runs.hold_entry("r1", "w1", 0, "dan") is None
118
119
120def test_the_charge_is_a_debit_and_the_release_is_not_a_refund():
121 """The reason hold/release are the only new kinds: every report that
122 already reads debits keeps working, and a released hold never
123 masquerades as money returned to a customer."""
124 entries = object_template_runs.settlement(run_row(), succeeded=True)
125 kinds = {e["kind"] for e in entries}
126 assert "refund" not in kinds
127 assert "debit" in kinds
128
129
130def test_already_settled_reads_the_entries_and_never_the_status():
131 entries = [{"generated_from": "template_run/r1/release"}]
132 assert object_template_runs.already_settled("r1", entries) is True
133 assert object_template_runs.already_settled("r2", entries) is False
134
135
136def test_outstanding_holds_is_a_fold_over_the_entries():
137 entries = [
138 {"generated_from": "template_run/r1/hold", "amount_minor": "-50"},
139 {"generated_from": "template_run/r2/hold", "amount_minor": "-30"},
140 {"generated_from": "template_run/r1/release", "amount_minor": "50"},
141 {"generated_from": "checkout/x", "amount_minor": "-99"},
142 ]
143 assert object_template_runs.outstanding_holds(entries) == {"r2": 30}
144
145
146def test_staleness_is_pure_and_only_claimed_runs_can_be_stale():
147 now = "2026-07-26T12:00:00Z"
148 old = {"status": "claimed", "heartbeat_at": "2026-07-26T11:30:00Z"}
149 fresh = {"status": "claimed", "heartbeat_at": "2026-07-26T11:59:00Z"}
150 queued = {"status": "queued", "heartbeat_at": "2026-07-26T01:00:00Z"}
151 assert object_template_runs.is_stale(old, now=now, stale_seconds=900)
152 assert not object_template_runs.is_stale(fresh, now=now, stale_seconds=900)
153 assert not object_template_runs.is_stale(queued, now=now, stale_seconds=900)
154
155
156# --- through the objects, money and all ----------------------------------------
157
158@pytest.fixture
159def data_dir(tmp_path, monkeypatch):
160 base = tmp_path / "data"
161 stage_collection(base, "app-runner", "template_runs")
162 stage_collection(base, "app-templates", "templates")
163 stage_collection(base, "app-billing", "wallets")
164 stage_collection(base, "app-billing", "wallet_entries")
165 stage_collection(base, "app-settings", "app_settings")
166 # Both roots merged into one tree and exported via the environment,
167 # the way test_promotions does it: action_run_template asks
168 # hook_wallet_entries through a FRESH in-process runtime (the same
169 # mechanism the shop uses), and that runtime resolves objects from the
170 # environment, not from this test's execute_object roots.
171 objects_root = tmp_path / "objects"
172 for source in (RUNNER_OBJECTS, BILLING_OBJECTS):
173 shutil.copytree(source, objects_root, dirs_exist_ok=True)
174 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
175 monkeypatch.setenv("DBBASIC_DATA_DIR", str(base))
176 return base
177
178
179def run_object(object_id, payload, *, method="POST"):
180 return object_execution.execute_object(
181 RUNTIME,
182 object_execution.ObjectExecutionRequest(object_id, method=method,
183 payload=payload)).result
184
185
186def seed_template(data_dir, **fields):
187 return object_records.create_collection_record(
188 "templates", template(**fields), base_dir=data_dir)
189
190
191def seed_wallet(data_dir, cents, wallet_id="w1", owner="dan"):
192 object_records.create_collection_record(
193 "wallets", {"id": wallet_id, "owner_id": owner, "kind": "balance",
194 "is_active": "true"},
195 base_dir=data_dir)
196 if cents:
197 object_records.create_collection_record(
198 "wallet_entries",
199 {"wallet_id": wallet_id, "amount_minor": str(cents),
200 "kind": "topup", "owner_id": owner},
201 base_dir=data_dir)
202
203
204def queue(data_dir, **payload):
205 payload.setdefault("template_id", "t1")
206 payload.setdefault("form_data", {"name": "Ada", "place": "the shop"})
207 payload.setdefault("_identity", {"user_id": "dan"})
208 return run_object("action_run_template", payload)
209
210
211def balance(data_dir, wallet_id="w1"):
212 return sum(int(row.get("amount_minor") or 0)
213 for row in object_records.read_collection_records(
214 "wallet_entries", base_dir=data_dir)
215 if row.get("wallet_id") == wallet_id)
216
217
218def test_queueing_places_the_hold_and_stamps_the_terms(data_dir):
219 seed_template(data_dir)
220 seed_wallet(data_dir, 200)
221
222 queued = queue(data_dir)
223 assert queued["ok"] is True and queued["held"] is True
224
225 assert balance(data_dir) == 150 # 200 - 50 held
226
227 run = object_records.read_collection_records("template_runs",
228 base_dir=data_dir)[0]
229 assert run["status"] == "queued"
230 assert run["rendered_body"] == "Hello Ada, welcome to the shop."
231 assert run["price_cents"] == "50"
232 assert run["idempotency_key"] # minted before any call
233
234
235def test_the_gate_refuses_the_run_the_balance_cannot_cover(data_dir):
236 """THE reason holds exist: the gate is asked at commitment. Three runs
237 fit a 120-cent balance twice; the third is refused with the wallet
238 still intact and nothing queued."""
239 seed_template(data_dir)
240 seed_wallet(data_dir, 120)
241
242 assert queue(data_dir)["ok"] is True
243 assert queue(data_dir)["ok"] is True
244 refused = queue(data_dir)
245 assert refused["status"] == 402
246 assert "Insufficient wallet balance" in refused["error"]
247
248 assert balance(data_dir) == 20 # two holds, no third
249 runs = object_records.read_collection_records("template_runs",
250 base_dir=data_dir)
251 assert len(runs) == 2
252
253
254def test_editing_the_template_after_queueing_restates_nothing(data_dir):
255 """Doctrine #1, on runs: the stamped terms are the terms."""
256 seed_template(data_dir)
257 seed_wallet(data_dir, 200)
258 queue(data_dir)
259
260 object_records.update_collection_record(
261 "templates", "t1",
262 {"body": "Completely different {name}", "run_cost_cents": "9000"},
263 base_dir=data_dir)
264
265 result = run_object("system_template_runner", {})
266 assert result["claimed"] == 1
267 run = object_records.read_collection_records("template_runs",
268 base_dir=data_dir)[0]
269 assert run["status"] == "succeeded"
270 assert run["output"] == "Hello Ada, welcome to the shop."
271 assert balance(data_dir) == 150 # charged 50, not 9000
272
273
274def test_a_successful_run_settles_release_plus_debit_and_only_once(data_dir):
275 seed_template(data_dir)
276 seed_wallet(data_dir, 200)
277 queue(data_dir)
278
279 run_object("system_template_runner", {})
280 assert balance(data_dir) == 150 # 200 - 50 charged
281
282 entries = object_records.read_collection_records("wallet_entries",
283 base_dir=data_dir)
284 kinds = sorted(e["kind"] for e in entries)
285 assert kinds == ["debit", "hold", "release", "topup"]
286
287 # A second pass finds nothing queued and, crucially, re-settles nothing.
288 again = run_object("system_template_runner", {})
289 assert again["claimed"] == 0
290 assert balance(data_dir) == 150
291
292
293def test_a_failed_run_costs_the_user_nothing(data_dir):
294 seed_template(data_dir, handler="ai_text") # queue-time check passes...
295 seed_wallet(data_dir, 200)
296 object_records.create_collection_record(
297 "app_settings", {"key": "runner.ai_model",
298 "value": "anthropic:claude-sonnet-4-5"},
299 base_dir=data_dir)
300 import object_service_keys
301 object_service_keys.set_service_key("dan", "anthropic", "sk-test-not-real",
302 base_dir=data_dir)
303 queue(data_dir)
304 import object_service_keys as keys
305 keys.remove_service_key("dan", "anthropic", base_dir=data_dir)
306
307 result = run_object("system_template_runner", {}) # ...and execution fails
308 assert result["results"][0]["status"] == "failed"
309
310 run = object_records.read_collection_records("template_runs",
311 base_dir=data_dir)[0]
312 assert run["status"] == "failed"
313 assert "API key" in run["error"]
314 assert balance(data_dir) == 200 # hold released in full
315 kinds = sorted(e["kind"] for e in object_records.read_collection_records(
316 "wallet_entries", base_dir=data_dir))
317 assert "debit" not in kinds
318
319
320def test_a_free_template_runs_without_a_wallet_existing_at_all(data_dir):
321 """Money machinery that runs for free jobs is machinery that fails
322 for free jobs -- so for a zero-price template there must be none."""
323 seed_template(data_dir, run_cost_cents="0")
324 queued = queue(data_dir)
325 assert queued["ok"] is True and queued["held"] is False
326
327 run_object("system_template_runner", {})
328 run = object_records.read_collection_records("template_runs",
329 base_dir=data_dir)[0]
330 assert run["status"] == "succeeded"
331 assert not object_records.read_collection_records("wallet_entries",
332 base_dir=data_dir)
333
334
335def test_an_ai_template_with_no_provider_is_refused_at_queue_time(data_dir):
336 """The capability boundary, refused while the person who can fix it
337 is looking at the screen -- not discovered on the daemon an hour
338 later. Nothing queued, nothing held."""
339 seed_template(data_dir, handler="ai_text")
340 seed_wallet(data_dir, 200)
341
342 refused = queue(data_dir)
343 assert refused["status"] == 409
344 assert "runner.ai_model" in refused["error"]
345 assert balance(data_dir) == 200
346 assert not object_records.read_collection_records("template_runs",
347 base_dir=data_dir)
348
349
350def test_an_anonymous_run_is_refused_because_runs_cost_money(data_dir):
351 seed_template(data_dir)
352 refused = run_object("action_run_template",
353 {"template_id": "t1", "form_data": {"name": "x"}})
354 assert refused["status"] == 401
355 assert "open tap" in refused["error"]
356
357
358def test_a_template_with_no_handler_is_a_document_not_a_job(data_dir):
359 seed_template(data_dir, handler="")
360 refused = queue(data_dir)
361 assert refused["status"] == 400
362 assert "declares no handler" in refused["error"]
363
364
365# --- the sweeper ----------------------------------------------------------------
366
367def test_a_stale_run_is_abandoned_refunded_and_never_requeued(data_dir):
368 seed_template(data_dir)
369 seed_wallet(data_dir, 200)
370 queue(data_dir)
371
372 run = object_records.read_collection_records("template_runs",
373 base_dir=data_dir)[0]
374 object_records.update_collection_record(
375 "template_runs", run["id"],
376 {"status": "claimed", "claimed_by": "a-runner-that-died",
377 "claimed_at": "2026-07-26T01:00:00Z",
378 "heartbeat_at": "2026-07-26T01:00:00Z"},
379 base_dir=data_dir)
380
381 result = run_object("system_run_sweeper", {"now": "2026-07-26T12:00:00Z"})
382 assert result["swept"] == 1
383
384 swept = object_records.read_collection_records("template_runs",
385 base_dir=data_dir)[0]
386 assert swept["status"] == "abandoned"
387 assert "NOT retried" in swept["error"]
388 assert balance(data_dir) == 200 # the hold came back in full
389
390 # And the runner never picks it up again: abandoned is not queued.
391 after = run_object("system_template_runner", {})
392 assert after["claimed"] == 0
393
394 # Sweeping again releases nothing twice.
395 again = run_object("system_run_sweeper", {"now": "2026-07-26T13:00:00Z"})
396 assert again["swept"] == 0 or all(r["hold"] == "already settled"
397 for r in again["runs"])
398 assert balance(data_dir) == 200
399
400
401def test_abandoned_is_a_dead_end_in_the_declared_state_machine():
402 """The transition map is the enforcement: no status may move a run
403 out of abandoned, so nothing -- not a bug, not a helpful operator
404 endpoint added later -- can quietly re-run a paid provider call."""
405 schema = json.loads((PACKAGES / "app-runner" / "schemas"
406 / "template_runs.json").read_text())
407 status = next(f for f in schema["fields"] if f["name"] == "status")
408 transitions = status["transitions"]
409 assert "abandoned" not in transitions # no exits
410 assert "succeeded" not in transitions
411 assert "failed" not in transitions
412 for moves in transitions.values():
413 assert "queued" not in moves # nothing moves BACK to queued
414
415
416def test_nothing_in_the_package_retries_a_run():
417 """Named as a grep on the whole package, the same way app-notary pins
418 its no-delete rule: the risk is not today's code, it is somebody later
419 adding retry as an improvement to a paid non-idempotent call."""
420 for path in (PACKAGES / "app-runner").rglob("*.py"):
421 source = path.read_text()
422 assert '"queued"}' not in source.replace("status\": \"queued", ""), path
423 # No update may ever set a run BACK to queued.
424 assert '{"status": "queued"' not in source, path
425
426
427def test_the_runner_and_sweeper_declare_EVENT():
428 for name in ("template_runner", "run_sweeper"):
429 source = (PACKAGES / "app-runner" / "objects" / "system"
430 / f"{name}.py").read_text()
431 assert "def EVENT(" in source, name
432 assert "POST = EVENT" in source, name
433
434
435def test_wallet_entries_gained_hold_and_release_and_nothing_was_removed():
436 schema = json.loads((PACKAGES / "app-billing" / "schemas"
437 / "wallet_entries.json").read_text())
438 kind = next(f for f in schema["fields"] if f["name"] == "kind")
439 assert set(kind["enum"]) == {"topup", "auto_topup", "debit", "refund",
440 "promo", "adjustment", "hold", "release"}
441
442
443# --- the claim race (63) --------------------------------------------------------
444#
445# The bug this closes was shipped and deployed before it was found, and it
446# is worth stating exactly: two passes -- the minutely schedule and an
447# operator pressing Run Now -- both read the same row as `queued`, both
448# wrote `claimed` (the transition check is a no-op when old == new), and
449# both ran the handler. Settlement is idempotent, so the USER was charged
450# once. That is what made it dangerous: the duplicate landed on OUR side
451# of the ledger as a second provider bill, which nothing in the money
452# model was watching.
453
454def _runner_module():
455 import importlib.util
456 spec = importlib.util.spec_from_file_location(
457 "_tr", PACKAGES / "app-runner" / "objects" / "system"
458 / "template_runner.py")
459 module = importlib.util.module_from_spec(spec)
460 spec.loader.exec_module(module)
461 return module
462
463
464def test_a_pass_holding_a_stale_row_loses_the_claim_and_never_executes(data_dir):
465 """Deterministic version: read a run, let somebody else move it, then
466 try to claim it with the row we read. The handler must not run."""
467 seed_template(data_dir)
468 seed_wallet(data_dir, 200)
469 queue(data_dir)
470
471 stale = object_records.read_collection_records("template_runs",
472 base_dir=data_dir)[0]
473
474 # Another pass gets there first.
475 object_records.update_collection_record(
476 "template_runs", stale["id"],
477 {"status": "claimed", "claimed_by": "the-other-pass"},
478 base_dir=data_dir)
479
480 result = _runner_module()._execute_one(data_dir, stale, 30)
481 assert result["status"] == "lost_claim"
482 assert result["settlement"] == "not ours"
483
484 run = object_records.read_collection_records("template_runs",
485 base_dir=data_dir)[0]
486 assert run["claimed_by"] == "the-other-pass" # not overwritten
487 assert run["output"] == "" # handler never ran
488 assert balance(data_dir) == 150 # still just the hold
489
490
491def test_two_concurrent_passes_execute_a_run_exactly_once(data_dir):
492 """The integration proof. Before the fix this reported [1, 1] and two
493 executions; a provider handler would have been called twice and billed
494 twice. Cannot fail spuriously: if the threads happen to serialise, the
495 second pass simply finds nothing queued -- still one execution."""
496 import threading
497
498 seed_template(data_dir)
499 seed_wallet(data_dir, 200)
500 queue(data_dir)
501
502 results = []
503 threads = [threading.Thread(
504 target=lambda: results.append(run_object("system_template_runner", {})))
505 for _ in range(2)]
506 for thread in threads:
507 thread.start()
508 for thread in threads:
509 thread.join()
510
511 assert sum(r["claimed"] for r in results) == 1, results
512
513 runs = object_records.read_collection_records("template_runs",
514 base_dir=data_dir)
515 assert len(runs) == 1 and runs[0]["status"] == "succeeded"
516 assert balance(data_dir) == 150 # charged exactly once
517
518
519def test_the_sweeper_will_not_write_off_a_run_that_moved_under_it(data_dir):
520 """The sweeper races the runner it is sweeping. A run that heartbeats
521 between the staleness read and the write has changed the row, so the
522 write-off loses -- otherwise the sweeper hands back money for work
523 that was in the middle of succeeding."""
524 seed_template(data_dir)
525 seed_wallet(data_dir, 200)
526 queue(data_dir)
527
528 stale = object_records.read_collection_records("template_runs",
529 base_dir=data_dir)[0]
530 object_records.update_collection_record(
531 "template_runs", stale["id"],
532 {"status": "claimed", "claimed_by": "runner",
533 "claimed_at": "2026-07-26T01:00:00Z",
534 "heartbeat_at": "2026-07-26T01:00:00Z"},
535 base_dir=data_dir)
536
537 import object_records as records
538 with pytest.raises(records.VersionConflictError):
539 records.update_collection_record(
540 "template_runs", stale["id"], {"status": "abandoned"},
541 base_dir=data_dir,
542 expected_rev=records.compute_record_rev(stale))
543
544
545def test_the_sweeper_repairs_a_hold_a_crash_left_behind(data_dir):
546 """Step 2 is driven by STATE, not by 'did step 1 just run'. A crash
547 between writing off a run and releasing its hold used to leave money
548 reserved forever, because a run already marked abandoned is no longer
549 stale and would never be looked at again."""
550 seed_template(data_dir)
551 seed_wallet(data_dir, 200)
552 queue(data_dir)
553 assert balance(data_dir) == 150 # held
554
555 run = object_records.read_collection_records("template_runs",
556 base_dir=data_dir)[0]
557 # Exactly the state a crash between the two steps leaves: terminal,
558 # with the hold still on.
559 object_records.update_collection_record(
560 "template_runs", run["id"], {"status": "abandoned"},
561 base_dir=data_dir)
562
563 result = run_object("system_run_sweeper", {"now": "2026-07-26T12:00:00Z"})
564 assert run["id"] in result["holds_released"]
565 assert balance(data_dir) == 200 # money back, without a retry
566
567 # And it is not released a second time.
568 again = run_object("system_run_sweeper", {"now": "2026-07-26T13:00:00Z"})
569 assert again["holds_released"] == []
570 assert balance(data_dir) == 200
571
572
573# --- task_id: one execution model, not a second one (q9's tasks.Work) ----------
574
575def seed_task(data_dir, task_id="task-1", owner="dan", **fields):
576 stage_collection(data_dir, "app-tasks", "tasks")
577 row = {"id": task_id, "title": "Review the homepage", "owner_id": owner}
578 row.update(fields)
579 return object_records.create_collection_record("tasks", row, base_dir=data_dir)
580
581
582def test_a_run_can_be_queued_against_a_task_the_caller_owns(data_dir):
583 seed_template(data_dir)
584 seed_wallet(data_dir, 200)
585 seed_task(data_dir, owner="dan")
586
587 queued = queue(data_dir, task_id="task-1")
588 assert queued["ok"] is True
589
590 run = object_records.read_collection_records("template_runs",
591 base_dir=data_dir)[0]
592 assert run["task_id"] == "task-1"
593
594
595def test_task_id_is_entirely_optional_and_unchanged_by_default(data_dir):
596 """The regression that would matter most: a template runner that
597 could only run FROM a task would break every ad-hoc run (a SWOT from
598 the shell, a one-off from Talk) that has nothing to do with one."""
599 seed_template(data_dir)
600 seed_wallet(data_dir, 200)
601
602 queued = queue(data_dir) # no task_id at all
603 assert queued["ok"] is True
604 run = object_records.read_collection_records("template_runs",
605 base_dir=data_dir)[0]
606 assert run["task_id"] == ""
607
608
609def test_a_run_cannot_be_linked_to_a_task_that_does_not_exist(data_dir):
610 seed_template(data_dir)
611 seed_wallet(data_dir, 200)
612
613 result = queue(data_dir, task_id="no-such-task")
614 assert result["status"] == 404
615 assert object_records.read_collection_records("template_runs",
616 base_dir=data_dir) == []
617
618
619def test_a_run_cannot_be_linked_to_someone_elses_task(data_dir):
620 """Refused at queue time, same 'refused while somebody is looking'
621 posture as the capability-boundary checks beside it -- letting the
622 link through would leak a stranger's task existence and status
623 through what the run settles against. Refused with the SAME 404 as a
624 task that does not exist: a 403 here confirmed the id was real."""
625 seed_template(data_dir)
626 seed_wallet(data_dir, 200)
627 seed_task(data_dir, task_id="not-mine", owner="mallory")
628
629 result = queue(data_dir, task_id="not-mine")
630 assert result["status"] == 404
631 missing = queue(data_dir, task_id="no-such-task")
632 assert missing["error"].replace("no-such-task", "not-mine") == result["error"]
633 assert object_records.read_collection_records("template_runs",
634 base_dir=data_dir) == []
635 # And nothing was held either -- the check runs before the hold.
636 assert balance(data_dir) == 200
637
638
639def test_an_admin_can_link_a_run_to_anyones_task(data_dir):
640 seed_template(data_dir)
641 seed_task(data_dir, task_id="someones", owner="mallory")
642 # The admin's OWN wallet holds the money -- linking to someone else's
643 # task changes whose task this serves, never who pays for it.
644 seed_wallet(data_dir, 200, wallet_id="w-ops", owner="ops")
645
646 result = queue(data_dir, task_id="someones",
647 **{"_identity": {"user_id": "ops", "roles": ["admin"]}})
648 assert result["ok"] is True, result
649
650
651def test_multiple_attempts_against_one_task_are_just_multiple_runs(data_dir):
652 """No second history collection -- q9's Work stored attempts in its
653 own rows; here it is a fold over template_runs sharing a task_id,
654 the same doctrine as every other one-to-many relationship in this
655 system."""
656 seed_template(data_dir)
657 seed_wallet(data_dir, 200)
658 seed_task(data_dir, owner="dan")
659
660 queue(data_dir, task_id="task-1")
661 queue(data_dir, task_id="task-1")
662
663 runs = [r for r in object_records.read_collection_records(
664 "template_runs", base_dir=data_dir)
665 if r.get("task_id") == "task-1"]
666 assert len(runs) == 2
667
668
669def test_a_run_never_mutates_the_tasks_own_status(data_dir):
670 """Deliberate. A run succeeding is not the same claim as 'this task
671 is finished' -- that is a human's call, or an agent's, looking at
672 the run's own output. Same 'the server notices, the person decides'
673 posture as system_reorder_check's suggestions."""
674 seed_template(data_dir)
675 seed_wallet(data_dir, 200)
676 seed_task(data_dir, owner="dan", status="open")
677
678 queue(data_dir, task_id="task-1")
679
680 task = object_records.get_collection_record("tasks", "task-1",
681 base_dir=data_dir)
682 assert task["status"] == "open"
683
684
685def test_the_task_detail_view_renders_the_runs_related_to_it():
686 """No new UI: the same `related` block order->order_lines already
687 uses, so a task's attempt history costs zero new client code."""
688 import csv
689 seed = (REPO_ROOT / "packages" / "app-tasks" / "seed" / "views.tsv")
690 rows = list(csv.DictReader(seed.read_text().splitlines(), delimiter="\t"))
691 detail = next(r for r in rows if r["id"] == "view_tasks_detail")
692 blocks = json.loads(detail["blocks"])
693 related = next((b for b in blocks if b.get("kind") == "related"), None)
694 assert related is not None, "no related block on the task detail view"
695 assert related["collection"] == "template_runs"
696 assert related["fk_field"] == "task_id"
697 assert related["match"] == "$record_id"
698
699
700def test_the_schema_declares_task_id_as_a_relation_to_tasks():
701 schema = json.loads((REPO_ROOT / "packages" / "app-runner" / "schemas"
702 / "template_runs.json").read_text())
703 field = next(f for f in schema["fields"] if f["name"] == "task_id")
704 assert field["type"] == "relation"
705 assert field["relation"]["collection"] == "tasks"
706 assert schema["version"] >= 2