Coverage for app / services / economics / export.py: 91%

234 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2The daily economics export: each finished UTC day's model spend, whose it 

3was, what it was for, and what it bought. 

4 

5svc-core writes the day; the compose host ships it (``infra/aws/economics``): 

6the tables to S3, where Athena reads them beside AWS's own bill (CUR 2.0), and 

7the day's platform totals to CloudWatch, where the cost dashboard draws them. 

8svc-core never reaches AWS itself. It has no credentials, and its one way out 

9(the feed network) is not for this. 

10 

11What a day holds (``<dir>/days/<YYYY-MM-DD>/``), every row ids and figures 

12only — never a prompt, an answer, or a name anyone typed: 

13 

14``usage/dt=<day>/usage.jsonl`` 

15 The usage ledger (``governance_usage``): attributed spend, by workspace, 

16 source, execution type and outcome. What each workspace's own work cost. 

17``meter/dt=<day>/meter.jsonl`` 

18 svc-ai's meter (``GET /stats/meter``): every model call, platform work 

19 included, by workspace, source, purpose, model and outcome. The 

20 deployment's whole spend, which is what the AWS bill is reconciled to. 

21``utility/dt=<day>/utility.jsonl`` 

22 What the spend bought, by workspace: active users, answers by their 

23 quality check, finished skill runs, evaluation runs, applied generations 

24 and blocked invocations. 

25``totals/dt=<day>/totals.jsonl`` 

26 One row: the day's totals, the spending ceiling's count and the 

27 inference backend. 

28``plans/dt=<day>/plans.jsonl`` 

29 The plan each kind of workspace was on that day (``services/plans.py``): 

30 its monthly fee, markup and included usage — what a workspace pays, so 

31 Athena can set revenue against cost (``gross-margin.sql``). No row for a 

32 kind with no plan. 

33``metrics.json`` 

34 The day's platform totals as a CloudWatch ``PutMetricData`` request. 

35``manifest.json`` 

36 Written last: a day with one is complete. 

37 

38A day is written once, on the first run after it has settled, into a 

39temporary directory renamed into place, so the shipper never sees half of one. 

40Runs fill in any missing day within ``ECONOMICS_EXPORT_LOOKBACK_DAYS`` and 

41delete days older than that. See ``docs/guides/cost-monitoring.md``. 

