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
template_runner.py · 21.0 KB · 491 lines
1"""system_template_runner -- claim queued runs, execute them, settle the
2money. The engine; every handler is a plug in it.
3
4Runs every minute from the package schedule, and by hand from the same
5object, so the button and the pass cannot drift apart.
6
7## One engine, pluggable handlers
8
9The handler owns exactly one thing: turning a claimed run into an output
10or an error. Claiming, charging, settling, recording and reporting belong
11to the engine, and no handler gets opinions about them. "Screenshot Page"
12will be one handler of this engine, not a feature -- the uniform layer
13the predecessor hand-built four times.
14
15Slice 1 ships two: `echo` (the rendered body straight back -- free, no
16provider, and the handler that proves the money model without spending
17anything) and `ai_text` (the rendered body to a configured provider
18through object_ai, which already exists).
19
20## What a handler must never do
21
22**Silently degrade.** No "provider unavailable, here is a placeholder".
23A run that did not do the thing fails, releases its hold, and says why in
24words a person can act on -- which capability is missing and what to
25configure.
26
27## Settlement, and the crash it is designed around
28
29Settlement is release-in-full plus an ordinary debit on success, release
30alone on failure (object_template_runs.settlement). It is idempotent by
31provenance marker, checked against the WALLET ENTRIES rather than the
32run's status, because the crash worth designing for is exactly the one
33between writing money and updating status: replayed at the next pass, the
34marker is found and nothing posts twice (doctrine #7).
35
36Money is written FIRST, status second. If the pass dies between them the
37run re-settles as a no-op on the next pass and the status catches up. The
38other order would leave a run marked settled whose money never moved.
39
40The settlement writes are in-process and deliberately NOT gated: a
41release is money coming back (never gated anyway), and the debit is the
42recording of a spend that already happened at the provider. Refusing to
43record reality does not undo it.
44
45## What the engine will not do
46
47**Retry.** A run that fails is failed. A claimed run whose heartbeat
48stops is the sweeper's, becomes abandoned, and stays abandoned. The
49provider call is not idempotent and is not ours -- re-running a job that
50may already have been billed is paying twice for one thing, and a retry
51loop around a paid non-idempotent call is an unbounded spend wearing a
52robustness costume. A retry is a new run, with a new hold, started by a
53person who can see what happened.
54"""
55
56import json
57import os
58import urllib.error
59import urllib.request
60from datetime import datetime, timezone
61
62import object_ai
63import object_records
64import object_service_keys
65import object_template_runs
66import object_wallet
67
68ACTOR = "system_template_runner"
69RUNS = "template_runs"
70
71BATCH_SETTING = "runner.batch"
72TIMEOUT_SETTING = "runner.timeout_seconds"
73DEFAULT_BATCH = 3
74DEFAULT_TIMEOUT = 120
75
76
77def _base_dir():
78 return os.environ.get("DBBASIC_DATA_DIR", "data")
79
80
81def _text(value):
82 return str(value if value is not None else "").strip()
83
84
85def _int(value, default=0):
86 try:
87 return int(_text(value) or default)
88 except (TypeError, ValueError):
89 return default
90
91
92def _now():
93 return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
94
95
96def _setting(base, key, default):
97 try:
98 for row in object_records.read_collection_records("app_settings",
99 base_dir=base):
100 if _text(row.get("key")) == key:
101 return _text(row.get("value")) or default
102 except Exception:
103 pass
104 return default
105
106
107# === handlers ================================================================
108#
109# handler(run, base, timeout) -> {"ok", "output", "error",
110# "provider_cost_cents", "provider_job_id"}
111# The whole contract. A handler that needs more than this is trying to own
112# something the engine owns.
113#
114# ASYNC handlers are a PAIR in ASYNC_HANDLERS: (submit, poll).
115#
116# submit(run, base, timeout) -> {"provider_job_id", "error"}
117# poll(run, base, timeout) -> {"done": bool, ...the sync shape when done}
118#
119# The engine, not the handler, owns what that means: a submit that
120# returns a job id moves the run to `running` and RETURNS, leaving the
121# pass free; later passes poll. A Sora job takes minutes and q9 budgets
122# thirty, so executing it inline would block the batch and eventually
123# collide with the sweeper writing off a job that is legitimately still
124# running. Short handlers (echo, ai_text) stay inline -- the engine
125# supports both shapes and the handler declares which it is by which
126# registry it appears in.
127
128def _handle_echo(run, base, timeout):
129 """The rendered body straight back. Free, instant, and the handler
130 slice 1 exists for: it exercises queue, claim, settle and report with
131 no provider and no spend, which is how the money model gets proven
132 before a dollar rides on it."""
133 return {"ok": True, "output": _text(run.get("rendered_body")),
134 "error": "", "provider_cost_cents": 0, "provider_job_id": ""}
135
136
137def _handle_ai_text(run, base, timeout):
138 """The rendered body to the stamped model, through object_ai.
139
140 The model comes off the RUN, not the settings -- stamped at queue
141 time, so a model swap in settings changes the next run and never
142 restates what produced this one. The key is re-read now because keys
143 get deleted between queue and run; that failure is the rare race, and
144 it fails with the same words the queue-time check uses.
145 """
146 model = _text(run.get("model"))
147 if ":" not in model:
148 return {"ok": False, "output": "",
149 "error": "No model was stamped on this run; it should have "
150 "been refused at queue time.",
151 "provider_cost_cents": 0, "provider_job_id": ""}
152 service, model_name = object_ai.split_model(model)
153 key = object_service_keys.get_service_key(
154 _text(run.get("owner_id")), service, base_dir=base)
155 if not key:
156 return {"ok": False, "output": "",
157 "error": f"No {service} API key is stored for "
158 f"{_text(run.get('owner_id'))} -- it existed at queue "
159 f"time and is gone now. Store one and start a new "
160 f"run; this one was not charged.",
161 "provider_cost_cents": 0, "provider_job_id": ""}
162
163 def send_http(url, headers, body):
164 request = urllib.request.Request(url, data=body, headers=dict(headers),
165 method="POST")
166 try:
167 with urllib.request.urlopen(request, timeout=timeout) as response:
168 return response.status, response.read()
169 except urllib.error.HTTPError as exc:
170 return exc.code, exc.read()
171
172 def refuse_tool(name, arguments):
173 # No tools are offered, so this cannot be reached; refusing rather
174 # than passing silently keeps that a fact instead of an assumption.
175 return {"http_status": 400,
176 "response": {"error": "Template runs offer no tools."}}
177
178 try:
179 result = object_ai.run_chat(
180 send_http=send_http,
181 dispatch_tool=refuse_tool,
182 service=service,
183 model=model_name,
184 key=key,
185 message=_text(run.get("rendered_body")),
186 system=_text(run.get("instructions")) or None,
187 )
188 except object_ai.AIProviderError as exc:
189 return {"ok": False, "output": "",
190 "error": f"{service} refused the request: {str(exc)[:300]}",
191 "provider_cost_cents": 0, "provider_job_id": ""}
192 except Exception as exc:
193 return {"ok": False, "output": "",
194 "error": f"The provider call failed: {str(exc)[:300]}",
195 "provider_cost_cents": 0, "provider_job_id": ""}
196
197 usage = result.get("usage") or {}
198 cost = 0
199 try:
200 prices = object_records.read_collection_records("ai_prices",
201 base_dir=base)
202 row = object_ai.select_price_row(prices, provider=service,
203 model=model_name)
204 computed = object_ai.cost_cents_for_usage(usage, row)
205 cost = computed if computed is not None else 0
206 except Exception:
207 cost = 0 # no price table is expected, not an error
208
209 return {"ok": True, "output": _text(result.get("reply")),
210 "error": "", "provider_cost_cents": cost, "provider_job_id": ""}
211
212
213HANDLERS = {
214 "echo": _handle_echo,
215 "ai_text": _handle_ai_text,
216}
217
218#: name -> (submit, poll). Empty until a media handler lands; the engine
219#: below is what that handler will plug into, and it is tested with a
220#: stand-in so the money rule is proven before a provider rides on it.
221ASYNC_HANDLERS = {}
222
223
224# === the engine ==============================================================
225
226def _settle(base, run, *, succeeded):
227 """Write the run's settlement, exactly once, money before status.
228
229 Returns a note for the pass report. Reads the entries fresh and checks
230 the release marker -- never run.status -- because the crash this
231 protects is the one between money and status.
232 """
233 try:
234 entries = object_records.read_collection_records("wallet_entries",
235 base_dir=base)
236 except Exception:
237 entries = []
238 if object_template_runs.already_settled(run.get("id"), entries):
239 return "already settled"
240
241 # Debit first, claiming the balance (wallet_entries.spend_seq), then the
242 # release; each entry at most once by its marker, so a settlement that
243 # died part-way is finished here rather than doubled. Written
244 # release-first with no claim, a hold placed between the two spent the
245 # released money again and the debit took the wallet below zero.
246 object_wallet.write_each_once(
247 object_template_runs.settlement(run, succeeded=succeeded),
248 base_dir=base, actor=ACTOR)
249 return "settled"
250
251
252def _claim(base, run):
253 """Take exclusive ownership of a queued run, or return None if
254 somebody else got there first.
255
256 THE claim is a compare-and-set (63, plan/vocabulary/63-concurrency-spec.md),
257 not a plain write, and this is the difference between one provider
258 call and two. Without the precondition: two passes -- the minutely
259 schedule and an operator pressing Run Now -- both read the same row as
260 `queued`, both write `claimed` (the transition check is a no-op when
261 old == new), and both execute. Settlement is idempotent so the USER is
262 charged once, which is exactly what makes it dangerous: the duplicate
263 lands on OUR side of the ledger, as a second provider bill nothing in
264 the money model was watching.
265
266 `expected_rev` closes it inside the write lock: the second pass's rev
267 no longer matches the row the first pass just claimed, so it 409s and
268 never runs the handler. Same primitive, same idiom as
269 app-timers/objects/site/timer_actions.py, and the same one an agent
270 uses to claim a task.
271 """
272 return object_records.update_collection_record(
273 RUNS, _text(run.get("id")),
274 {"status": "claimed", "claimed_by": ACTOR,
275 "claimed_at": _now(), "heartbeat_at": _now()},
276 base_dir=base, actor=ACTOR,
277 expected_rev=object_records.compute_record_rev(run))
278
279
280def _submit_one(base, run, timeout, pair):
281 """Claim a run, hand it to the provider, and leave it `running`.
282
283 The pass ends here. Nothing is settled, because nothing has finished
284 -- and the hold placed at queue time stays exactly where it is, which
285 is the whole reason a hold exists rather than a charge on completion.
286 """
287 run_id = _text(run.get("id"))
288 submit, _poll = pair
289 try:
290 _claim(base, run)
291 except object_records.VersionConflictError:
292 return {"run_id": run_id, "handler": _text(run.get("handler")),
293 "status": "lost_claim", "settlement": "not ours", "error": ""}
294
295 try:
296 outcome = submit(run, base, timeout)
297 except Exception as exc:
298 outcome = {"provider_job_id": "",
299 "error": f"Submission crashed: {str(exc)[:300]}"}
300
301 job_id = _text(outcome.get("provider_job_id"))
302 if not job_id:
303 # Nothing reached the provider, so nothing was spent: this settles
304 # as an ordinary failure and the hold comes back in full.
305 settled = _settle(base, run, succeeded=False)
306 object_records.update_collection_record(
307 RUNS, run_id,
308 {"status": "failed",
309 "error": _text(outcome.get("error")) or "Submission returned no job id.",
310 "finished_at": _now(), "heartbeat_at": _now()},
311 base_dir=base, actor=ACTOR)
312 return {"run_id": run_id, "handler": _text(run.get("handler")),
313 "status": "failed", "settlement": settled,
314 "error": _text(outcome.get("error"))[:160]}
315
316 # THE ORDERING THAT MATTERS: the job id is written before anything
317 # else can happen to this run. Once a provider is holding the job,
318 # the id is the only evidence that money may have been spent, and
319 # poll_disposition reads it to refuse to abandon the run. A crash
320 # between the call and this write is the one case that loses the
321 # evidence, which is why submit returns the id rather than writing
322 # it -- the window is as small as it can be made.
323 object_records.update_collection_record(
324 RUNS, run_id,
325 {"status": object_template_runs.RUNNING_STATUS,
326 "provider_job_id": job_id, "heartbeat_at": _now()},
327 base_dir=base, actor=ACTOR)
328 return {"run_id": run_id, "handler": _text(run.get("handler")),
329 "status": "running", "settlement": "held", "error": "",
330 "provider_job_id": job_id}
331
332
333def _poll_one(base, run, timeout, pair):
334 """Ask the provider whether a running job is done.
335
336 Not done is not an error: it touches the heartbeat and returns, which
337 is what stops the sweeper writing off a job that is legitimately
338 still running. That heartbeat is the entire reason
339 runner.stale_seconds must exceed the POLL interval rather than the
340 job duration.
341 """
342 run_id = _text(run.get("id"))
343 _submit, poll = pair
344 try:
345 outcome = poll(run, base, timeout)
346 except Exception as exc:
347 # A failed poll is not a failed job. The provider still has it,
348 # so touch the heartbeat and try again next pass; only
349 # max_run_seconds ends this loop, and it ends it at a human.
350 object_records.update_collection_record(
351 RUNS, run_id, {"heartbeat_at": _now()}, base_dir=base, actor=ACTOR)
352 return {"run_id": run_id, "handler": _text(run.get("handler")),
353 "status": "running", "settlement": "held",
354 "error": f"Poll failed, still running: {str(exc)[:160]}"}
355
356 if not outcome.get("done"):
357 object_records.update_collection_record(
358 RUNS, run_id, {"heartbeat_at": _now()}, base_dir=base, actor=ACTOR)
359 return {"run_id": run_id, "handler": _text(run.get("handler")),
360 "status": "running", "settlement": "held", "error": ""}
361
362 settled = _settle(base, run, succeeded=bool(outcome.get("ok")))
363 final = "succeeded" if outcome.get("ok") else "failed"
364 object_records.update_collection_record(
365 RUNS, run_id,
366 {"status": final,
367 "output": _text(outcome.get("output"))[:20000],
368 "error": _text(outcome.get("error"))[:2000],
369 "provider_cost_cents": str(_int(outcome.get("provider_cost_cents"))),
370 "finished_at": _now(), "heartbeat_at": _now()},
371 base_dir=base, actor=ACTOR)
372 return {"run_id": run_id, "handler": _text(run.get("handler")),
373 "status": final, "settlement": settled,
374 "error": _text(outcome.get("error"))[:160]}
375
376
377def _execute_one(base, run, timeout):
378 run_id = _text(run.get("id"))
379
380 try:
381 _claim(base, run)
382 except object_records.VersionConflictError:
383 # Another pass claimed it between our read and our write. Not an
384 # error and not worth a retry: the run is somebody else's now, and
385 # the whole point is that we did NOT call the provider.
386 return {"run_id": run_id, "handler": _text(run.get("handler")),
387 "status": "lost_claim", "settlement": "not ours",
388 "error": ""}
389
390 handler = HANDLERS.get(_text(run.get("handler")))
391 if handler is None:
392 outcome = {"ok": False, "output": "",
393 "error": f"No handler named {_text(run.get('handler'))!r} "
394 f"is installed on this server.",
395 "provider_cost_cents": 0, "provider_job_id": ""}
396 else:
397 try:
398 outcome = handler(run, base, timeout)
399 except Exception as exc:
400 outcome = {"ok": False, "output": "",
401 "error": f"The handler crashed: {str(exc)[:300]}",
402 "provider_cost_cents": 0, "provider_job_id": ""}
403
404 settled = _settle(base, run, succeeded=bool(outcome["ok"]))
405
406 final = "succeeded" if outcome["ok"] else "failed"
407 try:
408 object_records.update_collection_record(
409 RUNS, run_id,
410 {"status": final,
411 "output": _text(outcome.get("output"))[:20000],
412 "error": _text(outcome.get("error"))[:2000],
413 "provider_cost_cents": str(_int(outcome.get("provider_cost_cents"))),
414 "provider_job_id": _text(outcome.get("provider_job_id")),
415 "finished_at": _now(), "heartbeat_at": _now()},
416 base_dir=base, actor=ACTOR)
417 except Exception as exc:
418 # The one way this write legitimately fails: the sweeper decided
419 # our heartbeat had stopped and marked the run `abandoned`, which
420 # the transition map declares terminal -- so there is no move from
421 # it to `succeeded`, by design. The work IS done and the money is
422 # already right (the sweeper released the hold; `_settle` found
423 # that marker and charged nothing), so this must not crash the
424 # pass and take the rest of the batch with it. Report it: a run
425 # that completed after being written off is a signal that
426 # runner.stale_seconds is too short for this handler.
427 return {"run_id": run_id, "handler": _text(run.get("handler")),
428 "status": "finished_after_sweep", "settlement": settled,
429 "error": (f"Completed, but the run had already been swept as "
430 f"abandoned, so its result could not be recorded "
431 f"({str(exc)[:120]}). Raise runner.stale_seconds.")}
432
433 return {"run_id": run_id, "handler": _text(run.get("handler")),
434 "status": final, "settlement": settled,
435 "error": _text(outcome.get("error"))[:160]}
436
437
438def EVENT(request):
439 """The daemon entry point. EVENT with POST aliased, because the change
440 dispatcher calls EVENT while the scheduler calls the task's `method`
441 (POST unless the schedule names another), so an object that is both a
442 handler and a scheduled pass needs both names -- declaring only one is
443 a pass that silently never runs, a real production bug here, twice."""
444 request = request or {}
445 base = _base_dir()
446
447 batch = max(1, _int(_setting(base, BATCH_SETTING, DEFAULT_BATCH),
448 DEFAULT_BATCH))
449 timeout = max(5, _int(_setting(base, TIMEOUT_SETTING, DEFAULT_TIMEOUT),
450 DEFAULT_TIMEOUT))
451
452 try:
453 runs = object_records.read_collection_records(RUNS, base_dir=base)
454 except Exception:
455 return {"ok": True, "claimed": 0,
456 "note": "No template_runs collection on this box."}
457
458 queued = sorted((row for row in runs
459 if _text(row.get("status")) == "queued"),
460 key=lambda row: _text(row.get("created_at")))
461
462 results = []
463 for run in queued[:batch]:
464 pair = ASYNC_HANDLERS.get(_text(run.get("handler")))
465 results.append(_submit_one(base, run, timeout, pair) if pair
466 else _execute_one(base, run, timeout))
467
468 # Then poll everything already at the provider. These are NOT new
469 # claims -- the run is already ours -- so they are reported
470 # separately and never counted as work this pass started.
471 polled = []
472 for run in runs:
473 if _text(run.get("status")) != object_template_runs.RUNNING_STATUS:
474 continue
475 pair = ASYNC_HANDLERS.get(_text(run.get("handler")))
476 if pair is None:
477 continue # handler uninstalled; the sweeper will escalate
478 polled.append(_poll_one(base, run, timeout, pair))
479 # `claimed` counts runs this pass actually OWNED and executed. A lost
480 # claim is another pass's run, and counting it here would report two
481 # passes as having done the same work -- the exact confusion the
482 # compare-and-set exists to make impossible.
483 executed = [r for r in results if r["status"] != "lost_claim"]
484 lost = len(results) - len(executed)
485 return {"ok": True, "claimed": len(executed), "lost_claims": lost,
486 "queued_remaining": max(0, len(queued) - len(results)),
487 "polled": len(polled), "poll_results": polled,
488 "results": results}
489
490
491POST = EVENT