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

9 downloads

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, 49 minutes ago History
run_sweeper.py · 9.2 KB · 207 lines
1"""system_run_sweeper -- give the money back when a runner dies, and
2never, ever run the job again.
3
4A claimed run whose heartbeat has stopped is a run in an UNKNOWN state.
5The pass that owned it may have died before calling the provider, or
6after calling and before recording -- and in the second case the provider
7may have completed the work and billed us. There is no way to know from
8here, because the non-idempotent step belongs to somebody else's system.
9
10So 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
19What it pointedly does NOT do is retry. Re-running a job that may already
20have been billed is paying twice for one thing. A retry is a NEW run,
21with a new hold, started by a person looking at the abandoned one --
22`provider_job_id`, recorded before the call where the provider supports
23it, is the thread that person pulls to ask "did they charge us".
24
25Staleness comes from `runner.stale_seconds` (default 900). Generous on
26purpose: this sweep is for processes that DIED, and a slow provider call
27is not a dead process. Sweeping a run that is merely slow abandons work
28the provider will finish and bill for -- so err long, and let genuinely
29long-running handlers push their own heartbeats when they arrive.
30"""
31
32import os
33from datetime import datetime, timezone
34
35import object_records
36import object_template_runs
37import object_wallet
38
39ACTOR = "system_run_sweeper"
40RUNS = "template_runs"
41
42STALE_SETTING = "runner.stale_seconds"
43MAX_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.
47DEFAULT_MAX_RUN_SECONDS = 3600
48DEFAULT_STALE_SECONDS = 900
49
50
51def _base_dir():
52 return os.environ.get("DBBASIC_DATA_DIR", "data")
53
54
55def _text(value):
56 return str(value if value is not None else "").strip()
57
58
59def _int(value, default=0):
60 try:
61 return int(_text(value) or default)
62 except (TypeError, ValueError):
63 return default
64
65
66def _now():
67 return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
68
69
70def _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
81def 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
207POST = EVENT