42""" 

43 

44from __future__ import annotations 

45 

46import json 

47import logging 

48import shutil 

49import tempfile 

50from collections import defaultdict 

51from dataclasses import dataclass, field 

52from datetime import date, datetime, time, timedelta, timezone 

53from decimal import Decimal 

54from pathlib import Path 

55from typing import Any, Iterable 

56 

57from sqlalchemy import and_, case, distinct, func 

58from sqlalchemy.orm import Session 

59 

60from app.db.postgres.enums import ( 

61 GovernanceEnum, 

62 MessageEnum, 

63 RunnableEnum, 

64 SkillRunEnum, 

65) 

66from app.services import ai_client, quality_check 

67from app.services.economics import attribution 

68from app.services.economics.attribution import Kind, Owner, Projects 

69from app.util.time import aware_utcnow, utc_isoformat 

70 

71logger = logging.getLogger(__name__) 

72 

73#: Bumped whenever a table's columns change. 

74SCHEMA_VERSION = 1 

75DAYS_DIR = "days" 

76MANIFEST = "manifest.json" 

77METRICS_FILE = "metrics.json" 

78#: Where the host publishes ``metrics.json`` (``infra/aws/economics``). 

79METRIC_NAMESPACE = "ChainR/Economics" 

80#: How long after midnight UTC a day is exported: work that began before 

81#: midnight and is recorded just after belongs to the day it began. 

82SETTLE = timedelta(hours=1) 

83#: Days written per run. A first run, or one after a long gap, catches up 

84#: over several hourly runs instead of holding the tick. 

85MAX_DAYS_PER_RUN = 7 

86 

87#: An answer's quality check (``meta.eval_outcome``) → the column counting 

88#: it. An answer with no check recorded is ``answers_unchecked`` as well. 

89ANSWER_COLUMNS: dict[quality_check.Outcome, str] = { 

90 quality_check.Outcome.passed: "answers_passed", 

91 quality_check.Outcome.revised: "answers_revised", 

92 quality_check.Outcome.failed: "answers_failed", 

93 quality_check.Outcome.unavailable: "answers_unchecked", 

94 # Unchecked by the agent's cost profile's choice: unchecked all the same, 

95 # and the Athena tables' columns stay as they are. 

96 quality_check.Outcome.skipped: "answers_unchecked", 

97} 

98UTILITY_COUNTS = ( 

99 "active_users", 

100 "answers", 

101 "answers_passed", 

102 "answers_revised", 

103 "answers_failed", 

104 "answers_unchecked", 

105 "skill_runs_completed", 

106 "skill_runs_failed", 

107 "evaluation_runs_completed", 

108 "generations_applied", 

109 "invocations_blocked", 

110) 

111_SKILL_RUN_COLUMNS = { 

112 SkillRunEnum.Status.completed.value: "skill_runs_completed", 

113 SkillRunEnum.Status.failed.value: "skill_runs_failed", 

114} 

115USAGE_SUMS = ( 

116 "invocations", 

117 "llm_calls", 

118 "unpriced_calls", 

119 "input_tokens", 

120 "output_tokens", 

121 "cost_usd", 

122) 

123METER_SUMS = ( 

124 "calls", 

125 "failed_calls", 

126 "unpriced_calls", 

127 "prompt_tokens", 

128 "completion_tokens", 

129 "cache_read_tokens", 

130 "cache_write_tokens", 

131 "reasoning_tokens", 

132 "cost_usd", 

133 "cache_savings_usd", 

134) 

135_MONEY = {"cost_usd", "cache_savings_usd"} 

136 

137 

138class ExportError(Exception): 

139 """A day could not be built or written; the message says why.""" 

140 

141 

142@dataclass 

143class DayExport: 

144 day: date 

145 tables: dict[str, list[dict[str, Any]]] 

146 metrics: dict[str, Any] 

147 

148 

149@dataclass 

150class RunResult: 

151 written: list[date] = field(default_factory=list) 

152 #: Missing days left for the next run (``MAX_DAYS_PER_RUN``). 

153 pending: int = 0 

154 pruned: int = 0 

155 

156 

157# ─── Days ───────────────────────────────────────────────────────────────────── 

158 

159 

160def bounds(day: date) -> tuple[datetime, datetime]: 

161 """The UTC day as the naive datetimes the columns hold.""" 

162 start = datetime.combine(day, time.min) 

163 return start, start + timedelta(days=1) 

164 

165 

166def due_days(now: datetime, lookback_days: int) -> list[date]: 

167 """The finished, settled days within the lookback, oldest first.""" 

168 last = (now.astimezone(timezone.utc) - SETTLE).date() - timedelta(days=1) 

169 first = now.astimezone(timezone.utc).date() - timedelta(days=lookback_days) 

170 return [first + timedelta(days=n) for n in range((last - first).days + 1)] 

171 

172 

173def day_dir(root: Path, day: date) -> Path: 

174 return root / DAYS_DIR / day.isoformat() 

175 

176 

177def written(root: Path, day: date) -> bool: 

178 return (day_dir(root, day) / MANIFEST).is_file() 

179 

180 

181# ─── Building a day ─────────────────────────────────────────────────────────── 

182 

183 

184class _Sums: 

185 """Rows keyed by their non-figure columns, figures summed: two raw groups 

