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.
run_sweeper.py · 9.2 KB · 207 lines
| 1 | """system_run_sweeper -- give the money back when a runner dies, and |
| 2 | never, ever run the job again. |
| 3 | |
| 4 | A claimed run whose heartbeat has stopped is a run in an UNKNOWN state. |
| 5 | The pass that owned it may have died before calling the provider, or |
| 6 | after calling and before recording -- and in the second case the provider |
| 7 | may have completed the work and billed us. There is no way to know from |
| 8 | here, because the non-idempotent step belongs to somebody else's system. |
| 9 | |
| 10 | So the sweep does the only two things that are safe in both worlds: |
| 11 | |
| 12 | * mark the run `abandoned` -- a terminal state with no exits, declared so |
| 13 | in the schema's transition map, so nothing can quietly re-queue it |
| 14 | * release the hold, in full, through the same idempotent settlement the |
| 15 | runner uses -- the user pays nothing for a job nobody can prove |
| 16 | happened, and the marker check means a runner that actually did settle |
| 17 | before dying is not paid back twice |
| 18 | |
| 19 | What it pointedly does NOT do is retry. Re-running a job that may already |
| 20 | have been billed is paying twice for one thing. A retry is a NEW run, |
| 21 | with a new hold, started by a person looking at the abandoned one -- |
| 22 | `provider_job_id`, recorded before the call where the provider supports |
| 23 | it, is the thread that person pulls to ask "did they charge us". |
| 24 | |
| 25 | Staleness comes from `runner.stale_seconds` (default 900). Generous on |
| 26 | purpose: this sweep is for processes that DIED, and a slow provider call |
| 27 | is not a dead process. Sweeping a run that is merely slow abandons work |
| 28 | the provider will finish and bill for -- so err long, and let genuinely |
| 29 | long-running handlers push their own heartbeats when they arrive. |
| 30 | """ |
| 31 | |
| 32 | import os |
| 33 | from datetime import datetime, timezone |
| 34 | |
| 35 | import object_records |
| 36 | import object_template_runs |
| 37 | import object_wallet |
| 38 | |
| 39 | ACTOR = "system_run_sweeper" |
| 40 | RUNS = "template_runs" |
| 41 | |
| 42 | STALE_SETTING = "runner.stale_seconds" |
| 43 | MAX_RUN_SETTING = "runner.max_run_seconds" |
| 44 | # Deliberately generous: this is not "how long should a job take" but |
| 45 | # "how long before a machine gives up deciding and asks a person". Sora |
| 46 | # budgets thirty minutes; an hour leaves room for a provider queue. |
| 47 | DEFAULT_MAX_RUN_SECONDS = 3600 |
| 48 | DEFAULT_STALE_SECONDS = 900 |
| 49 | |
| 50 | |
| 51 | def _base_dir(): |
| 52 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 53 | |
| 54 | |
| 55 | def _text(value): |
| 56 | return str(value if value is not None else "").strip() |
| 57 | |
| 58 | |
| 59 | def _int(value, default=0): |
| 60 | try: |
| 61 | return int(_text(value) or default) |
| 62 | except (TypeError, ValueError): |
| 63 | return default |
| 64 | |
| 65 | |
| 66 | def _now(): |
| 67 | return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 68 | |
| 69 | |
| 70 | def _setting(base, key, default): |
| 71 | try: |
| 72 | for row in object_records.read_collection_records("app_settings", |
| 73 | base_dir=base): |
| 74 | if _text(row.get("key")) == key: |
| 75 | return _text(row.get("value")) or default |
| 76 | except Exception: |
| 77 | pass |
| 78 | return default |
| 79 | |
| 80 | |
| 81 | def EVENT(request): |
| 82 | request = request or {} |
| 83 | base = _base_dir() |
| 84 | stale_seconds = max(60, _int(_setting(base, STALE_SETTING, |
| 85 | DEFAULT_STALE_SECONDS), |
| 86 | DEFAULT_STALE_SECONDS)) |
| 87 | now = _text(request.get("now")) or _now() |
| 88 | |
| 89 | try: |
| 90 | runs = object_records.read_collection_records(RUNS, base_dir=base) |
| 91 | except Exception: |
| 92 | return {"ok": True, "swept": 0, |
| 93 | "note": "No template_runs collection on this box."} |
| 94 | |
| 95 | # None, not [], when the ledger cannot be read: step 2 then pays back |
| 96 | # nothing this pass, rather than deciding from an empty ledger which |
| 97 | # runs are unsettled and which charges have nothing to answer for. |
| 98 | try: |
| 99 | entries = object_records.read_collection_records("wallet_entries", |
| 100 | base_dir=base) |
| 101 | except Exception: |
| 102 | entries = None |
| 103 | |
| 104 | max_run_seconds = max(stale_seconds, _int(_setting(base, MAX_RUN_SETTING, |
| 105 | DEFAULT_MAX_RUN_SECONDS), |
| 106 | DEFAULT_MAX_RUN_SECONDS)) |
| 107 | |
| 108 | swept, review = [], [] |
| 109 | # STEP 1 -- decide. Writing off a run is a COMPARE-AND-SET, because the |
| 110 | # sweeper races the runner it is sweeping: a runner that heartbeats or |
| 111 | # finishes between our staleness read and our write has changed the |
| 112 | # row, so our rev no longer matches and we correctly lose. Without the |
| 113 | # precondition this pass could write off a run that was completing and |
| 114 | # hand back money for work that succeeded. |
| 115 | # |
| 116 | # WHICH decision is object_template_runs.poll_disposition's, not this |
| 117 | # loop's, because the same rule has to bind the runner too. The rule |
| 118 | # that matters: a run carrying a provider_job_id is NEVER abandoned. |
| 119 | # Abandoning is what releases the hold, and a job the provider is |
| 120 | # already holding may already have cost everything -- handing the |
| 121 | # money back on a timer would be paying for it ourselves. Such a run |
| 122 | # is polled instead (the provider can simply be asked), and if polling |
| 123 | # never resolves it, it stops for a person. |
| 124 | for run in runs: |
| 125 | disposition = object_template_runs.poll_disposition( |
| 126 | run, now=now, stale_seconds=stale_seconds, |
| 127 | max_run_seconds=max_run_seconds) |
| 128 | if disposition not in ("abandon", "review"): |
| 129 | continue # "poll" belongs to the runner, not here |
| 130 | run_id = _text(run.get("id")) |
| 131 | if disposition == "abandon": |
| 132 | changes = { |
| 133 | "status": "abandoned", |
| 134 | "error": (f"Abandoned: no heartbeat for over {stale_seconds}s " |
| 135 | f"and nothing was submitted to a provider, so " |
| 136 | f"nothing was spent. The hold is released in full. " |
| 137 | f"NOT retried -- a retry is a new run, started by a " |
| 138 | f"person."), |
| 139 | "finished_at": now, |
| 140 | } |
| 141 | else: |
| 142 | changes = { |
| 143 | "status": object_template_runs.NEEDS_REVIEW_STATUS, |
| 144 | "error": (f"Submitted to the provider (job " |
| 145 | f"{_text(run.get('provider_job_id')) or 'unknown'}) " |
| 146 | f"and still unresolved after {max_run_seconds}s. " |
| 147 | f"The hold is deliberately NOT released: this job " |
| 148 | f"may already have been charged, so releasing would " |
| 149 | f"give away what we paid and charging would bill for " |
| 150 | f"work that may never have arrived. A person decides."), |
| 151 | } |
| 152 | try: |
| 153 | object_records.update_collection_record( |
| 154 | RUNS, run_id, changes, base_dir=base, actor=ACTOR, |
| 155 | expected_rev=object_records.compute_record_rev(run)) |
| 156 | except object_records.VersionConflictError: |
| 157 | # It moved while we were looking at it -- alive after all. |
| 158 | continue |
| 159 | (swept if disposition == "abandon" else review).append(run_id) |
| 160 | |
| 161 | # STEP 2 -- pay back, driven by STATE rather than by "did step 1 just |
| 162 | # run". Every terminal run whose hold has not been released gets it |
| 163 | # released, so a crash between the two steps is repaired by the next |
| 164 | # pass instead of leaving money reserved against a run that is over. |
| 165 | # Idempotent by the release marker, so this is a no-op for the runs |
| 166 | # the runner already settled itself. |
| 167 | # |
| 168 | # A run written off after its charge landed (settlement is debit |
| 169 | # first, and the worker died before the release and the status) also |
| 170 | # gets the charge reversed: its output was never recorded, so the |
| 171 | # customer has nothing to show for it (object_template_runs. |
| 172 | # charge_reversal). |
| 173 | released = [] |
| 174 | if entries is None: |
| 175 | return {"ok": True, "swept": len(swept), "runs": swept, |
| 176 | "needs_review": review, "holds_released": released, |
| 177 | "stale_seconds": stale_seconds, |
| 178 | "max_run_seconds": max_run_seconds, |
| 179 | "note": ("The wallet ledger could not be read, so no hold was " |
| 180 | "released this pass; the next pass will.")} |
| 181 | for run in object_records.read_collection_records(RUNS, base_dir=base): |
| 182 | if _text(run.get("status")) not in object_template_runs.TERMINAL_STATUSES: |
| 183 | continue |
| 184 | run_id = _text(run.get("id")) |
| 185 | if object_template_runs.already_settled(run_id, entries): |
| 186 | continue |
| 187 | entries_written = object_template_runs.settlement(run, succeeded=False) |
| 188 | if not entries_written: |
| 189 | continue # a free run: nothing was held |
| 190 | reversal = object_template_runs.charge_reversal(run, entries) |
| 191 | if reversal: |
| 192 | entries_written.append(reversal) |
| 193 | # Each entry once by its marker: a runner settling this same run at |
| 194 | # this moment, or an earlier pass that died part-way, has already |
| 195 | # written what it wrote, and the ledger's unique key says so. |
| 196 | object_wallet.write_each_once(entries_written, base_dir=base, |
| 197 | actor=ACTOR) |
| 198 | entries.extend(entries_written) # so a second hit this pass skips |
| 199 | released.append(run_id) |
| 200 | |
| 201 | return {"ok": True, "swept": len(swept), "runs": swept, |
| 202 | "needs_review": review, |
| 203 | "holds_released": released, "stale_seconds": stale_seconds, |
| 204 | "max_run_seconds": max_run_seconds} |
| 205 | |
| 206 | |
| 207 | POST = EVENT |