1"""Charging that cannot leak, cannot over-bill, and cannot silently bill nothing.
2
3Every rule in this module is here because a build in this portfolio shipped
4without it. The run always looked healthy; the money was wrong. Keep this file
5when re-targeting the template - it is not target-specific - and configure it
6once in main.py (see `Ledger.configure`).
7
8WHAT GOES WRONG, AND WHICH RULE ANSWERS IT
9------------------------------------------
101. Push, then charge. Past the run's `maxTotalChargeUsd` `Actor.charge` bills
11 nothing and raises nothing, so rows already in flight ship free and the run
12 ends SUCCEEDED. Measured: letterboxd at a $0.11 cap delivered 200 rows
13 against 110 charges - 45% of the run free, because five pages were in flight
14 at maxConcurrency 5 and each pushed before charging. (The same cap at $0.10
15 looked clean: 100 rows is a page boundary, so a page-aligned cap hides it.)
16 -> every delivery goes through `Actor.push_data(rows, charged_event_name=...)`,
17 which holds the SDK's charge lock across the write AND the charge, truncates
18 the write to the remaining budget, and charges exactly what it wrote.
19
202. Charge, then push, and the push fails. Billing for a row nobody received is
21 worse than the leak above. dynamitejobs reverted a correct reorder over this:
22 one listing in ~100 failed the dataset schema, so charge-first billed 100 and
23 delivered 99, three runs out of three.
24 -> rows are validated against the dataset schema BEFORE they are charged
25 (`RowGuard`), and the atomic push above cannot write without charging.
26
273. A bulk count bills partially. `charged_count < count` when the budget runs
28 out mid-batch; opentable shipped rows carrying 20 reviews with 5 billed.
29 -> delivery is always sliced to `charged_count`, never gated on a boolean.
30
314. `charged_count == 0` does not mean "unpaid". It is also 0 on a local run and
32 on a free run of a monetised Actor, where every row must still ship. Reading
33 it as a spent budget empties the dataset - it broke a cap test on
34 dubai-rest before it shipped.
35 -> billability is resolved ONCE at run start from the live pricing config,
36 and a failed read falls back to delivering unbilled, never to withholding.
37
385. An event name the pricing config does not know bills USD 0 in silence.
39 Measured against apify 4.0.2 on 2026-10-29, on-platform: charging an unpriced
40 name returns `charged_count == count` with `event_charge_limit_reached=False`,
41 `push_data` does not truncate, and no charge request is sent - only a
42 `logger.warning`. So the SDK's own numbers say "fully billed" while the run
43 earns nothing; `per_event_prices` is the only thing that tells you otherwise.
44 (Off-platform the same name costs $1 each, which is the opposite failure:
45 charged_count 0 and a truncated push.) sofascore billed no enrichments at all
46 for two weeks this way, because the build led the pricing.
47 -> event names are resolved from `per_event_prices` at run start, with a
48 legacy fallback, so no build ever charges a name the platform does not
49 price. The audit names any event that was charged while unpriced.
50
516. A surcharge that gates delivery. The base row is already paid for by the time
52 a surcharge fires, so withholding the row then bills without delivering - the
53 mirror of (1). 99co measured 49 rows against 52 `listing-detail` charges at a
54 $0.101 cap, three surcharges with no row, because Crawlee drained DETAIL
55 requests concurrently and several handlers cleared the surcharge before any of
56 their pushes found the budget gone.
57 -> `surcharges` are charged AFTER the base row has shipped, only for rows that
58 shipped, and can never withhold. A refused surcharge leaves one row's
59 enrichment unbilled, which is the right direction to fail.
60 -> for an enrichment that CAN be withheld because it has not shipped yet, use
61 `slices`: charged before the write, and a refused slice blanks its own
62 fields and lets the row ship (ssense: 67 rows carried a detail slice
63 against 66 pdp-row charges).
64
657. The same row billed twice. dubai-rest 0.0.17 delivered 5 rows and charged the
66 legacy event 10, because the base and the surcharge path each charged it.
67 -> one base charge per row per delivery, and the audit reconciles charged
68 against delivered per event.
69
708. Billing for rows that resolved nothing, or for duplicates. Yahoo Sports
71 answers an unknown-but-well-formed id with HTTP 200 and a zero-byte body, and
72 a full-shaped row was billed off it. Zara billed 79 rows for 39 distinct
73 products; esimdb would have billed each multi-country plan up to 3.7x.
74 -> `resolved` and `key_of` run strictly BEFORE the charge, and both counts are
75 in the audit. Dedupe state is scoped, because sharing one scope across
76 sibling walks made each stay drop the previous one's results (booking).
77
789. Concurrency. Everything above is decided per handler while 5-20 handlers run,
79 so a decision read outside a lock is a decision taken on stale state.
80 -> `deliver()` holds one lock across dedupe -> validate -> slice charges ->
81 write+charge -> counters, and the stop flag is set under that same lock.
82 `should_enqueue()` exists because the charge that spends the budget happens
83 in the same pass that queues the next page, so follow-up work has to
84 re-check (the skill's rule; 99co's three free surcharges are the cost).
85
8610. A capped run that does not explain itself. It ends SUCCEEDED with a short
87 dataset, which reads as "that is all there was"; and the count in the message
88 has to be rows DELIVERED, not rows emitted - hacker-news told users
89 "Stopped after 150 row(s)" for a run that delivered and billed 100.
90 -> `finish()` sets the status message from the delivered count.
91
9211. Nothing in the run record says what was billed and why. `chargedEventCounts`
93 on the platform settles ~20s after the run finishes and is `{}` on the list
94 endpoint, so there is nothing to triage with while the run is fresh.
95 -> `finish()` logs a per-event audit and writes it to the key-value store,
96 including a cross-check of the ledger's own counts against the SDK's, which
97 is how a charge made outside the ledger shows up at all.
98"""
99
100from __future__ import annotations
101
102import asyncio
103import inspect
104import json
105from collections import Counter
106from dataclasses import dataclass, field
107from decimal import Decimal
108from pathlib import Path
109from typing import Any, Callable, Hashable, Mapping, Sequence
110
111from apify import Actor
112
113Row = dict[str, Any]
114
115
116
117
118
119
120SYNTHETIC_PREFIX = "apify-"
121SYNTHETIC_DATASET_ITEM = "apify-default-dataset-item"
122
123AUDIT_RECORD_KEY = "BILLING_AUDIT"
124
125STOP_CAP = "charge-cap"
126STOP_MAX_ITEMS = "max-items"
127STOP_CHANNEL = "charge-channel"
128
129_STOP_MESSAGES = {
130 STOP_CAP: (
131 "Stopped after {rows} row(s): this run hit its maximum cost setting, not the end "
132 "of the results. Raise the run's max total charge to collect the rest."
133 ),
134 STOP_MAX_ITEMS: "Finished at the requested limit of {rows} row(s).",
135 STOP_CHANNEL: (
136 "Stopped after {rows} row(s): the Apify charging API would not answer, so the run "
137 "stopped rather than carry on scraping without being able to bill it. Nothing new "
138 "was charged after that point - please re-run, and contact support if anything was "
139 "billed without being delivered."
140 ),
141}
142
143
144class BillingChannelError(RuntimeError):
145 """The charge/write channel failed twice, so no more billable work is safe.
146
147 Raised out of `deliver()` after the ledger has already stopped itself. Let it
148 reach main.py's handler: a charging channel that just failed cannot be trusted
149 with the rest of the run, and the run must not crash on it either (a platform
150 outage is not this Actor's defect and must not page the crash webhook as one).
151 """
152
153
154@dataclass(frozen=True)
155class Slice:
156 """An optional part of a row, billed separately, withheld if it is refused.
157
158 `kind` is a key in the ledger's event map, `fields` the row keys the slice
159 owns, and `present` decides which rows actually carry it (default: at least
160 one of the fields is not None). Use a slice when the enrichment is in hand
161 before the row ships and so CAN be withheld; use a surcharge when it cannot.
162
163 **A slice may be billed per ITEM rather than per row.** Several Actors here
164 charge one event per review, per sale, per price-history point - a list that
165 rides inside the row it belongs to. Give such a slice a `count` (how many
166 units this row owes) and a `trim` (cut the row back to the `billed` units),
167 and the ledger charges and trims in units instead of all-or-nothing. Without
168 `trim`, a refused slice is blanked entirely, which is right for a scalar part
169 and wrong for a list the buyer partly paid for.
170 """
171
172 kind: str
173 fields: tuple[str, ...]
174 present: Callable[[Row], bool] | None = None
175 count: Callable[[Row], int] | None = None
176 trim: Callable[[Row, int], None] | None = None
177
178 def units(self, row: Row) -> int:
179 """How many billable units of this slice the row carries."""
180 if self.count is None:
181 return 1 if self.carries(row) else 0
182 return max(0, int(self.count(row) or 0))
183
184 def carries(self, row: Row) -> bool:
185 if self.count is not None:
186 return self.units(row) > 0
187 if self.present is not None:
188 return bool(self.present(row))
189 return any(row.get(name) is not None for name in self.fields)
190
191 def cut(self, row: Row, billed: int) -> None:
192 """Keep only what was billed. `billed == 0` removes the part entirely."""
193 if self.trim is not None:
194 self.trim(row, billed)
195 return
196 self.blank(row)
197
198 def blank(self, row: Row) -> None:
199 for name in self.fields:
200 if name in row:
201 row[name] = None
202
203
204@dataclass(frozen=True)
205class Delivery:
206 """What one `deliver()` call actually did. Count rows from here, not from the
207 list you passed in - that is the bug in rule 10 above."""
208
209 kind: str
210 delivered: list[Row]
211 billed: int
212 duplicates: int = 0
213 unresolved: int = 0
214 invalid: int = 0
215 trimmed: int = 0
216 stripped: dict[str, int] = field(default_factory=dict)
217 stopped: str | None = None
218
219 @property
220 def count(self) -> int:
221 return len(self.delivered)
222
223
224_JSON_TYPES: dict[str, tuple[type, ...]] = {
225 "string": (str,),
226 "integer": (int,),
227 "number": (int, float),
228 "boolean": (bool,),
229 "array": (list,),
230 "object": (dict,),
231 "null": (type(None),),
232}
233
234
235@dataclass
236class RowGuard:
237 """Drops a row the dataset would reject, before it can be charged.
238
239 The platform validates each item against `dataset_schema.json` and rejects the
240 WHOLE item on one bad member, so with charging ahead of the write a type
241 mismatch becomes a bill with no delivery. uniqlo billed 5 and delivered 0 that
242 way: three row shapes shared one schema whose types were written for one of
243 them, and review fields are routinely null, which a bare `"string"` rejects.
244
245 Build it from the shipped schema (`from_dataset_schema`) so the types have one
246 source of truth. With no schema file this is a no-op by design - the template
247 deliberately ships no `dataset_schema.json`, because one describing the example
248 would reject a real target's rows.
249 """
250
251 types: dict[str, tuple[str, ...]] = field(default_factory=dict)
252 required: tuple[str, ...] = ()
253
254 @classmethod
255 def from_dataset_schema(cls, path: str | Path) -> RowGuard:
256 schema_path = Path(path)
257 if not schema_path.is_file():
258 return cls()
259 try:
260 fields = json.loads(schema_path.read_text()).get("fields") or {}
261 except (OSError, ValueError):
262 return cls()
263 properties = fields.get("properties") or {}
264 types: dict[str, tuple[str, ...]] = {}
265 for name, spec in properties.items():
266 declared = spec.get("type") if isinstance(spec, dict) else None
267 if isinstance(declared, str):
268 types[name] = (declared,)
269 elif isinstance(declared, list):
270 types[name] = tuple(str(entry) for entry in declared)
271 return cls(types=types, required=tuple(fields.get("required") or ()))
272
273 @property
274 def active(self) -> bool:
275 return bool(self.types or self.required)
276
277 def reject_reason(self, row: Row) -> str | None:
278 """None when the row is deliverable, else why it would be rejected."""
279 for name in self.required:
280 if row.get(name) is None:
281 return f"required field '{name}' is missing or null"
282 for name, declared in self.types.items():
283 if name not in row:
284 continue
285 value = row[name]
286 if not self._matches(value, declared):
287 return (
288 f"field '{name}' is {type(value).__name__}, "
289 f"schema declares {'|'.join(declared)}"
290 )
291 return None
292
293 @staticmethod
294 def _matches(value: Any, declared: Sequence[str]) -> bool:
295 for name in declared:
296 allowed = _JSON_TYPES.get(name)
297 if allowed is None:
298 return True
299
300
301 if name in {"integer", "number"} and isinstance(value, bool):
302 continue
303 if isinstance(value, allowed):
304 return True
305 return False
306
307
308class Ledger:
309 """One run's charging state: which events it bills, what it has billed, and
310 whether it is still allowed to bill anything.
311
312 Configured once in main.py, then used from the route handlers through the
313 module-level `LEDGER` singleton - the same shape as `crash_reporting.REPORTER`,
314 and for the same reason: the handlers run concurrently and must share one
315 piece of state rather than each keeping their own.
316 """
317
318 def __init__(self) -> None:
319 self._events: dict[str, tuple[str, ...]] = {}
320 self._resolved: dict[str, str] = {}
321 self._prices: dict[str, Decimal] = {}
322 self._is_ppe = False
323 self._pricing_read_failed = False
324 self._key_of: Callable[[str, Row], Hashable | None] | None = None
325 self._resolved_pred: Callable[[str, Row], bool] | None = None
326 self._guard = RowGuard()
327 self._max_items: int | None = None
328 self._lock = asyncio.Lock()
329 self._seen: set[tuple[str, str, Hashable]] = set()
330 self._charged: Counter[str] = Counter()
331 self._unbilled: Counter[str] = Counter()
332 self._attempted: Counter[str] = Counter()
333 self._delivered_on: Counter[str] = Counter()
334 self._delivered_by_kind: Counter[str] = Counter()
335 self._roles: dict[str, str] = {}
336 self._counters: Counter[str] = Counter()
337 self._stop_reason: str | None = None
338 self._started = False
339 self._finished = False
340 self._report: Callable[[dict[str, Any]], Any] | None = None
341
342
343
344 def configure(
345 self,
346 *,
347 events: Mapping[str, str | Sequence[str]],
348 key_of: Callable[[str, Row], Hashable | None] | None = None,
349 resolved: Callable[[str, Row], bool] | None = None,
350 guard: RowGuard | None = None,
351 max_items: int | None = None,
352 report: Callable[[dict[str, Any]], Any] | None = None,
353 ) -> None:
354 """Declare the event map and the three gates that run before any charge.
355
356 `events` maps a kind (a row kind, a slice, a surcharge - any label the
357 handlers use) to the event name to charge, or to several names in
358 preference order. Several names is how a pricing switchover crosses its
359 own effective date with one build: the Actor charges the first name the
360 platform actually prices, so there is never a window where the name in the
361 code is not a name in `pricingInfos` (sofascore, 2026-10-21). An event
362 absent from the map bills NOTHING once per-class pricing is in force and
363 nothing in the run record reveals it, so `start()` names the gap
364 (marketmovers: `index-row` was priced for a kind the code could not emit).
365 """
366 normalised: dict[str, tuple[str, ...]] = {}
367 for kind, names in events.items():
368 candidates = (names,) if isinstance(names, str) else tuple(names)
369 for name in candidates:
370 if name.startswith(SYNTHETIC_PREFIX):
371 raise ValueError(
372 f"'{name}' is a synthetic platform event: it cannot be charged "
373 "from the Actor and cannot be capped from the Actor either. "
374 "Price a named event instead."
375 )
376 normalised[kind] = candidates
377 self._events = normalised
378 self._key_of = key_of
379 self._resolved_pred = resolved
380 self._guard = guard or RowGuard()
381 self._max_items = max_items if max_items and max_items > 0 else None
382
383
384
385
386 self._report = report
387
388 async def start(self) -> None:
389 """Resolve which events this run can actually bill. Call once, before the
390 first request: every later decision is a lookup, not an API call."""
391 self._started = True
392 try:
393 info = Actor.get_charging_manager().get_pricing_info()
394 self._is_ppe = bool(info.is_pay_per_event)
395 self._prices = dict(info.per_event_prices or {})
396 except Exception as exc:
397
398
399 self._pricing_read_failed = True
400 self._is_ppe = False
401 self._prices = {}
402 Actor.log.warning(f"Could not read pricing info; delivering unbilled: {exc}")
403 return
404
405 if not self._is_ppe:
406 Actor.log.info(
407 "Not a pay-per-event run (local, free, or a different pricing model): "
408 "every row is delivered unbilled."
409 )
410 return
411
412 priced = set(self._prices)
413 for kind, candidates in self._events.items():
414 for name in candidates:
415 if name in priced:
416 self._resolved[kind] = name
417 break
418 else:
419 Actor.log.warning(
420 f"No priced event for '{kind}' (tried {', '.join(candidates)}); "
421 "those rows will be delivered unbilled."
422 )
423 continue
424 if self._resolved[kind] != candidates[0]:
425 Actor.log.info(
426 f"'{kind}' bills the fallback event '{self._resolved[kind]}'; it switches "
427 f"to '{candidates[0]}' by itself once that is priced. No redeploy."
428 )
429 also_priced = [n for n in candidates[1:] if n in priced and n != self._resolved[kind]]
430 if also_priced:
431
432
433
434 Actor.log.warning(
435 f"'{kind}' resolves to '{self._resolved[kind]}' but "
436 f"{', '.join(also_priced)} {'is' if len(also_priced) == 1 else 'are'} "
437 "also priced - check the pricing entry does not bill this row twice."
438 )
439
440
441
442 def event_for(self, kind: str) -> str | None:
443 """The event this run charges for `kind`, or None when nothing is billable."""
444 return self._resolved.get(kind)
445
446 def billable(self, kind: str) -> bool:
447 return kind in self._resolved
448
449 @property
450 def started(self) -> bool:
451 """True once `start()` has read the pricing. A caller that finishes the audit from
452 a `finally` needs this: a run that never got as far as configuring billing has
453 nothing to report, and an audit claiming `payPerEvent: false` would be a lie about
454 a run that never asked."""
455 return self._started
456
457 @property
458 def stop_reason(self) -> str | None:
459 return self._stop_reason
460
461 @property
462 def delivered(self) -> int:
463 return sum(self._delivered_by_kind.values())
464
465 def should_enqueue(self) -> bool:
466 """Re-check before queueing follow-up work - a next page, a detail request.
467
468 The charge that spends the budget fires in the same pass that queues the
469 next request, so a handler that only checks before pushing queues work the
470 user can no longer be billed for.
471 """
472 return self._stop_reason is None
473
474
475
476 async def deliver(
477 self,
478 kind: str,
479 rows: Sequence[Row],
480 *,
481 scope: str = "",
482 slices: Sequence[Slice] = (),
483 surcharges: Sequence[str] = (),
484 ) -> Delivery:
485 """Dedupe, validate, charge and write `rows` - in that order, under one lock.
486
487 `scope` separates dedupe state between sibling walks that legitimately
488 return the same entity (booking's flexible-date search shared one scope and
489 each stay dropped the previous one's results). `slices` are charged before
490 the write and blanked if refused; `surcharges` are charged after it and can
491 never withhold.
492 """
493 if not self._started:
494 raise RuntimeError("Ledger.start() was not awaited before the first delivery")
495
496 async with self._lock:
497 if self._stop_reason is not None:
498 return Delivery(kind=kind, delivered=[], billed=0, stopped=self._stop_reason)
499
500 counts = {"unresolved": 0, "duplicates": 0, "invalid": 0, "trimmed": 0}
501 candidates: list[Row] = []
502 for row in rows:
503 if self._resolved_pred is not None and not self._resolved_pred(kind, row):
504
505
506
507 counts["unresolved"] += 1
508 continue
509 if self._key_of is not None:
510 key = self._key_of(kind, row)
511 if key is not None:
512 marker = (scope, kind, key)
513 if marker in self._seen:
514 counts["duplicates"] += 1
515 continue
516
517
518
519
520 self._seen.add(marker)
521 candidates.append(row)
522
523 if self._max_items is not None:
524 room = self._max_items - self.delivered
525 if room <= 0:
526 self._stop(STOP_MAX_ITEMS)
527 return Delivery(kind=kind, delivered=[], billed=0, stopped=self._stop_reason)
528 if len(candidates) > room:
529 counts["trimmed"] = len(candidates) - room
530 candidates = candidates[:room]
531
532 deliverable: list[Row] = []
533 for row in candidates:
534 reason = self._guard.reject_reason(row)
535 if reason is None:
536 deliverable.append(row)
537 continue
538 counts["invalid"] += 1
539
540
541 Actor.log.warning(f"Dropping a {kind} row the dataset would reject: {reason}")
542
543 for name, value in counts.items():
544 self._counters[name] += value
545
546 if not deliverable:
547 return Delivery(
548 kind=kind,
549 delivered=[],
550 billed=0,
551 stopped=self._stop_reason,
552 **counts,
553 )
554
555 deliverable, bound_by_budget, slice_budget = self._plan(kind, deliverable, slices)
556 if bound_by_budget:
557 counts["trimmed"] += bound_by_budget
558 self._counters["trimmed"] += bound_by_budget
559 self._counters["budget_trimmed"] += bound_by_budget
560 if not deliverable:
561 self._stop(STOP_CAP)
562 return Delivery(kind=kind, delivered=[], billed=0, stopped=self._stop_reason, **counts)
563
564 stripped = await self._charge_slices(deliverable, slices, slice_budget)
565 delivered, billed = await self._write(kind, deliverable)
566 if bound_by_budget:
567 self._stop(STOP_CAP)
568
569 self._delivered_by_kind[kind] += len(delivered)
570 event = self.event_for(kind)
571 if event is not None:
572 self._delivered_on[event] += len(delivered)
573 if self._max_items is not None and self.delivered >= self._max_items:
574 self._stop(STOP_MAX_ITEMS)
575
576 for surcharge in surcharges:
577 await self._charge_surcharge(surcharge, len(delivered))
578
579 return Delivery(
580 kind=kind,
581 delivered=delivered,
582 billed=billed,
583 stopped=self._stop_reason,
584 stripped=stripped,
585 **counts,
586 )
587
588 def _plan(
589 self, kind: str, rows: list[Row], slices: Sequence[Slice]
590 ) -> tuple[list[Row], int, Decimal | None]:
591 """Decide how many rows the base event can pay for, and reserve its money.
592
593 `push_data` truncates to what the BASE event's budget covers, which is
594 exactly right when the base event is the only charge. It is not enough once
595 a slice is charged ahead of the write: the slice spends budget the write was
596 going to need, so the write truncates and the slice has paid for a row
597 nobody receives - the over-bill 99co measured, reached by another route.
598
599 The order that cannot do that, and does not throw away a row the buyer can
600 still afford: size the batch on the base event alone, reserve exactly what
601 writing those rows will cost, and hand the slices only what is left over. A
602 row whose base is affordable therefore always ships; a slice that does not
603 fit blanks itself. Planning the row as one indivisible cost instead would
604 refuse the whole row - measured while porting this onto
605 social-blade-lookup, whose rows are a $0.015 lookup plus two $0.006
606 sections: a whole row is $0.027, so at a $0.022 cap the indivisible plan
607 delivers nothing where the buyer can afford the lookup and one section.
608
609 Returns the rows to deliver, how many were cut, and the budget the slices
610 may spend (None when the run is not billable, or when the budget could not
611 be read - in which case the write's own truncation is still a backstop).
612 """
613 base_event = self.event_for(kind)
614 if base_event is None or not rows:
615 return rows, 0, None
616 try:
617 manager = Actor.get_charging_manager()
618 keep = manager.compute_push_data_limit(
619 items_count=len(rows), event_name=base_event, is_default_dataset=True
620 )
621 remaining = manager.get_max_total_charge_usd() - manager.calculate_total_charged_amount()
622
623
624
625 per_row = self._prices.get(base_event, Decimal(0)) + self._prices.get(
626 SYNTHETIC_DATASET_ITEM, Decimal(0)
627 )
628 slice_budget = remaining - keep * per_row
629 if not slice_budget.is_finite():
630 slice_budget = None
631 else:
632 slice_budget = max(Decimal(0), slice_budget)
633 except Exception as exc:
634 Actor.log.warning(f"Could not plan the batch against the budget: {exc}")
635 return rows, 0, None
636 return rows[:keep], len(rows) - keep, slice_budget
637
638 async def _charge_slices(
639 self, rows: list[Row], slices: Sequence[Slice], budget: Decimal | None = None
640 ) -> dict[str, int]:
641 """Charge each slice for the rows that carry it; blank what was refused.
642
643 `budget` is what `_plan` left over after reserving the base event's money.
644 Charging past it would take the budget the write needs, so a slice is only
645 charged for as many rows as that leftover covers; the rest keep the row and
646 lose the part.
647
648 Only runs where the slice's event is actually priced. That gate is
649 load-bearing, not defensive: an unpriced name reports a count that proves
650 nothing, and trimming on it would strip every row's enrichment while the
651 legacy event billed for it (opentable, 2026-10-27).
652 """
653 stripped: dict[str, int] = {}
654 for part in slices:
655 carrying = [(row, part.units(row)) for row in rows if part.carries(row)]
656 owed = sum(units for _, units in carrying)
657 if not owed:
658 continue
659 event = self.event_for(part.kind)
660 if event is None:
661 continue
662 wanted = owed
663 price = self._prices.get(event, Decimal(0))
664 if budget is not None and price:
665 wanted = min(wanted, int(budget // price))
666 billed = await self._charge(event, wanted, role="slice") if wanted else 0
667 if budget is not None:
668 budget = max(Decimal(0), budget - billed * price)
669 if billed >= owed:
670 continue
671
672
673
674
675
676 left = billed
677 for row, units in carrying:
678 share = min(left, units)
679 left -= share
680 if share < units:
681 part.cut(row, share)
682 stripped[event] = stripped.get(event, 0) + (owed - billed)
683 self._counters[f"stripped:{event}"] += owed - billed
684 Actor.log.warning(
685 f"Charge for '{event}' was refused for {owed - billed} of {owed} unit(s); "
686 "the rows ship without that part rather than being given away."
687 )
688 return stripped
689
690 async def _charge_surcharge(self, kind: str, rows: int) -> None:
691 if rows <= 0:
692 return
693 event = self.event_for(kind)
694 if event is None:
695 return
696 billed = await self._charge(event, rows, role="surcharge")
697 if billed < rows:
698
699
700
701 Actor.log.warning(
702 f"'{event}' billed {billed} of {rows} delivered row(s) - the budget ran "
703 "out. Those rows were delivered; the surcharge was not charged."
704 )
705
706 async def _charge(self, event: str, count: int, *, role: str) -> int:
707 """A bare charge, for things that are not a dataset write.
708
709 `count` is keyword-only on SDK 4, so a positional `Actor.charge(EVENT, 1)`
710 dies after the first push - a run that works until it doesn't.
711 """
712 self._roles.setdefault(event, role)
713 self._attempted[event] += count
714 try:
715 result = await Actor.charge(event_name=event, count=count)
716 except Exception as exc:
717
718
719
720
721 self._counters["charge_failures"] += 1
722 Actor.log.warning(f"Charging '{event}' failed; treating it as unbilled: {exc}")
723 self._stop(STOP_CHANNEL)
724 return 0
725 self._charged[event] += result.charged_count
726 if result.event_charge_limit_reached:
727 self._stop(STOP_CAP)
728 return result.charged_count
729
730 async def _write(self, kind: str, rows: list[Row]) -> tuple[list[Row], int]:
731 """Write and charge in one act, and report only what the platform took.
732
733 `Actor.push_data(rows, charged_event_name=...)` holds the SDK's charge lock
734 across both, truncates the write to the remaining budget and charges
735 exactly what it wrote, so delivery can never outrun billing. The returned
736 `charged_count` IS the number of rows written.
737 """
738 event = self.event_for(kind)
739 if event is None:
740
741
742
743 await self._push(rows, None, kind)
744 return rows, 0
745
746 self._roles.setdefault(event, "base")
747 self._attempted[event] += len(rows)
748 result = await self._push(rows, event, kind)
749 self._charged[event] += result.charged_count
750 if result.charged_count < len(rows):
751 Actor.log.warning(
752 f"Charge cap: {result.charged_count} of {len(rows)} {kind} row(s) were "
753 "billed and written; the rest were neither."
754 )
755 if result.event_charge_limit_reached:
756 self._stop(STOP_CAP)
757 return rows[: result.charged_count], result.charged_count
758
759 async def _push(self, rows: list[Row], event: str | None, kind: str) -> Any:
760 """One write, retried once, without ever writing the same rows twice.
761
762 A charge is an API call and so is a write, so either can fail transiently -
763 and the atomic form does the write first, then the charge. Retrying blindly
764 would therefore double-write and double-charge whenever it was the CHARGE
765 that failed. The SDK's own counter tells the two apart: it is incremented
766 before the charge request is sent, so a count that moved means the write
767 already happened.
768 """
769 for attempt in (1, 2):
770 before = self._sdk_charged(event)
771 try:
772 if event is None:
773 await Actor.push_data(rows)
774 return None
775 return await Actor.push_data(rows, charged_event_name=event)
776 except Exception as exc:
777 written = self._sdk_charged(event) - before if event is not None else 0
778 if written > 0:
779
780
781
782 self._counters["charge_failures"] += 1
783
784
785
786
787 self._unbilled[event] += written
788 self._counters["written_unbilled"] += written
789 Actor.log.warning(
790 f"Charging '{event}' failed after {written} row(s) were written; they "
791 f"are delivered and may be unbilled: {exc}"
792 )
793 self._stop(STOP_CHANNEL)
794 raise BillingChannelError(f"charge failed after writing {kind} rows") from exc
795 if attempt == 1:
796 self._counters["write_retries"] += 1
797 Actor.log.warning(f"Writing {len(rows)} {kind} row(s) failed; retrying once: {exc}")
798 continue
799 self._counters["write_failures"] += 1
800 self._stop(STOP_CHANNEL)
801 raise BillingChannelError(f"could not write {kind} rows: {exc}") from exc
802 return None
803
804 @staticmethod
805 def _sdk_charged(event: str | None) -> int:
806 if event is None:
807 return 0
808 try:
809 return Actor.get_charging_manager().get_charged_event_count(event)
810 except Exception:
811 return 0
812
813 async def charge_once(self, kind: str) -> bool:
814 """A flat per-run fee. False means do no work: the fee could not be charged.
815
816 Used by the per-run-fee Actors (regex-helper, pd-katana, osint-jobs), where
817 running the whole job and then failing to bill it is the whole failure mode.
818 True when the run is not billable at all, so a local or free run still works.
819 """
820 event = self.event_for(kind)
821 if event is None:
822 return True
823 return await self._charge(event, 1, role="once") > 0
824
825 def _stop(self, reason: str) -> None:
826 """First reason wins: the cap being spent is not news once the channel is
827 broken, and the status message should name what actually stopped the run."""
828 if self._stop_reason is None:
829 self._stop_reason = reason
830
831
832
833 def _money(self, events: Mapping[str, Mapping[str, Any]]) -> dict[str, Any]:
834 """What this run should have billed, what the platform says it billed, and
835 whatever is left over when the two are subtracted.
836
837 `expectedUsd` is the ledger's own arithmetic: every charge it made, at the
838 price this run was given. `chargedUsd` is the SDK's running total, which also
839 counts the synthetic per-dataset-item event (charged by the platform on every
840 write, with no charge call of ours) and anything charged outside the ledger.
841 Naming the synthetic part explicitly is what makes the remainder meaningful:
842 an `unexplainedUsd` that is not zero is money this Actor cannot account for,
843 in either direction, and that is the thing worth a webhook.
844 """
845 money: dict[str, Any] = {
846 "expectedUsd": round(sum(data["estimatedUsd"] for data in events.values()), 6),
847 }
848 budget = self._budget()
849 money.update(budget)
850 if "chargedUsd" not in money:
851 return money
852 synthetic_price = self._prices.get(SYNTHETIC_DATASET_ITEM)
853 money["syntheticUsd"] = (
854 round(float(synthetic_price) * self.delivered, 6) if synthetic_price else 0.0
855 )
856 money["unexplainedUsd"] = round(
857 money["chargedUsd"] - money["expectedUsd"] - money["syntheticUsd"], 6
858 )
859 return money
860
861 def _budget(self) -> dict[str, Any]:
862 """The run's own money, as the platform sees it.
863
864 `estimatedUsd` per event is the ledger's arithmetic at whatever price this
865 run was given; this is the SDK's own running total and the cap it is
866 charged against, which is what the two should be reconciled to.
867
868 The price itself is NOT something an Actor computes. On a tier-priced
869 event the Apify platform resolves the buyer's plan rung before the run
870 starts and hands the Actor a flat `eventPriceUsd` in
871 APIFY_ACTOR_PRICING_INFO, so `per_event_prices` already carries the
872 discounted price for this buyer - measured 2026-10-29 on
873 social-blade-lookup, whose live entry prices `profile-lookup` only as a
874 tier table (FREE $0.024 ... DIAMOND $0.0127) and whose platform run read
875 exactly $0.015, the BRONZE rung. The rung's NAME is not exposed to the
876 Actor; the price that applies to this run is.
877 """
878 try:
879 manager = Actor.get_charging_manager()
880 cap = manager.get_max_total_charge_usd()
881 return {
882
883 "maxTotalChargeUsd": float(cap) if cap.is_finite() else None,
884 "chargedUsd": float(manager.calculate_total_charged_amount()),
885 }
886 except Exception:
887 return {}
888
889 def summary(self) -> dict[str, Any]:
890 events: dict[str, Any] = {}
891 for event in sorted(set(self._attempted) | set(self._charged) | set(self._unbilled)):
892 price = self._prices.get(event)
893 charged = self._charged[event]
894 events[event] = {
895 "role": self._roles.get(event, "base"),
896 "attempted": self._attempted[event],
897 "charged": charged,
898 "writtenUnbilled": self._unbilled[event] or None,
899 "deliveredRows": self._delivered_on.get(event) or None,
900 "priced": price is not None,
901 "priceUsd": float(price) if price is not None else None,
902 "estimatedUsd": round(float(price) * charged, 6) if price is not None else 0.0,
903 }
904 money = self._money(events)
905 return {
906 "payPerEvent": self._is_ppe,
907 "pricingReadFailed": self._pricing_read_failed,
908 "eventsByKind": {kind: self._resolved.get(kind) for kind in self._events},
909 "events": events,
910 "rowsDelivered": self.delivered,
911 "rowsByKind": dict(self._delivered_by_kind),
912 "counters": dict(self._counters),
913 "money": money,
914 "stopReason": self._stop_reason,
915 "findings": self._findings(events, money),
916 }
917
918 def _findings(
919 self, events: Mapping[str, Mapping[str, Any]], money: Mapping[str, Any] | None = None
920 ) -> list[str]:
921 """The reconciliation, stated as findings rather than left for arithmetic.
922
923 Rows > charges is a leak; charges > rows is an over-bill. Both directions
924 are defects, and on an uncapped run neither is visible - nothing truncates
925 - so the numbers go in the record for the capped run that will.
926 """
927 findings: list[str] = []
928
929 unexplained = (money or {}).get("unexplainedUsd") or 0.0
930 if self._is_ppe and abs(unexplained) > 0.005:
931 direction = "more than" if unexplained > 0 else "less than"
932 findings.append(
933 f"MONEY: the platform charged ${money['chargedUsd']:.4f}, which is "
934 f"${abs(unexplained):.4f} {direction} this run can account for "
935 f"(${money['expectedUsd']:.4f} of events it charged"
936 + (f" plus ${money['syntheticUsd']:.4f} of dataset items"
937 if money.get("syntheticUsd") else "")
938 + ")"
939 )
940 if self._is_ppe and not self._resolved and self._events:
941 findings.append(
942 "pay-per-event is on but none of the declared events is priced: "
943 "every row was delivered unbilled"
944 )
945 for event, data in events.items():
946 if data["writtenUnbilled"]:
947 findings.append(
948 f"LEAK: {data['writtenUnbilled']} row(s) were written on '{event}' while "
949 "the charge failed - delivered, possibly unbilled"
950 )
951 if not data["priced"] and data["charged"]:
952 findings.append(
953 f"'{event}' was charged {data['charged']}x while absent from the pricing "
954 "config: those charges billed USD 0"
955 )
956 rows = data["deliveredRows"]
957 if data["role"] == "base" and rows is not None:
958 if data["charged"] > rows:
959 findings.append(
960 f"OVER-BILL: '{event}' charged {data['charged']} for {rows} delivered row(s)"
961 )
962 elif self.billable_event(event) and data["charged"] < rows:
963 findings.append(
964 f"LEAK: {rows} row(s) delivered on '{event}' against {data['charged']} charged"
965 )
966 if data["role"] in {"slice", "surcharge"} and data["charged"] > data["attempted"]:
967
968
969
970
971 findings.append(
972 f"OVER-BILL: '{event}' charged {data['charged']} where {data['attempted']} "
973 "unit(s) were owed"
974 )
975 sdk = self._sdk_charged(event)
976 if sdk and sdk != data["charged"] + self._unbilled[event]:
977
978
979
980 findings.append(
981 f"'{event}': the SDK counted {sdk} charge(s), the ledger {data['charged']} - "
982 "something charged outside the ledger"
983 )
984 return findings
985
986 def billable_event(self, event: str) -> bool:
987 return event in self._prices
988
989 async def finish(self, *, set_status_message: bool = True) -> None:
990 """Log the audit, leave it in the key-value store, and explain a short run.
991
992 Nothing here may raise: it runs at the end of every run, including the ones
993 that are already failing.
994 """
995 if self._finished:
996
997
998
999
1000 return
1001 self._finished = True
1002 try:
1003 summary = self.summary()
1004 lines = [
1005 f"{'event':<24}{'role':<10}{'charged':>8}{'rows':>7}{'price':>11}{'est. USD':>10}"
1006 ]
1007 for event, data in summary["events"].items():
1008 price = "unpriced" if not data["priced"] else f"{data['priceUsd']:.6f}"
1009 rows = "-" if data["deliveredRows"] is None else str(data["deliveredRows"])
1010 lines.append(
1011 f"{event:<24}{data['role']:<10}{data['charged']:>8}{rows:>7}"
1012 f"{price:>11}{data['estimatedUsd']:>10.4f}"
1013 )
1014 counters = ", ".join(f"{k}={v}" for k, v in sorted(summary["counters"].items()) if v)
1015 Actor.log.info(
1016 "Billing audit for this run:\n"
1017 + "\n".join(lines)
1018 + f"\nrows delivered: {summary['rowsDelivered']}"
1019 + (
1020 f" | charged ${summary['money']['chargedUsd']:.4f}"
1021 + (
1022 f" of a ${summary['money']['maxTotalChargeUsd']:.4f} cap"
1023 if summary["money"].get("maxTotalChargeUsd") is not None
1024 else " (no cap on this run)"
1025 )
1026 if "chargedUsd" in summary["money"]
1027 else ""
1028 )
1029 + (f" ({counters})" if counters else "")
1030 + (f"\nstopped by: {summary['stopReason']}" if summary["stopReason"] else "")
1031 )
1032 for finding in summary["findings"]:
1033 Actor.log.warning(f"Billing audit: {finding}")
1034 await Actor.set_value(AUDIT_RECORD_KEY, summary)
1035 if summary["findings"]:
1036 await self._send_report(summary)
1037 if set_status_message and self._stop_reason in _STOP_MESSAGES:
1038 await Actor.set_status_message(
1039 _STOP_MESSAGES[self._stop_reason].format(rows=self.delivered)
1040 )
1041 except Exception as exc:
1042 Actor.log.warning(f"Could not write the billing audit: {exc}")
1043
1044 async def _send_report(self, summary: dict[str, Any]) -> None:
1045 """Hand the audit to whatever this Actor reports anomalies with.
1046
1047 A billing defect is the one failure nobody sees: the run SUCCEEDS, the user
1048 has their rows, and the only trace is a number in a record nobody opens. So
1049 it goes out the same way a crash does.
1050 """
1051 if self._report is None:
1052 return
1053 try:
1054 result = self._report(summary)
1055 if inspect.isawaitable(result):
1056 await result
1057 except Exception as exc:
1058 Actor.log.warning(f"Could not report the billing findings: {exc}")
1059
1060
1061
1062
1063LEDGER = Ledger()