186 that resolve to the same workspace become one row.""" 

187 

188 def __init__(self, figures: Iterable[str]) -> None: 

189 self.figures = tuple(figures) 

190 self.rows: dict[tuple, dict[str, Any]] = {} 

191 

192 def add(self, keys: dict[str, Any], figures: dict[str, Any]) -> None: 

193 index = tuple(keys.items()) 

194 row = self.rows.get(index) 

195 if row is None: 

196 row = self.rows[index] = {**keys, **dict.fromkeys(self.figures, 0)} 

197 for name in self.figures: 

198 row[name] += figures.get(name) or 0 

199 

200 def out(self) -> list[dict[str, Any]]: 

201 return sorted(self.rows.values(), key=lambda row: json.dumps(row, default=str)) 

202 

203 

204def _value(member: Any) -> Any: 

205 return getattr(member, "value", member) 

206 

207 

208def _usage(db: Session, projects: Projects, start: datetime, end: datetime): 

209 from app.db.postgres.models import GovernanceUsage as G 

210 

211 unstamped = and_( 

212 G.workspace_user_id.is_(None), 

213 G.owner_project_id.is_(None), 

214 G.owner_organisation_id.is_(None), 

215 ) 

216 # The invoker only where no stamp says whose workspace it was. 

217 person = case((unstamped, G.owner_user_id), else_=G.workspace_user_id) 

218 keys = ( 

219 person.label("user_id"), 

220 G.owner_organisation_id, 

221 G.owner_project_id, 

222 G.source_type, 

223 G.execution_type, 

224 G.outcome, 

225 ) 

226 rows = ( 

227 db.query( 

228 *keys, 

229 func.count(G.id).label("invocations"), 

230 func.coalesce(func.sum(G.llm_calls), 0).label("llm_calls"), 

231 func.coalesce(func.sum(G.unpriced_calls), 0).label("unpriced_calls"), 

232 func.coalesce(func.sum(G.input_tokens), 0).label("input_tokens"), 

233 func.coalesce(func.sum(G.output_tokens), 0).label("output_tokens"), 

234 func.coalesce(func.sum(G.estimated_cost_usd), 0).label("cost_usd"), 

235 ) 

236 .filter(G.occurred_at >= start, G.occurred_at < end) 

237 .group_by(*keys) 

238 .all() 

239 ) 

240 sums = _Sums(USAGE_SUMS) 

241 for row in rows: 

242 where = attribution.owner( 

243 projects, 

244 user_id=row.user_id, 

245 organisation_id=row.owner_organisation_id, 

246 project_id=row.owner_project_id, 

247 ) 

248 sums.add( 

249 { 

250 **where.columns(), 

251 "source": row.source_type or "unattributed", 

252 "execution_type": row.execution_type, 

253 "outcome": _value(row.outcome), 

254 }, 

255 {name: getattr(row, name) for name in USAGE_SUMS}, 

256 ) 

257 return sums.out() 

258 

259 

260def _meter(projects: Projects, groups: list[dict[str, Any]]): 

261 sums = _Sums(METER_SUMS) 

262 for group in groups: 

263 where = attribution.trace_owner( 

264 projects, group.get("workspace"), group.get("user_id") 

265 ) 

266 figures = { 

267 name: Decimal(str(group.get(name) or 0)) 

268 if name in _MONEY 

269 else int(group.get(name) or 0) 

270 for name in METER_SUMS 

271 } 

272 sums.add( 

273 { 

274 **where.columns(), 

275 "source": attribution.source_of(group.get("purpose")), 

276 "purpose": group.get("purpose"), 

277 "provider": group.get("provider"), 

278 "model": group.get("model"), 

279 "kind": group.get("kind"), 

280 "status": group.get("status"), 

281 }, 

282 figures, 

283 ) 

284 return sums.out() 

285 

286 

287class _Utility: 

288 """Utility counts per workspace, and the day's distinct active users.""" 

289 

290 def __init__(self, projects: Projects) -> None: 

291 self.projects = projects 

292 self.counts: dict[Owner, dict[str, int]] = defaultdict( 

293 lambda: dict.fromkeys(UTILITY_COUNTS, 0) 

294 ) 

