askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_resolve_run.py · 13.0 KB · 303 lines
| 1 | """Resolving what the machine refused to decide. |
| 2 | |
| 3 | The sweeper stops a submitted-but-unresolved run at `needs_review` with |
| 4 | its hold intact, because both automatic answers are wrong: releasing |
| 5 | gives away money the provider may already have taken, charging bills for |
| 6 | work that may never have arrived. |
| 7 | |
| 8 | Stopping there is only a design if somebody can continue. A queue nobody |
| 9 | can act on is money parked forever, so this is the other half -- and it |
| 10 | is the only hand that moves a run out of needs_review. |
| 11 | """ |
| 12 | |
| 13 | import os |
| 14 | import pathlib |
| 15 | |
| 16 | import pytest |
| 17 | from conftest import stage_collection |
| 18 | from test_attention_declared import shipped_count |
| 19 | |
| 20 | import object_execution |
| 21 | import object_records |
| 22 | import object_template_runs |
| 23 | import python_object_runtime |
| 24 | |
| 25 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 26 | RUNNER_OBJECTS = REPO_ROOT / "packages" / "app-runner" / "objects" |
| 27 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 28 | |
| 29 | |
| 30 | def setup_env(tmp_path, monkeypatch, *, status="needs_review", price="600"): |
| 31 | data_dir = tmp_path / "data" |
| 32 | for pkg, name in (("app-runner", "template_runs"), |
| 33 | ("app-templates", "templates"), |
| 34 | ("app-billing", "wallets"), |
| 35 | ("app-billing", "wallet_entries")): |
| 36 | stage_collection(data_dir, pkg, name) |
| 37 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 38 | object_records.create_collection_record( |
| 39 | "templates", {"id": "tpl", "name": "Picture", "handler": "ai_image", |
| 40 | "body": "x", "owner_id": "dan"}, base_dir=data_dir) |
| 41 | object_records.create_collection_record( |
| 42 | "wallets", {"id": "w1", "owner_id": "dan", "is_active": "true"}, |
| 43 | base_dir=data_dir) |
| 44 | object_records.create_collection_record( |
| 45 | "wallet_entries", |
| 46 | {"wallet_id": "w1", "amount_minor": "5000", "kind": "topup", |
| 47 | "owner_id": "dan"}, base_dir=data_dir) |
| 48 | object_records.create_collection_record( |
| 49 | "wallet_entries", |
| 50 | {"wallet_id": "w1", "amount_minor": f"-{price}", "kind": "hold", |
| 51 | "generated_from": "template_run/r1/hold", "owner_id": "dan"}, |
| 52 | base_dir=data_dir) |
| 53 | object_records.create_collection_record( |
| 54 | "template_runs", |
| 55 | {"id": "r1", "template_id": "tpl", "template_name": "Picture", |
| 56 | "handler": "ai_image", "status": status, "price_cents": price, |
| 57 | "wallet_id": "w1", "owner_id": "dan", |
| 58 | "provider_job_id": "job-abc", "provider_cost_cents": "40", |
| 59 | "error": "unresolved after 3600s"}, |
| 60 | base_dir=data_dir) |
| 61 | return data_dir |
| 62 | |
| 63 | |
| 64 | def resolve(payload, *, user_id="dan", is_admin=False): |
| 65 | return object_execution.execute_object( |
| 66 | RUNTIME, |
| 67 | object_execution.ObjectExecutionRequest( |
| 68 | "action_resolve_run", method="POST", |
| 69 | # An admin is a ROLE, the way the server describes one in |
| 70 | # _identity; the action asks the permission engine, which reads |
| 71 | # roles (and the policy's admin_roles), never an is_admin flag. |
| 72 | payload={**payload, |
| 73 | "_identity": {"user_id": user_id, |
| 74 | "roles": ["admin"] if is_admin else []}}), |
| 75 | roots=[RUNNER_OBJECTS]).result |
| 76 | |
| 77 | |
| 78 | def kinds(data_dir): |
| 79 | return [e["kind"] for e in object_records.read_collection_records( |
| 80 | "wallet_entries", base_dir=data_dir) |
| 81 | if "template_run/r1/" in str(e.get("generated_from"))] |
| 82 | |
| 83 | |
| 84 | def test_charging_settles_the_run_as_delivered(tmp_path, monkeypatch): |
| 85 | data_dir = setup_env(tmp_path, monkeypatch) |
| 86 | result = resolve({"run_id": "r1", "decision": "charge", |
| 87 | "note": "file landed in the bucket"}) |
| 88 | assert result["ok"] and result["settlement"] == "settled" |
| 89 | |
| 90 | # Debit before release: written the other way round the hold's money |
| 91 | # was free for one write (tests/test_wallet_debit_claims.py). |
| 92 | assert kinds(data_dir) == ["hold", "debit", "release"] |
| 93 | run = object_records.get_collection_record("template_runs", "r1", |
| 94 | base_dir=data_dir) |
| 95 | assert run["status"] == "succeeded" |
| 96 | assert "file landed in the bucket" in run["error"] |
| 97 | assert "Resolved by dan as charge" in run["error"] |
| 98 | |
| 99 | |
| 100 | def test_refunding_releases_the_hold_and_charges_nothing(tmp_path, monkeypatch): |
| 101 | data_dir = setup_env(tmp_path, monkeypatch) |
| 102 | result = resolve({"run_id": "r1", "decision": "refund"}) |
| 103 | assert result["ok"] |
| 104 | |
| 105 | assert kinds(data_dir) == ["hold", "release"] |
| 106 | run = object_records.get_collection_record("template_runs", "r1", |
| 107 | base_dir=data_dir) |
| 108 | assert run["status"] == "failed" |
| 109 | |
| 110 | |
| 111 | def test_what_it_cost_us_stays_visible_after_a_refund(tmp_path, monkeypatch): |
| 112 | """Eating a provider cost is a number somebody can find, never a |
| 113 | silent write-off.""" |
| 114 | data_dir = setup_env(tmp_path, monkeypatch) |
| 115 | resolve({"run_id": "r1", "decision": "refund"}) |
| 116 | run = object_records.get_collection_record("template_runs", "r1", |
| 117 | base_dir=data_dir) |
| 118 | assert run["provider_cost_cents"] == "40" |
| 119 | |
| 120 | |
| 121 | def test_a_second_decision_writes_money_once(tmp_path, monkeypatch): |
| 122 | """Idempotent by the same release marker everything else uses.""" |
| 123 | data_dir = setup_env(tmp_path, monkeypatch) |
| 124 | resolve({"run_id": "r1", "decision": "charge"}) |
| 125 | before = kinds(data_dir) |
| 126 | again = resolve({"run_id": "r1", "decision": "charge"}) |
| 127 | assert again["status"] == 409 # no longer needs_review |
| 128 | assert kinds(data_dir) == before |
| 129 | |
| 130 | |
| 131 | def overlapping_decisions(monkeypatch, first, second): |
| 132 | """Decision A reads the run as needs_review; decision B then runs start |
| 133 | to finish, at the moment A is about to read the ledger; then A goes |
| 134 | on. Returns (A's answer, B's answer).""" |
| 135 | real = object_records.read_collection_records |
| 136 | state = {"second": None} |
| 137 | |
| 138 | def read(name, *args, **kwargs): |
| 139 | if name == "wallet_entries" and state["second"] is None: |
| 140 | state["second"] = "running" |
| 141 | state["second"] = resolve(second) |
| 142 | return real(name, *args, **kwargs) |
| 143 | |
| 144 | monkeypatch.setattr(object_records, "read_collection_records", read) |
| 145 | try: |
| 146 | return resolve(first), state["second"] |
| 147 | finally: |
| 148 | monkeypatch.setattr(object_records, "read_collection_records", real) |
| 149 | |
| 150 | |
| 151 | @pytest.mark.parametrize("first_decision,second_decision", |
| 152 | [("charge", "charge"), ("refund", "charge")]) |
| 153 | def test_two_overlapping_decisions_settle_the_run_once_and_its_status_agrees( |
| 154 | tmp_path, monkeypatch, first_decision, second_decision): |
| 155 | """The markers kept the money to one settlement, but both requests then |
| 156 | went on to write the run. The same decision twice answered 200 twice, |
| 157 | rewrote finished_at and appended a second "Resolved by" line; a refund |
| 158 | overlapping a charge found the charge's money already written, skipped |
| 159 | its own, and died on the transition guard (succeeded -> failed) as an |
| 160 | unhandled error. The run is claimed before anything is read now, so the |
| 161 | second decision is told it is in progress and writes nothing.""" |
| 162 | data_dir = setup_env(tmp_path, monkeypatch) |
| 163 | first, second = overlapping_decisions( |
| 164 | monkeypatch, |
| 165 | {"run_id": "r1", "decision": first_decision}, |
| 166 | {"run_id": "r1", "decision": second_decision}) |
| 167 | first, second = first or {"status": "crashed"}, second or {"status": "crashed"} |
| 168 | |
| 169 | answers = sorted([first.get("status"), second.get("status")], key=str) |
| 170 | assert answers == [200, 409], (first, second) |
| 171 | loser = first if first.get("status") == 409 else second |
| 172 | assert loser.get("code") == "in_progress", loser |
| 173 | |
| 174 | run = object_records.get_collection_record("template_runs", "r1", |
| 175 | base_dir=data_dir) |
| 176 | charged = "debit" in kinds(data_dir) |
| 177 | assert run["status"] == ("succeeded" if charged else "failed"), (run["status"], kinds(data_dir)) |
| 178 | assert run["error"].count("Resolved by") == 1 |
| 179 | assert run["action_claim"] == "" |
| 180 | |
| 181 | |
| 182 | def test_a_decision_on_a_run_somebody_is_deciding_writes_nothing(tmp_path, monkeypatch): |
| 183 | """A live claim means another request is settling this run right now.""" |
| 184 | import object_claims |
| 185 | data_dir = setup_env(tmp_path, monkeypatch) |
| 186 | object_claims.take("template_runs", "r1", base_dir=data_dir, actor="test") |
| 187 | result = resolve({"run_id": "r1", "decision": "charge"}) |
| 188 | assert result["status"] == 409 and result["code"] == "in_progress" |
| 189 | assert kinds(data_dir) == ["hold"] |
| 190 | run = object_records.get_collection_record("template_runs", "r1", base_dir=data_dir) |
| 191 | assert run["status"] == "needs_review" |
| 192 | |
| 193 | |
| 194 | def test_only_a_needs_review_run_can_be_resolved(tmp_path, monkeypatch): |
| 195 | """A terminal run is already settled; a running one may still be |
| 196 | answered, and polling beats a guess.""" |
| 197 | for status in ("running", "succeeded", "failed", "abandoned", "queued"): |
| 198 | data_dir = setup_env(tmp_path, monkeypatch, status=status) |
| 199 | result = resolve({"run_id": "r1", "decision": "charge"}) |
| 200 | assert result["status"] == 409, status |
| 201 | assert kinds(data_dir) == ["hold"], status |
| 202 | |
| 203 | |
| 204 | def test_a_bad_decision_is_refused_explaining_both(tmp_path, monkeypatch): |
| 205 | setup_env(tmp_path, monkeypatch) |
| 206 | result = resolve({"run_id": "r1", "decision": "maybe"}) |
| 207 | assert result["status"] == 400 |
| 208 | assert "charge" in result["error"] and "refund" in result["error"] |
| 209 | |
| 210 | |
| 211 | def test_a_stranger_cannot_decide_somebody_elses_money(tmp_path, monkeypatch): |
| 212 | data_dir = setup_env(tmp_path, monkeypatch) |
| 213 | result = resolve({"run_id": "r1", "decision": "charge"}, user_id="mallory") |
| 214 | assert result["status"] == 403 |
| 215 | assert kinds(data_dir) == ["hold"] |
| 216 | |
| 217 | |
| 218 | def test_an_admin_can_resolve_any_run(tmp_path, monkeypatch): |
| 219 | data_dir = setup_env(tmp_path, monkeypatch) |
| 220 | result = resolve({"run_id": "r1", "decision": "refund"}, |
| 221 | user_id="ops", is_admin=True) |
| 222 | assert result["ok"] |
| 223 | assert kinds(data_dir) == ["hold", "release"] |
| 224 | |
| 225 | |
| 226 | def test_anonymous_is_refused(tmp_path, monkeypatch): |
| 227 | setup_env(tmp_path, monkeypatch) |
| 228 | assert resolve({"run_id": "r1", "decision": "charge"}, |
| 229 | user_id="")["status"] == 401 |
| 230 | |
| 231 | |
| 232 | def test_an_unknown_run_is_a_404(tmp_path, monkeypatch): |
| 233 | setup_env(tmp_path, monkeypatch) |
| 234 | assert resolve({"run_id": "nope", "decision": "charge"})["status"] == 404 |
| 235 | |
| 236 | |
| 237 | def test_a_run_that_cannot_be_read_is_a_503_not_a_404(tmp_path, monkeypatch): |
| 238 | """Any error reading the run answered "There is no run": somebody |
| 239 | holding a parked run's money was told it did not exist. Unreadable is |
| 240 | an unknown -- 503, nothing written, and the same request goes through |
| 241 | once the run reads again.""" |
| 242 | data_dir = setup_env(tmp_path, monkeypatch) |
| 243 | real = object_records.get_collection_record |
| 244 | |
| 245 | def failing(collection, *args, **kwargs): |
| 246 | if collection == "template_runs": |
| 247 | raise OSError("simulated: template_runs unreadable") |
| 248 | return real(collection, *args, **kwargs) |
| 249 | |
| 250 | monkeypatch.setattr(object_records, "get_collection_record", failing) |
| 251 | refused = resolve({"run_id": "r1", "decision": "charge"}) |
| 252 | monkeypatch.setattr(object_records, "get_collection_record", real) |
| 253 | assert refused["status"] == 503, refused |
| 254 | assert "There is no run" not in refused["error"] |
| 255 | assert kinds(data_dir) == ["hold"] |
| 256 | assert resolve({"run_id": "r1", "decision": "charge"})["ok"] |
| 257 | |
| 258 | |
| 259 | def test_resolving_never_contacts_a_provider(tmp_path, monkeypatch): |
| 260 | """The standing refusal survives: a resolution verb settles MONEY |
| 261 | against a fate somebody established by other means. It is not a |
| 262 | retry, and must never become one.""" |
| 263 | source = (RUNNER_OBJECTS / "action" / "resolve_run.py").read_text() |
| 264 | assert "never re-runs anything" in source |
| 265 | for forbidden in ("HANDLERS", "send_http", "urlopen", "object_ai"): |
| 266 | assert forbidden not in source, forbidden |
| 267 | |
| 268 | |
| 269 | # --- the queue has to be visible ------------------------------------------------ |
| 270 | |
| 271 | def count_review(): |
| 272 | """The declared `runs_needing_review` count, as an admin sees it (the |
| 273 | whole queue) -- formerly system_review_attention's COUNT.""" |
| 274 | return shipped_count("app-runner", "runs_needing_review", |
| 275 | os.environ["DBBASIC_DATA_DIR"]) |
| 276 | |
| 277 | |
| 278 | def test_a_parked_run_shows_up_with_the_money_it_is_holding( |
| 279 | tmp_path, monkeypatch): |
| 280 | """A queue nobody can see is the same as no queue -- and this is the |
| 281 | one where doing nothing costs somebody money continuously, so the |
| 282 | detail leads with the amount held rather than the age.""" |
| 283 | setup_env(tmp_path, monkeypatch) |
| 284 | result = count_review() |
| 285 | assert result["count"] == 1 |
| 286 | assert "$6.00 held" in result["detail"] |
| 287 | |
| 288 | |
| 289 | def test_resolving_clears_it_from_the_queue(tmp_path, monkeypatch): |
| 290 | setup_env(tmp_path, monkeypatch) |
| 291 | resolve({"run_id": "r1", "decision": "refund"}) |
| 292 | assert count_review()["count"] == 0 |
| 293 | |
| 294 | |
| 295 | def test_only_needs_review_counts(tmp_path, monkeypatch): |
| 296 | for status in ("running", "succeeded", "failed", "abandoned", "queued"): |
| 297 | setup_env(tmp_path, monkeypatch, status=status) |
| 298 | assert count_review()["count"] == 0, status |
| 299 | |
| 300 | |
| 301 | def test_it_degrades_to_zero_without_the_collection(tmp_path, monkeypatch): |
| 302 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "empty")) |
| 303 | assert count_review() == {"count": 0, "detail": ""} |