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_template.py · 15.5 KB · 354 lines
| 1 | """action_run_template -- press Run on a template: validate, hold the |
| 2 | money, queue the job. |
| 3 | |
| 4 | POST {template_id, form_data?} |
| 5 | |
| 6 | This object QUEUES and never executes. A verb that both queued and ran |
| 7 | would make the queue a fiction under load, and -- worse -- would put a |
| 8 | paid provider call inside a web request, where a timeout looks to the |
| 9 | user like failure while the provider bills us anyway. Execution belongs |
| 10 | to system_template_runner, on the daemon, where a crash has a sweeper. |
| 11 | |
| 12 | ## The gate is asked at the moment of commitment |
| 13 | |
| 14 | The stamped price goes on the wallet as a HOLD, here, before anything is |
| 15 | queued -- through hook_wallet_entries, asked in process, exactly the way |
| 16 | action_checkout asks it for gift cards. The gate summing the real entries |
| 17 | at THIS moment is what makes "insufficient balance" mean something: a |
| 18 | user with five cents cannot queue four hundred runs and present the |
| 19 | provider bill later, because the four-hundredth hold fails the gate. |
| 20 | |
| 21 | Free templates (price 0) touch no wallet at all: no hold, no wallet_id on |
| 22 | the run, nothing to settle. Money machinery that runs for free jobs is |
| 23 | machinery that fails for free jobs. |
| 24 | |
| 25 | ## Capability boundaries are refused HERE, not discovered at 3am |
| 26 | |
| 27 | An ai handler needs a model (`runner.ai_model` in app_settings) and a |
| 28 | stored provider key for whoever is running it. Both are checked at queue |
| 29 | time and refused with a 409 naming exactly what to configure -- the house |
| 30 | posture: absent by default, never a stub that pretends to work. Refusing |
| 31 | here beats queueing a run that the daemon fails an hour later, because |
| 32 | the person who can fix the configuration is the one looking at the screen |
| 33 | right now. (The runner re-checks at execution -- a key can be deleted |
| 34 | between queue and run -- but that failure is the rare race, not the |
| 35 | normal path.) |
| 36 | |
| 37 | ## One execution model, not two (task_id) |
| 38 | |
| 39 | q9 (askrobots) has a SEPARATE model, `tasks.Work`, for "a template was run |
| 40 | in service of this task": task + template + worker + status + result, its |
| 41 | own row, its own history. This runner does not get a second one. `task_id` |
| 42 | on template_runs is the only piece Work had that this runner did not: |
| 43 | everything else Work would have needed -- a status machine, an idempotent |
| 44 | settlement, staleness detection, async submit/poll, an escalation path for |
| 45 | a run stuck between "submitted" and "resolved" -- template_runs already |
| 46 | has, built and proven under real money before this field existed. Work |
| 47 | had none of that; its billing lived in a THIRD, disconnected model |
| 48 | (`integrations.APILog`) that had to be kept in sync by hand. Here it is |
| 49 | the same row. |
| 50 | |
| 51 | Multiple attempts against one task are just multiple runs sharing a |
| 52 | task_id -- the append-only doctrine applies exactly as it does everywhere |
| 53 | else in this codebase: "how many times has this been attempted" is a |
| 54 | fold over rows, not a stored counter. The task's detail page renders that |
| 55 | fold with the same `related` block every other one-to-many relationship |
| 56 | in this system uses (order -> order_lines, invoice -> invoice_lines); |
| 57 | nothing new was built to show it. |
| 58 | |
| 59 | Deliberately absent: nothing here mutates task.status when a run |
| 60 | succeeds. A Design Review producing a report is not the same claim as |
| 61 | "this task is finished" -- that is a human's call, or an agent's, |
| 62 | looking at the run's own output, exactly the same "the server notices, |
| 63 | the person decides" posture system_reorder_check takes with its |
| 64 | suggestions. Automatic status transitions are a door left open, not one |
| 65 | walked through here. |
| 66 | |
| 67 | ## Ordering, and the crash between the two writes |
| 68 | |
| 69 | The hold is written BEFORE the run row. If the crash lands between them, |
| 70 | the result is a hold with no run -- money reserved for nothing, visible, |
| 71 | annoying, releasable. The other order would leave a QUEUED RUN WITH NO |
| 72 | HOLD: a job the runner would happily execute for free, invisibly. When a |
| 73 | crash must leave one of two wrongs, leave the one that fails safe and |
| 74 | shows up. (The window is one create call wide; on a run-create failure |
| 75 | this object immediately writes the release itself, so the orphan hold |
| 76 | survives only a crash, not an error.) |
| 77 | """ |
| 78 | |
| 79 | import json |
| 80 | import os |
| 81 | from datetime import datetime, timezone |
| 82 | |
| 83 | import object_execution |
| 84 | import object_ids |
| 85 | import object_access |
| 86 | import object_records |
| 87 | import object_service_keys |
| 88 | import object_template_runs |
| 89 | import object_wallet |
| 90 | import python_object_runtime |
| 91 | |
| 92 | ACTOR = "action_run_template" |
| 93 | RUNS = "template_runs" |
| 94 | MODEL_SETTING = "runner.ai_model" |
| 95 | |
| 96 | AI_HANDLERS = ("ai_text",) |
| 97 | KNOWN_HANDLERS = ("echo", "ai_text") |
| 98 | |
| 99 | |
| 100 | def _base_dir(): |
| 101 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 102 | |
| 103 | |
| 104 | def _text(value): |
| 105 | return str(value if value is not None else "").strip() |
| 106 | |
| 107 | |
| 108 | def _now(): |
| 109 | return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 110 | |
| 111 | |
| 112 | def _setting(base, key): |
| 113 | try: |
| 114 | # access: box configuration |
| 115 | for row in object_records.read_collection_records("app_settings", |
| 116 | base_dir=base): |
| 117 | if _text(row.get("key")) == key: |
| 118 | return _text(row.get("value")) |
| 119 | except Exception: |
| 120 | pass |
| 121 | return "" |
| 122 | |
| 123 | |
| 124 | def _call(object_id, payload, *, method="POST"): |
| 125 | """Run another installed object in process -- the pattern |
| 126 | action_checkout uses to ask hook_wallet_entries.""" |
| 127 | try: |
| 128 | runtime = python_object_runtime.PythonObjectRuntime() |
| 129 | outcome = object_execution.execute_object( |
| 130 | runtime, |
| 131 | object_execution.ObjectExecutionRequest( |
| 132 | object_id, method=method, payload=payload)) |
| 133 | except Exception as exc: |
| 134 | return None, str(exc)[:200] |
| 135 | if not outcome.ok: |
| 136 | message = getattr(outcome.error, "message", "") if outcome.error else "" |
| 137 | return None, (_text(message)[:200] or f"{object_id} failed") |
| 138 | return outcome.result, "" |
| 139 | |
| 140 | |
| 141 | def _wallet_for(base, owner_id): |
| 142 | """The owner's spending wallet: active, kind balance (or legacy blank). |
| 143 | |
| 144 | Gift cards and store credit are deliberately not reached from here in |
| 145 | slice 1 -- a template run is metered usage, and mixing tender kinds |
| 146 | into the hold path is a decision for the checkout that already makes |
| 147 | it, not a default. |
| 148 | """ |
| 149 | try: |
| 150 | # access: the caller's own wallet: owner_id == the caller's user_id |
| 151 | rows = object_records.read_collection_records("wallets", base_dir=base) |
| 152 | except Exception: |
| 153 | return None |
| 154 | candidates = [row for row in rows |
| 155 | if _text(row.get("owner_id")) == owner_id |
| 156 | and _text(row.get("kind")) in ("", "balance") |
| 157 | and _text(row.get("is_active")).lower() != "false"] |
| 158 | candidates.sort(key=lambda row: _text(row.get("created_at"))) |
| 159 | return candidates[0] if candidates else None |
| 160 | |
| 161 | |
| 162 | def POST(request): |
| 163 | request = request or {} |
| 164 | base = _base_dir() |
| 165 | |
| 166 | identity = request.get("_identity") or {} |
| 167 | user_id = _text(identity.get("user_id")) |
| 168 | if not user_id: |
| 169 | return {"status": 401, |
| 170 | "error": "Running a template requires an account: runs are " |
| 171 | "held against a wallet, and an anonymous run would " |
| 172 | "be an open tap."} |
| 173 | |
| 174 | # Every read below is a trusted read, so this object is the gate for |
| 175 | # both records it touches, and it asks the permission engine the |
| 176 | # question the API would (object_access). It used to run anybody's |
| 177 | # PRIVATE template -- stamping its body and instructions onto a run the |
| 178 | # caller could then read -- and to answer 404 for a missing id but |
| 179 | # 200/403 for somebody else's, an existence oracle for template and |
| 180 | # task ids (bug-reports/2026-11-28-06-14-31). A record the caller may |
| 181 | # not read is now the same 404 as one that does not exist. |
| 182 | access = object_access.Access(identity, base_dir=base) |
| 183 | |
| 184 | template_id = _text(request.get("template_id")) |
| 185 | if not template_id: |
| 186 | return {"status": 400, "error": "template_id is required."} |
| 187 | try: |
| 188 | template = access.get("templates", template_id) |
| 189 | except Exception: |
| 190 | template = None |
| 191 | if template is None: |
| 192 | return {"status": 404, |
| 193 | "error": f"There is no template {template_id!r} on this server."} |
| 194 | |
| 195 | # --- the optional task link ----------------------------------------------- |
| 196 | # |
| 197 | # A run is in service of a task, or it is not -- most are not (a SWOT |
| 198 | # from the shell, a one-off from Talk). When it is, ownership is |
| 199 | # checked HERE, at queue time, the same "refused while somebody is |
| 200 | # looking" posture the capability-boundary checks below already use: |
| 201 | # attaching a run to a task the caller cannot see would let them |
| 202 | # infer the task exists (its id, its status) through what the run |
| 203 | # settles against. Same posture as the attachments capability, which |
| 204 | # gates a file to the record it is attached to the same way. |
| 205 | # |
| 206 | # "Cannot see" is the engine's answer to reading the task through the |
| 207 | # tasks API (owner, assignee, admin), and it is one 404 whether the |
| 208 | # task is missing or not the caller's: a 403 for the second case was |
| 209 | # the very inference this check exists to prevent. |
| 210 | task_id = _text(request.get("task_id")) |
| 211 | if task_id: |
| 212 | try: |
| 213 | task = access.get("tasks", task_id) |
| 214 | except Exception: |
| 215 | task = None |
| 216 | if task is None: |
| 217 | return {"status": 404, |
| 218 | "error": f"There is no task {task_id!r} on this server."} |
| 219 | |
| 220 | form_data = request.get("form_data") |
| 221 | if isinstance(form_data, str): |
| 222 | try: |
| 223 | form_data = json.loads(form_data or "{}") |
| 224 | except ValueError: |
| 225 | return {"status": 400, "error": "form_data is not valid JSON."} |
| 226 | form_data = form_data if isinstance(form_data, dict) else {} |
| 227 | |
| 228 | found = object_template_runs.problems(template, form_data) |
| 229 | handler = _text(template.get("handler")) |
| 230 | if handler and handler not in KNOWN_HANDLERS: |
| 231 | found.append(f"'{handler}' is not a handler this server knows. " |
| 232 | f"Available: {', '.join(KNOWN_HANDLERS)}.") |
| 233 | if found: |
| 234 | return {"status": 400, "error": " ".join(found), "problems": found} |
| 235 | |
| 236 | # --- capability boundaries, refused while somebody is looking ------------ |
| 237 | model = "" |
| 238 | if handler in AI_HANDLERS: |
| 239 | model = _setting(base, MODEL_SETTING) |
| 240 | missing = [] |
| 241 | if not model or ":" not in model: |
| 242 | missing.append(f"set {MODEL_SETTING} in app_settings to " |
| 243 | f"'<service>:<model>' (e.g. 'anthropic:claude-sonnet-4-5')") |
| 244 | else: |
| 245 | service = model.split(":", 1)[0] |
| 246 | if not object_service_keys.get_service_key(user_id, service, |
| 247 | base_dir=base): |
| 248 | missing.append(f"store a {service} API key for {user_id} " |
| 249 | f"(Settings -> Service Keys)") |
| 250 | if missing: |
| 251 | return {"status": 409, |
| 252 | "error": ("This template runs on an AI provider, and this " |
| 253 | "server is not configured for one: " |
| 254 | + "; ".join(missing) + ". Nothing was queued " |
| 255 | "and nothing was charged."), |
| 256 | "problems": missing} |
| 257 | |
| 258 | stamped = object_template_runs.stamp(template, form_data, model=model) |
| 259 | price = int(stamped["price_cents"]) |
| 260 | run_id = object_ids.new_uuid4() |
| 261 | |
| 262 | # --- the hold, through the gate, before the run -------------------------- |
| 263 | wallet_id = "" |
| 264 | if price > 0: |
| 265 | wallet = _wallet_for(base, user_id) |
| 266 | if wallet is None: |
| 267 | return {"status": 409, |
| 268 | "error": (f"This template costs {price} cents to run and " |
| 269 | f"{user_id} has no active wallet to hold it " |
| 270 | f"against. Create a wallet and top it up first.")} |
| 271 | wallet_id = _text(wallet.get("id")) |
| 272 | hold = object_template_runs.hold_entry( |
| 273 | run_id, wallet_id, price, user_id, |
| 274 | template_name=stamped["template_name"]) |
| 275 | |
| 276 | # The gate is asked on every attempt, and the hold CLAIMS the balance |
| 277 | # it was asked about (object_wallet: the next spend_seq of this |
| 278 | # wallet, unique inside the write lock). The gate alone runs before |
| 279 | # the lock, so four runs queued at once all passed it against one |
| 280 | # balance and a wallet with room for two held four. |
| 281 | gate_status = [402] |
| 282 | |
| 283 | def gate(entry): |
| 284 | verdict, error = _call("hook_wallet_entries", |
| 285 | {"action": "create", |
| 286 | "collection": "wallet_entries", |
| 287 | "record": entry}, |
| 288 | method="BEFORE_WRITE") |
| 289 | if error: |
| 290 | gate_status[0] = 409 |
| 291 | return (f"The wallet gate could not be consulted ({error}), " |
| 292 | f"so nothing was held and nothing was queued.") |
| 293 | if isinstance(verdict, dict) and verdict.get("error"): |
| 294 | gate_status[0] = int(verdict.get("status") or 402) |
| 295 | return _text(verdict.get("error")) or "The wallet gate refused the hold." |
| 296 | return "" |
| 297 | |
| 298 | try: |
| 299 | object_wallet.append_debit(wallet_id, hold, base_dir=base, |
| 300 | actor=user_id, gate=gate) |
| 301 | except object_wallet.Refused as refused: |
| 302 | return {"status": gate_status[0], "error": refused.message} |
| 303 | except object_wallet.Unreadable as exc: |
| 304 | return {"status": 503, |
| 305 | "error": (f"The wallet's balance cannot be read right now " |
| 306 | f"({exc}), so nothing was held and nothing was " |
| 307 | f"queued.")} |
| 308 | except object_wallet.Contended: |
| 309 | return {"status": 409, |
| 310 | "error": ("This wallet is being spent by other requests " |
| 311 | "right now, so nothing was held and nothing was " |
| 312 | "queued. Try again in a moment.")} |
| 313 | except Exception as exc: |
| 314 | return {"status": 500, |
| 315 | "error": f"The hold could not be placed: {str(exc)[:160]}"} |
| 316 | |
| 317 | # --- the run -------------------------------------------------------------- |
| 318 | record = { |
| 319 | "id": run_id, |
| 320 | **stamped, |
| 321 | "task_id": task_id, |
| 322 | "status": "queued", |
| 323 | "idempotency_key": object_ids.new_uuid4(), |
| 324 | "wallet_id": wallet_id, |
| 325 | "owner_id": user_id, |
| 326 | } |
| 327 | try: |
| 328 | # access: the caller's own run: owner_id is the caller; template and task were read through Access above |
| 329 | stored = object_records.create_collection_record( |
| 330 | RUNS, record, base_dir=base, actor=user_id) |
| 331 | except Exception as exc: |
| 332 | # The one wrong this ordering can leave is a hold with no run; give |
| 333 | # the money back now rather than leaving it to be noticed. |
| 334 | if price > 0: |
| 335 | try: |
| 336 | object_wallet.write_each_once( |
| 337 | object_template_runs.settlement( |
| 338 | {"id": run_id, "price_cents": str(price), |
| 339 | "wallet_id": wallet_id, "owner_id": user_id}, |
| 340 | succeeded=False), |
| 341 | base_dir=base, actor=ACTOR) |
| 342 | except Exception: |
| 343 | pass |
| 344 | return {"status": 500, |
| 345 | "error": f"The run could not be queued: {str(exc)[:160]}"} |
| 346 | |
| 347 | return {"ok": True, "run_id": run_id, "status": "queued", |
| 348 | "price_cents": price, "handler": handler, |
| 349 | "held": price > 0, |
| 350 | "note": ("Queued. The runner executes it on its next pass; the " |
| 351 | "hold settles when it finishes -- released in full plus " |
| 352 | "an ordinary debit on success, released alone on " |
| 353 | "failure." if price > 0 else |
| 354 | "Queued. Free to run, so no money was held.")} |