295 self.users: dict[Owner, set[str]] = defaultdict(set) 

296 

297 def add(self, where: Owner, column: str, count: int) -> None: 

298 self.counts[where][column] += int(count or 0) 

299 

300 def rows(self) -> list[dict[str, Any]]: 

301 for where, people in self.users.items(): 

302 self.counts[where]["active_users"] = len(people) 

303 return sorted( 

304 ({**where.columns(), **counts} for where, counts in self.counts.items()), 

305 key=lambda row: json.dumps(row, default=str), 

306 ) 

307 

308 def active_users(self) -> int: 

309 return len(set().union(*self.users.values())) if self.users else 0 

310 

311 

312def _utility(db: Session, projects: Projects, start: datetime, end: datetime): 

313 from app.db.postgres.models import ChatMessage as M 

314 from app.db.postgres.models import Conversation as C 

315 from app.db.postgres.models import Experiment as E 

316 from app.db.postgres.models import ExperimentBatch as B 

317 from app.db.postgres.models import GenerationRun as R 

318 from app.db.postgres.models import GovernanceEvent as V 

319 from app.db.postgres.models import GovernanceUsage as G 

320 from app.db.postgres.models import SkillRun as S 

321 

322 out = _Utility(projects) 

323 

324 def stamped(model: Any) -> tuple: 

325 """A stamped table's workspace, the invoker where it has none.""" 

326 unstamped = and_( 

327 model.workspace_user_id.is_(None), 

328 model.owner_project_id.is_(None), 

329 model.owner_organisation_id.is_(None), 

330 ) 

331 return ( 

332 case((unstamped, model.owner_user_id), else_=model.workspace_user_id), 

333 model.owner_organisation_id, 

334 model.owner_project_id, 

335 ) 

336 

337 # Active users: everyone whose work reached a model, per workspace. 

338 for user, org, project, person in ( 

339 db.query(*stamped(G), G.owner_user_id) 

340 .filter(G.occurred_at >= start, G.occurred_at < end) 

341 .distinct() 

342 .all() 

343 ): 

344 if person is None: 

345 # Work no person started (a scheduled crawl of an 

346 # organisation's source, migration 99): nobody was active. 

347 continue 

348 where = attribution.owner( 

349 projects, user_id=user, organisation_id=org, project_id=project 

350 ) 

351 out.users[where].add(str(person)) 

352 

353 # Answers delivered, by what their quality check concluded. 

354 outcome = M.meta["eval_outcome"].as_string() 

355 for user, org, project, checked, count in ( 

356 db.query( 

357 C.owner_user_id, 

358 C.workspace_organisation_id, 

359 C.workspace_project_id, 

360 outcome, 

361 func.count(M.id), 

362 ) 

363 .join(C, M.conversation_id == C.id) 

364 .filter( 

365 M.role == MessageEnum.Role.ASSISTANT, 

366 M.status == MessageEnum.Status.COMPLETED, 

367 M.sent_at >= start, 

368 M.sent_at < end, 

369 ) 

370 .group_by( 

371 C.owner_user_id, 

372 C.workspace_organisation_id, 

373 C.workspace_project_id, 

374 outcome, 

375 ) 

376 .all() 

377 ): 

378 where = attribution.owner( 

379 projects, user_id=user, organisation_id=org, project_id=project 

380 ) 

381 out.add(where, "answers", count) 

382 try: 

383 column = ANSWER_COLUMNS[quality_check.Outcome(checked)] 

384 except ValueError: 

385 column = "answers_unchecked" 

386 out.add(where, column, count) 

387 

388 # Standalone skill runs that finished. 

389 for user, org, project, status, count in ( 

390 db.query( 

391 S.user_id, 

392 S.workspace_organisation_id, 

393 S.workspace_project_id, 

394 S.status, 

395 func.count(S.id), 

396 ) 

397 .filter( 

398 S.finished_at >= start, 

399 S.finished_at < end, 

400 S.status.in_(list(_SKILL_RUN_COLUMNS)), 

401 ) 

402 .group_by( 

403 S.user_id, S.workspace_organisation_id, S.workspace_project_id, S.status 

404 ) 

405 .all() 

406 ): 

