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/object_template_runs.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, 8 minutes ago History
object_template_runs.py · 16.8 KB · 407 lines
1"""object_template_runs -- the arithmetic of running a template.
2
3Pure. No I/O, no clock, no data directory. The same posture as
4object_rates, object_cart and object_promotions: the package objects in
5packages/app-runner do the reading and writing, and everything here is
6testable without either.
7
8## What a run IS
9
10A run is a COMMITMENT the moment it is queued: money is placed on hold
11against it, a provider may be paid real cash to execute it, and the terms
12it runs under are stamped onto its own row so that editing the template
13tomorrow restates nothing that already happened
14(docs/logic-decisions.md #1). A template is edited constantly -- that is
15what makes it a template -- so the run must carry its own copy of the
16handler, the body, the price and the model that were in force when the
17user pressed the button. A user reading last month's run history is
18reading what last month actually cost, not what this month's prices would
19have made it cost.
20
21## The money model: hold, release, charge
22
23Three wallet movements, and the naming is the design:
24
25* **hold** (negative) -- placed at queue time for the stamped price. Goes
26 through the wallet gate, which is the point: the moment the gate is
27 asked is the moment money is committed, so a user with 5 cents cannot
28 queue four hundred runs and present the provider bill later.
29* **release** (positive) -- the hold handed back at settlement, always in
30 full, always paired to its hold by provenance marker.
31* **charge** -- an ordinary `debit` for what the run actually cost the
32 user. Deliberately NOT a new kind: every report that already reads
33 debits keeps working, and a released hold never masquerades as a
34 refund. A hold is not a debit that got undone; it is money that was
35 never spent, and the ledger should read that way.
36
37A successful run settles as debit + release (sum: the price). A failed
38run settles as release alone (sum: zero). The debit comes FIRST: written
39release-first, the hold's money was back on the balance for the length of
40one write, a hold placed in that window spent it again, and the debit then
41took the wallet below zero. Debit-first, the balance only ever
42under-states what is free; a settlement that dies between the two leaves
43the wallet short by one hold, visibly, and the next settler (the sweeper,
44or a retry) writes the release and skips the debit it finds by marker.
45Writers write these through object_wallet.write_each_once, which claims
46the balance on the debit (wallet_entries.spend_seq). Nothing is ever mutated and the
47balance stays derived, so every state -- reserved, spent, given back --
48is reconstructible from the entries alone.
49
50## Provenance markers
51
52Each movement carries a `generated_from` marker naming the run and the
53leg (`template_run/<id>/hold`, `/release`, `/charge`). Settlement checks
54for the release marker before writing, which is what makes it idempotent:
55the runner and the sweeper can both try to settle the same run and the
56second one finds the marker and writes nothing (doctrine #7). The failure
57this prevents is not theoretical -- it is a crash between "settled" and
58"status updated", replayed at the next pass, giving the money back twice.
59"""
60
61import json
62import re
63
64# The one non-negotiable ordering rule, written down where both the
65# runner and the sweeper import it: a stale run is never re-queued.
66# Retrying a paid, non-idempotent provider call automatically is the sort
67# of feature that looks like robustness and is actually an unbounded
68# spend. A retry is a NEW run, with a new hold, started by a person.
69TERMINAL_STATUSES = ("succeeded", "failed", "abandoned")
70
71# `running` sits between claimed and terminal: the provider has the job,
72# we have a provider_job_id, and no pass is executing anything. It is
73# owned but idle, which is why it needs its own status rather than
74# stretching `claimed` to cover it.
75RUNNING_STATUS = "running"
76
77# The one state a machine must not resolve. A submitted job whose outcome
78# we never learned is money that MAY already be spent at the provider:
79# releasing the hold gives away what we paid, and charging bills a
80# customer for something they may never have received. Both are wrong and
81# the box genuinely cannot tell which, so it stops and asks. Deliberately
82# NOT in TERMINAL_STATUSES -- that tuple is what drives the sweeper's
83# automatic hold release, and the whole point is that this one is not
84# released automatically.
85NEEDS_REVIEW_STATUS = "needs_review"
86
87HOLD_MARKER = "template_run/{run_id}/hold"
88RELEASE_MARKER = "template_run/{run_id}/release"
89CHARGE_MARKER = "template_run/{run_id}/charge"
90
91_PLACEHOLDER = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}")
92
93
94def _text(value):
95 return str(value if value is not None else "").strip()
96
97
98def _int(value, default=0):
99 try:
100 return int(_text(value) or default)
101 except (TypeError, ValueError):
102 return default
103
104
105# --- the form ----------------------------------------------------------------
106
107def form_fields(template):
108 """The template's declared form, as a list of {name, required, ...}.
109
110 templates.schema is a JSON Schema string (stored as text because the
111 field-type contract has no json type). Only the parts a runner needs
112 are read: property names and the required list. A template with no
113 schema has no form and accepts anything, which is the right default
114 for a body with no placeholders.
115 """
116 raw = _text(template.get("schema"))
117 if not raw:
118 return []
119 try:
120 parsed = json.loads(raw)
121 except ValueError:
122 return []
123 properties = parsed.get("properties")
124 if not isinstance(properties, dict):
125 return []
126 required = set(parsed.get("required") or [])
127 return [{"name": name, "required": name in required,
128 "title": _text((spec or {}).get("title")) or name}
129 for name, spec in properties.items()]
130
131
132def problems(template, form_data):
133 """Every reason this submission cannot run, at once.
134
135 A list rather than a first failure -- a form that reveals one problem
136 per attempt is a form people abandon, which is the same argument
137 object_promotions.blockers makes about checkouts.
138 """
139 found = []
140 handler = _text(template.get("handler"))
141 if not handler:
142 found.append(
143 f"The template '{_text(template.get('name')) or '?'}' declares no "
144 f"handler, so there is nothing to run it with. Set `handler` on "
145 f"the template (e.g. 'echo' or 'ai_text').")
146
147 form_data = form_data if isinstance(form_data, dict) else {}
148 for field in form_fields(template):
149 if field["required"] and not _text(form_data.get(field["name"])):
150 found.append(f"'{field['title']}' is required and was not provided.")
151
152 price = _int(template.get("run_cost_cents"))
153 if price < 0:
154 found.append("run_cost_cents is negative; a template cannot pay "
155 "people to run it.")
156 return found
157
158
159def render(body, form_data):
160 """The template body with {name} placeholders filled from the form.
161
162 Unknown placeholders stay as written rather than erroring or blanking:
163 a brace in prose ("{TBD}") must not kill a run, and a silently emptied
164 placeholder is a prompt that quietly lost its subject -- the worst
165 outcome, because the provider answers SOMETHING and charges for it.
166 """
167 form_data = form_data if isinstance(form_data, dict) else {}
168
169 def fill(match):
170 key = match.group(1)
171 if key in form_data:
172 return str(form_data[key])
173 return match.group(0)
174
175 return _PLACEHOLDER.sub(fill, str(body or ""))
176
177
178# --- stamping ------------------------------------------------------------------
179
180def stamp(template, form_data, *, model=""):
181 """The terms of this run, copied at queue time.
182
183 Everything execution or a later reader needs, taken from the template
184 NOW, so the run is immune to every future edit of the template. The
185 rendered body is stamped rather than re-rendered later for the same
186 reason: rendering reads the template, and by execution time the
187 template may say something else.
188 """
189 return {
190 "template_id": _text(template.get("id")),
191 "template_name": _text(template.get("name")),
192 "handler": _text(template.get("handler")),
193 "model": _text(model),
194 "form_data": json.dumps(form_data if isinstance(form_data, dict) else {},
195 sort_keys=True),
196 "rendered_body": render(template.get("body"), form_data),
197 "instructions": _text(template.get("instructions")),
198 "price_cents": str(max(0, _int(template.get("run_cost_cents")))),
199 }
200
201
202# --- settlement ----------------------------------------------------------------
203
204def settlement(run, *, succeeded):
205 """The wallet movements that close this run. Pure: returns a list of
206 entries for the caller to write, after checking the release marker.
207
208 Success: an ordinary debit for the stamped price, then the hold
209 released in full -- in that order, written in that order (see "The
210 money model" above). Failure: release alone -- the user pays nothing
211 for a run that did not do the thing, whatever it cost US at the
212 provider (our cost is recorded on the run for margin, not billed to
213 them).
214
215 A free run (price 0) had no hold and settles to no entries at all.
216 """
217 run_id = _text(run.get("id"))
218 price = _int(run.get("price_cents"))
219 wallet_id = _text(run.get("wallet_id"))
220 if price <= 0 or not wallet_id:
221 return []
222
223 release = {
224 "wallet_id": wallet_id,
225 "amount_minor": str(price),
226 "kind": "release",
227 "description": f"Hold released: run {run_id}",
228 "reference": f"template_runs/{run_id}",
229 "generated_from": RELEASE_MARKER.format(run_id=run_id),
230 "owner_id": _text(run.get("owner_id")),
231 }
232 entries = []
233 if succeeded:
234 entries.append({
235 "wallet_id": wallet_id,
236 "amount_minor": str(-price),
237 "kind": "debit",
238 "description": (f"Template run: "
239 f"{_text(run.get('template_name')) or run_id}"),
240 "reference": f"template_runs/{run_id}",
241 "generated_from": CHARGE_MARKER.format(run_id=run_id),
242 "owner_id": _text(run.get("owner_id")),
243 })
244 entries.append(release)
245 return entries
246
247
248def charge_reversal(run, wallet_entries):
249 """The compensating credit for a charge whose run did not end
250 `succeeded`, or None.
251
252 Debit-first settlement has one crash of its own: the charge is written,
253 the worker dies before the release and before the run's status, and the
254 sweeper later writes the run off as abandoned -- a run whose output was
255 never recorded, so the customer has nothing to show for the charge.
256 The sweeper releases the hold as for any abandoned run, and this undoes
257 the charge with an entry that says so (doctrine #3: money moves, it is
258 never edited). A run that did end `succeeded` keeps its charge.
259 """
260 run_id = _text(run.get("id"))
261 if _text(run.get("status")) == "succeeded" or not run_id:
262 return None
263 marker = CHARGE_MARKER.format(run_id=run_id)
264 charged = [row for row in wallet_entries or ()
265 if _text(row.get("generated_from")) == marker]
266 if not charged:
267 return None
268 return {
269 "wallet_id": _text(charged[0].get("wallet_id")),
270 "amount_minor": str(-sum(_int(row.get("amount_minor")) for row in charged)),
271 "kind": "adjustment",
272 "description": (f"Charge reversed: run {run_id} ended "
273 f"{_text(run.get('status')) or 'unfinished'} after it was "
274 f"charged, so its output was never recorded"),
275 "reference": f"template_runs/{run_id}",
276 "generated_from": f"template_run/{run_id}/charge_reversal",
277 "owner_id": _text(charged[0].get("owner_id")) or _text(run.get("owner_id")),
278 }
279
280
281def hold_entry(run_id, wallet_id, price_cents, owner_id, template_name=""):
282 """The hold placed at queue time. Negative, so the wallet gate fires
283 on it -- which is the entire reason a hold exists: the gate is asked
284 at the moment of commitment, not at the moment of spending."""
285 price = max(0, _int(price_cents))
286 if price == 0:
287 return None
288 return {
289 "wallet_id": _text(wallet_id),
290 "amount_minor": str(-price),
291 "kind": "hold",
292 "description": f"Hold: template run {_text(template_name) or run_id}",
293 "reference": f"template_runs/{run_id}",
294 "generated_from": HOLD_MARKER.format(run_id=run_id),
295 "owner_id": _text(owner_id),
296 }
297
298
299def already_settled(run_id, wallet_entries):
300 """Has this run's hold already been released?
301
302 THE idempotency check. The runner settling a run it just executed and
303 the sweeper settling a run whose worker died can both reach here; the
304 marker means at most one of them writes. Checked against the entries
305 themselves, never against run.status, because the crash this guards
306 is precisely the one between writing money and updating status.
307 """
308 marker = RELEASE_MARKER.format(run_id=_text(run_id))
309 return any(_text(row.get("generated_from")) == marker
310 for row in wallet_entries or ())
311
312
313def outstanding_holds(wallet_entries):
314 """Sum of holds not yet released, by run id -- what is reserved right
315 now. A fold over the entries, like every other balance here."""
316 held = {}
317 for row in wallet_entries or ():
318 marker = _text(row.get("generated_from"))
319 if marker.startswith("template_run/"):
320 parts = marker.split("/")
321 if len(parts) == 3 and parts[2] in ("hold", "release"):
322 run_id = parts[1]
323 held[run_id] = held.get(run_id, 0) + _int(row.get("amount_minor"))
324 return {run_id: -total for run_id, total in held.items() if total != 0}
325
326
327def poll_disposition(run, *, now, stale_seconds, max_run_seconds):
328 """What should be done with this run right now? Pure; no clock.
329
330 The money rule for asynchronous jobs lives here, in one place, so the
331 sweeper and the runner cannot disagree about it:
332
333 - **claimed, heartbeat stopped, no provider_job_id** -> "abandon".
334 Nothing was submitted, so nothing was spent, and the hold is
335 released in full. This is the original sweeper behaviour and it
336 stays exactly right for the case it was written for.
337
338 - **running (or claimed WITH a provider_job_id), heartbeat stopped**
339 -> "poll". NOT abandoned. The provider is holding the job and can
340 simply be asked, so a dead worker is not a lost job -- and crucially
341 the hold is NOT released, because a submitted job may already have
342 cost everything. This is the case the original sweeper got actively
343 wrong for media.
344
345 - **running past max_run_seconds** -> "review". Polling has not
346 resolved it for longer than any job should take, so it stops being
347 a machine's decision. The hold stays put.
348
349 - anything else -> None, leave it alone.
350
351 A claimed run that carries a provider_job_id is treated as running
352 even if the status write never landed: the id is the evidence that a
353 call was made, and evidence outranks a status field that a crash may
354 have prevented.
355 """
356 status = _text(run.get("status"))
357 if status in TERMINAL_STATUSES or status == NEEDS_REVIEW_STATUS:
358 return None
359
360 submitted = bool(_text(run.get("provider_job_id")))
361 beat = _text(run.get("heartbeat_at")) or _text(run.get("claimed_at"))
362
363 if status == RUNNING_STATUS or (status == "claimed" and submitted):
364 started = _text(run.get("claimed_at")) or beat
365 if started:
366 deadline = _shift_iso(started, abs(int(max_run_seconds)))
367 if _text(now) > deadline:
368 return "review"
369 return "poll"
370
371 if status == "claimed":
372 if not beat:
373 return "abandon"
374 if beat < _shift_iso(_text(now), -abs(int(stale_seconds))):
375 return "abandon"
376 return None
377
378
379def is_stale(run, *, now, stale_seconds):
380 """Has this claimed run's heartbeat stopped?
381
382 String comparison on ISO-8601 timestamps, which sort lexicographically
383 -- the same convention the rest of the codebase leans on. `now` is a
384 parameter, never read from a clock here, so the sweeper's tests do not
385 need to sleep.
386 """
387 if _text(run.get("status")) not in ("claimed",):
388 return False
389 beat = _text(run.get("heartbeat_at")) or _text(run.get("claimed_at"))
390 if not beat:
391 return True
392 cutoff = _shift_iso(_text(now), -abs(int(stale_seconds)))
393 return beat < cutoff
394
395
396def _shift_iso(stamp, seconds):
397 """An ISO timestamp moved by N seconds, staying pure (no clock)."""
398 from datetime import datetime, timedelta
399
400 text = stamp.rstrip("Z")
401 try:
402 parsed = datetime.fromisoformat(text)
403 except ValueError:
404 return stamp
405 shifted = parsed + timedelta(seconds=seconds)
406 out = shifted.isoformat()
407 return out + "Z" if stamp.endswith("Z") else out