407 where = attribution.owner( 

408 projects, user_id=user, organisation_id=org, project_id=project 

409 ) 

410 out.add(where, _SKILL_RUN_COLUMNS[status], count) 

411 

412 # Evaluation runs that completed: saved evaluations only (an unsaved 

413 # Quick try has no experiment), the platform benchmark's as the 

414 # platform's. 

415 for user, org, project, is_system, count in ( 

416 db.query( 

417 E.owner_user_id, 

418 E.owner_organisation_id, 

419 E.owner_project_id, 

420 E.is_system, 

421 func.count(B.id), 

422 ) 

423 .join(E, B.experiment_id == E.id) 

424 .filter( 

425 B.status == RunnableEnum.Status.completed, 

426 B.finished_at >= start, 

427 B.finished_at < end, 

428 ) 

429 .group_by( 

430 E.owner_user_id, E.owner_organisation_id, E.owner_project_id, E.is_system 

431 ) 

432 .all() 

433 ): 

434 where = ( 

435 attribution.PLATFORM 

436 if is_system 

437 else attribution.owner( 

438 projects, user_id=user, organisation_id=org, project_id=project 

439 ) 

440 ) 

441 out.add(where, "evaluation_runs_completed", count) 

442 

443 # Generated proposals somebody accepted. 

444 for user, org, project, count in ( 

445 db.query( 

446 R.actor_user_id, 

447 R.workspace_organisation_id, 

448 R.workspace_project_id, 

449 func.count(R.id), 

450 ) 

451 .filter(R.applied_at >= start, R.applied_at < end) 

452 .group_by(R.actor_user_id, R.workspace_organisation_id, R.workspace_project_id) 

453 .all() 

454 ): 

455 where = attribution.owner( 

456 projects, user_id=user, organisation_id=org, project_id=project 

457 ) 

458 out.add(where, "generations_applied", count) 

459 

460 # Invocations a policy rule refused: one per invocation, however many 

461 # rules said so. 

462 keys = stamped(V) 

463 for user, org, project, count in ( 

464 db.query(*keys, func.count(distinct(func.coalesce(V.invocation_id, V.id)))) 

465 .filter( 

466 V.outcome == GovernanceEnum.Outcome.blocked, 

467 V.created_at >= start, 

468 V.created_at < end, 

469 ) 

470 .group_by(*keys) 

471 .all() 

472 ): 

473 where = attribution.owner( 

474 projects, user_id=user, organisation_id=org, project_id=project 

475 ) 

476 out.add(where, "invocations_blocked", count) 

477 

478 return out 

479 

480 

481def _total(rows: list[dict[str, Any]], name: str, **where: Any) -> Any: 

482 return sum( 

483 ( 

484 row[name] 

485 for row in rows 

486 if all( 

487 (row[key] in value) if isinstance(value, tuple) else row[key] == value 

488 for key, value in where.items() 

489 ) 

490 ), 

491 Decimal(0) if name in _MONEY else 0, 

492 ) 

493 

494 

495def _metrics(day: date, meter: list[dict], summary: dict[str, Any]) -> dict[str, Any]: 

496 """The day's platform totals as a CloudWatch ``PutMetricData`` request, 

497 stamped at noon so a daily period puts it in its own day whatever the 

498 viewer's time zone. Workspaces stay in Athena: a CloudWatch metric costs 

499 the same for one figure as for a whole dimension's worth.""" 

500 stamp = datetime.combine(day, time(12), tzinfo=timezone.utc).isoformat() 

501 

502 def datum(name: str, value: Any, unit: str, **dimensions: str) -> dict: 

503 out: dict[str, Any] = { 

504 "MetricName": name, 

505 "Timestamp": stamp, 

506 "Value": float(value), 

507 "Unit": unit, 

508 } 

509 if dimensions: 

510 out["Dimensions"] = [{"Name": k, "Value": v} for k, v in dimensions.items()] 

511 return out 

512 

513 owned = tuple(kind.value for kind in Kind if kind is not Kind.platform) 

514 data = [ 

515 datum( 

516 "AICost", 

517 _total(meter, "cost_usd", workspace_kind=owned, source=source), 

518 "None", 

519 Source=source, 

520 ) 

521 for source in attribution.sources() 

522 ] 

523 data.append( 

524 datum("AICost", summary["platform_usd"], "None", Source=Kind.platform.value) 

525 ) 

526 data += [ 

527 datum("MeteredCost", summary["metered_usd"], "None"), 

528 datum("CacheSavings", summary["cache_savings_usd"], "None"), 

529 datum("FailedWorkCost", summary["failed_work_usd"], "None"), 

530 datum("ActiveUsers", summary["active_users"], "Count"), 

531 ] 

532 data += [ 

533 datum( 

534 "".join(part.capitalize() for part in column.split("_")), 

535 summary[column], 

536 "Count", 

537 ) 

538 for column in UTILITY_COUNTS 

539 if column != "active_users" 

540 ] 

541 return {"Namespace": METRIC_NAMESPACE, "MetricData": data} 

542 

543 

544def _plans() -> list[dict[str, Any]]: 

545 """Each kind of workspace's plan in force (``services/plans.py``): one 

546 row a kind that has one. Prices are the deployment's, per kind, so the 

547 day's are the settings as they stand when it is written.""" 

548 from app.services import plans 

549 

550 rows = [] 

551 for kind in (Kind.personal, Kind.organisation): 

552 plan = plans.for_kind(kind.value) 

553 if plan is not None: 

554 rows.append( 

555 { 

556 "workspace_kind": kind.value, 

557 "currency": plans.CURRENCY, 

558 "fee_usd": plan.fee_usd, 

559 "markup_percent": plan.markup_percent, 

560 "included_usd": plan.included_usd, 

561 } 

562 ) 

563 return rows 

564 

565 

566def build(db: Session, day: date) -> DayExport: 

567 """Everything one UTC day comes to. Raises ``ExportError`` when svc-ai's 

568 meter cannot be read: a day without the deployment's whole spend is not 

569 worth writing.""" 

570 projects = Projects(db) 

571 start, end = bounds(day) 

572 try: 

573 metered = ai_client.get_daily_meter(day) 

574 except ai_client.AIServiceError as exc: 

575 raise ExportError(f"svc-ai's meter for {day}: {exc}") from exc 

576 usage = _usage(db, projects, start, end) 

577 meter = _meter(projects, metered.get("groups") or []) 

578 utility = _utility(db, projects, start, end) 

579 utility_rows = utility.rows() 

580 counted = metered.get("ceiling_counted_usd") 

581 summary: dict[str, Any] = { 

582 "schema_version": SCHEMA_VERSION, 

583 "backend": ai_client.inference_backend(), 

584 "metered_usd": _total(meter, "cost_usd"), 

585 "platform_usd": _total(meter, "cost_usd", workspace_kind=Kind.platform.value), 

586 "ledger_usd": _total(usage, "cost_usd"), 

587 "ceiling_counted_usd": None if counted is None else Decimal(str(counted)), 

588 "cache_savings_usd": _total(meter, "cache_savings_usd"), 

589 "failed_work_usd": _total(meter, "cost_usd", status=("error", "timeout")), 

590 "unpriced_calls": _total(meter, "unpriced_calls"), 

591 **{ 

592 column: _total(utility_rows, column) 

593 for column in UTILITY_COUNTS 

594 if column != "active_users" 

595 }, 

596 # Not the sum of the rows: one person can be active in several 

597 # workspaces in a day. 

598 "active_users": utility.active_users(), 

599 "exported_at": utc_isoformat(aware_utcnow()), 

600 } 

601 return DayExport( 

602 day=day, 

603 tables={ 

604 "usage": usage, 

605 "meter": meter, 

606 "utility": utility_rows, 

607 "totals": [summary], 

608 "plans": _plans(), 

609 }, 

610 metrics=_metrics(day, meter, summary), 

611 ) 

612 

613 

614# ─── Writing ────────────────────────────────────────────────────────────────── 

615 

616 

617def _json(value: Any) -> Any: 

618 if isinstance(value, Decimal): 

619 # Exact to the ledger's own precision (Numeric(14, 8)). 

620 return float(round(value, 10)) 

621 raise TypeError(f"Not exportable: {type(value).__name__}") 

622 

623 

624def write(root: Path, export: DayExport) -> Path: 

625 """Write ``export`` as its day's directory, whole or not at all.""" 

626 parent = root / DAYS_DIR 

627 parent.mkdir(parents=True, exist_ok=True) 

628 day = export.day.isoformat() 

629 staging = Path(tempfile.mkdtemp(prefix=f".{day}-", dir=parent)) 

630 try: 

631 for table, rows in export.tables.items(): 

632 path = staging / table / f"dt={day}" / f"{table}.jsonl" 

633 path.parent.mkdir(parents=True) 

634 path.write_text( 

635 "".join(json.dumps(row, default=_json) + "\n" for row in rows) 

636 ) 

637 (staging / METRICS_FILE).write_text(json.dumps(export.metrics, indent=1)) 

638 manifest = { 

639 "day": day, 

640 "schema_version": SCHEMA_VERSION, 

641 "rows": {table: len(rows) for table, rows in export.tables.items()}, 

642 "written_at": utc_isoformat(aware_utcnow()), 

643 } 

644 (staging / MANIFEST).write_text(json.dumps(manifest, indent=1)) 

645 staging.chmod(0o755) 

646 final = day_dir(root, export.day) 

647 if final.exists(): # an attempt that never got its manifest 

648 shutil.rmtree(final) 

649 staging.rename(final) 

650 return final 

651 except BaseException: 

652 shutil.rmtree(staging, ignore_errors=True) 

653 raise 

654 

655 

656def prune(root: Path, keep_from: date) -> int: 

657 """Delete written days before ``keep_from``, and any staging directory a 

658 crashed write left behind. The host has long since shipped them.""" 

659 parent = root / DAYS_DIR 

660 if not parent.is_dir(): 

661 return 0 

662 removed = 0 

663 for entry in parent.iterdir(): 

664 name = entry.name 

665 try: 

666 stale = name.startswith(".") or date.fromisoformat(name) < keep_from 

667 except ValueError: 

668 continue # not ours 

669 if stale and entry.is_dir(): 

670 shutil.rmtree(entry, ignore_errors=True) 

671 removed += not name.startswith(".") 

672 return removed 

673 

674 

675def run( 

676 db: Session, root: Path, *, lookback_days: int, now: datetime | None = None 

677) -> RunResult: 

678 """Write every missing day within the lookback (oldest first, up to 

679 ``MAX_DAYS_PER_RUN``) and delete days that have left it.""" 

680 moment = now or aware_utcnow() 

681 result = RunResult() 

682 missing = [day for day in due_days(moment, lookback_days) if not written(root, day)] 

683 result.pending = max(0, len(missing) - MAX_DAYS_PER_RUN) 

684 for day in missing[:MAX_DAYS_PER_RUN]: 

685 export = build(db, day) 

686 try: 

687 write(root, export) 

688 except OSError as exc: 

689 raise ExportError(f"Could not write {day} to {root}: {exc}") from exc 

690 result.written.append(day) 

691 logger.info("Economics export: wrote %s", day) 

692 result.pruned = prune(root, moment.date() - timedelta(days=lookback_days)) 

693 return result