inference-tracker 0.9.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,842 @@
1
+ """Tracks calls made with fal's Python client (the fal_client package), sync or async.
2
+
3
+ import fal_client
4
+ import inference_tracker
5
+
6
+ client = inference_tracker.fal.track(fal_client.AsyncClient(key=...))
7
+ handle = await client.submit("fal-ai/kling-video/v2.6/pro/motion-control", arguments=args)
8
+ result = await handle.get()
9
+
10
+ The tracked client has every method of the one it wraps; what isn't listed below (upload, status,
11
+ cancel, stream, realtime...) passes through unchanged. The call itself is never changed. Tracking never
12
+ raises: a problem in it is logged and the call goes on as if nothing happened.
13
+
14
+ What is recorded, one record for each part of a call this process sees:
15
+
16
+ - submit(): a "start" record once fal has answered with the request id. When submit itself fails,
17
+ one "call" record with status "error" instead.
18
+ - The handle submit() returns: a "finish" record when the result is fetched with get(), when it is
19
+ fetched with client.result(application, request_id) for a request this process submitted, or when
20
+ the request is cancelled. status() and iter_events() don't finish a call (only the result says
21
+ whether it worked), but the metrics fal reports with the completed status go on the finish record.
22
+ - subscribe(): a "start" record when fal has queued the request, a "finish" record when it ends.
23
+ - run(): one "call" record, with the request id from fal's x-fal-request-id response header.
24
+ - webhook(body): the "finish" record of a call whose result fal sent to a webhook.
25
+
26
+ The server joins start and finish on provider + request id. A start without a finish is a call this
27
+ process never saw the end of: the result went to a webhook that doesn't call webhook(), or the app
28
+ gave up waiting.
29
+
30
+ When the app stops waiting (its task is cancelled, or a timeout around the wait runs out, fal_client's
31
+ client_timeout included), fal may still be running the request, and billing it: no finish is recorded,
32
+ and a request submitted here stays open, so a later client.result() (or webhook()) finishes it. A call
33
+ that never got a request id (cancelled during submit, or run()) is one "call" record with status
34
+ "cancelled".
35
+
36
+ Apps that call fal's HTTP API themselves (httpx, requests, or their own methods on a fal_client subclass)
37
+ use track_http(client) instead: the same records, read from the requests and answers. See track_http().
38
+
39
+ Settings: of the arguments, only those named in `settings` are copied, the ones that change the price
40
+ (resolution, duration, number of images...). Never the whole input: prompts and media URLs stay out.
41
+
42
+ Our own fal apps make calls of their own. In the app's endpoint, inside(self) makes the request the app
43
+ is serving the parent of every tracked call in the block.
44
+
45
+ Workflows: submitted with the header WORKFLOW_ENVELOPE_HEADER set to "true" (the app adds it; this module
46
+ never does), a fal workflow's result comes back as {output, nodes}, where nodes holds the endpoint and
47
+ request id of each step that ran. Each step then gets a "call" record with the run as its parent, from
48
+ webhook(body) and from a result fetched here with get(), client.result() or subscribe(). On a failed run
49
+ (seen only by webhook(): a failed result raises in fal_client), the step named by node_id failed and the
50
+ others that ran worked. A step that fell back to another model also gets a record for the failed attempt.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import contextvars
56
+ import inspect
57
+ import logging
58
+ import re
59
+ import threading
60
+ import time
61
+ from collections import OrderedDict
62
+ from collections.abc import Callable, Generator, Iterable, Mapping
63
+ from contextlib import contextmanager
64
+ from typing import Any
65
+
66
+ from . import _attach, _bypass, _client, _http
67
+ from ._context import Context, context, current
68
+ from ._record import Record, cancelled, code, error_name
69
+
70
+ logger = logging.getLogger("inference_tracker")
71
+
72
+ PROVIDER = "fal"
73
+ REQUEST_ID_HEADER = "x-fal-request-id"
74
+ # Sent as "true" on submit, it makes a workflow's result {output, nodes}. The app sends it, never this module.
75
+ WORKFLOW_ENVELOPE_HEADER = "X-Fal-Workflow-Envelope"
76
+
77
+ # Arguments copied onto the record because they change the price. Pass settings=[...] to track() for others.
78
+ SETTINGS = (
79
+ "resolution",
80
+ "aspect_ratio",
81
+ "duration",
82
+ "num_images",
83
+ "image_size",
84
+ "num_frames",
85
+ "generate_audio",
86
+ "enable_audio",
87
+ "quality",
88
+ )
89
+
90
+ # Requests this process submitted and hasn't seen the end of are remembered by request id, so that
91
+ # client.result(application, request_id) can finish them. Beyond this many, the oldest is forgotten.
92
+ MAX_OPEN = 1000
93
+
94
+
95
+ def track(client: Any, *, settings: Iterable[str] = SETTINGS) -> Any:
96
+ """Wraps a fal_client.SyncClient or fal_client.AsyncClient. See the module docstring."""
97
+ tracker = _Tracker(settings)
98
+ is_async = inspect.iscoroutinefunction(getattr(client, "submit", None))
99
+ return _AsyncClient(client, tracker) if is_async else _Client(client, tracker)
100
+
101
+
102
+ @contextmanager
103
+ def inside(app: Any) -> Generator[Context, None, None]:
104
+ """In one of our own fal apps: every tracked call in the block gets the fal request the app is serving
105
+ as its parent. `app` is the fal.App, so in an endpoint:
106
+
107
+ with inference_tracker.fal.inside(self):
108
+ return await self._inference(input)
109
+
110
+ The request id is read from app.current_request (as in fal 1.72). When there is none (the app runs
111
+ outside fal, or an older fal), the block runs as if inside() weren't there."""
112
+ request_id = _current_request_id(app)
113
+ if request_id is None:
114
+ logger.debug("inference_tracker: no current fal request, so calls in this block get no parent")
115
+ yield current()
116
+ return
117
+ with context(parent_provider=PROVIDER, parent_request_id=request_id) as ctx:
118
+ yield ctx
119
+
120
+
121
+ def _current_request_id(app: Any) -> str | None:
122
+ try:
123
+ request_id = getattr(getattr(app, "current_request", None), "request_id", None)
124
+ except Exception:
125
+ return None
126
+ return request_id if isinstance(request_id, str) and request_id else None
127
+
128
+
129
+ def webhook(body: Any, *, model: str | None = None) -> Record | None:
130
+ """Records the "finish" of a call whose result fal sent to a webhook. `body` is the webhook's JSON
131
+ body (request_id, status "OK" or "ERROR", payload...). The application isn't in it; pass `model`
132
+ when you know it, otherwise the server takes it from the start record. When the call is a workflow
133
+ run with its steps in the payload, each step gets a record too (see the module docstring). Call it
134
+ inside the user's context when the user is known. Returns the finish record, or None when the body
135
+ has no request id."""
136
+ try:
137
+ if not _client.active():
138
+ return None
139
+ request_id = body.get("request_id") if isinstance(body, Mapping) else None
140
+ if not isinstance(request_id, str) or not request_id:
141
+ return None
142
+ ok = body.get("status") == "OK"
143
+ record = Record.new(
144
+ PROVIDER,
145
+ model,
146
+ phase="finish",
147
+ request_id=request_id,
148
+ status="ok" if ok else "error",
149
+ error_type=None if ok else _webhook_error_type(body),
150
+ )
151
+ _client.record(record)
152
+ except Exception:
153
+ logger.exception("inference_tracker: could not record a fal webhook")
154
+ return None
155
+ _safe(_record_steps, body.get("payload"), request_id, error_type=record.error_type)
156
+ return record
157
+
158
+
159
+ def _webhook_error_type(body: Mapping[str, Any]) -> str:
160
+ """fal puts the failure in a `detail` list, [{type, msg, error_code, loc}]: under payload for an app,
161
+ deeper for a workflow (payload.error.body.detail). The code or type is taken, never the message."""
162
+ return _detail_code(body.get("payload")) or "error"
163
+
164
+
165
+ def _detail_code(data: Any) -> str | None:
166
+ first = _first_detail(data)
167
+ if first is not None:
168
+ for key in ("error_code", "type"):
169
+ if (found := code(first.get(key))) is not None:
170
+ return found
171
+ return None
172
+
173
+
174
+ def _first_detail(data: Any, depth: int = 0) -> Mapping[str, Any] | None:
175
+ """The first entry of the first `detail` list found in `data`, looking only through dicts. The depth
176
+ is capped so that a dict that holds itself can't loop."""
177
+ if not isinstance(data, Mapping) or depth > 20:
178
+ return None
179
+ details = data.get("detail")
180
+ if isinstance(details, list) and details and isinstance(details[0], Mapping):
181
+ return details[0]
182
+ for value in data.values():
183
+ if (found := _first_detail(value, depth + 1)) is not None:
184
+ return found
185
+ return None
186
+
187
+
188
+ # --- workflow steps --------------------------------------------------------------------------------
189
+
190
+
191
+ def _record_steps(result: Any, run_id: Any, *, error_type: str | None = None, **fields: Any) -> None:
192
+ """One "call" record for each step in a workflow result's `nodes`, with the run as parent. error_type
193
+ is given for a failed run: it goes on the step named by node_id. `fields` (user, task) go on every record."""
194
+ nodes = result.get("nodes") if isinstance(result, Mapping) else None
195
+ if not isinstance(nodes, Mapping) or not isinstance(run_id, str) or not run_id:
196
+ return
197
+ if error_type is None and "output" not in result:
198
+ return # a successful run's result has both; anything else is an app's own output
199
+ failed_node = result.get("node_id") if error_type else None
200
+ for key, node in nodes.items():
201
+ if not isinstance(node, Mapping):
202
+ continue
203
+ fallback = node.get("fallback")
204
+ if isinstance(fallback, Mapping): # the step's first model failed and another one did the step
205
+ # The reason is kept when it is a code; fal may put a sentence there, which could quote the input.
206
+ failed = code(fallback.get("reason")) or "fallback"
207
+ _record_step(fallback.get("failed_endpoint"), fallback.get("failed_request_id"), run_id, failed, fields)
208
+ step_error = error_type if key == failed_node else None
209
+ _record_step(node.get("endpoint"), node.get("request_id"), run_id, step_error, fields)
210
+
211
+
212
+ def _record_step(endpoint: Any, request_id: Any, run_id: str, error_type: str | None, fields: dict) -> None:
213
+ """A step without a request id can't be matched to the bill: it isn't recorded. The endpoint is kept as
214
+ fal gives it, case included."""
215
+ if not isinstance(request_id, str) or not request_id:
216
+ return
217
+ _client.record(
218
+ Record.new(
219
+ PROVIDER,
220
+ endpoint if isinstance(endpoint, str) else None,
221
+ request_id=request_id,
222
+ status="error" if error_type else "ok",
223
+ error_type=error_type,
224
+ parent_provider=PROVIDER,
225
+ parent_request_id=run_id,
226
+ **fields,
227
+ )
228
+ )
229
+
230
+
231
+ # --- one call ----------------------------------------------------------------------------------
232
+
233
+
234
+ class _Call:
235
+ """The record of one call while this process follows it."""
236
+
237
+ def __init__(
238
+ self,
239
+ application: str,
240
+ arguments: Mapping[str, Any],
241
+ settings: tuple[str, ...],
242
+ started: tuple[float, float] | None = None, # (unix seconds, time.monotonic()) when it was sent; now if None
243
+ ):
244
+ started_at, self._clock = started or (time.time(), time.monotonic())
245
+ self.record = Record.new(
246
+ PROVIDER,
247
+ application,
248
+ phase="start",
249
+ started_at=started_at,
250
+ settings={k: arguments[k] for k in settings if k in arguments},
251
+ )
252
+ self.units: dict[str, float] = {} # fal's metrics (inference_seconds) and billing headers
253
+ self.envelope = False # submitted over plain HTTP asking for a workflow's {output, nodes}
254
+ self.done = False
255
+
256
+ def submitted(self, request_id: str) -> None:
257
+ self.record.request_id = request_id
258
+ _client.record(self.record)
259
+
260
+ def saw(self, status: Any) -> None:
261
+ """A queue status answer. The completed one carries fal's metrics."""
262
+ if type(status).__name__ == "Completed":
263
+ self.saw_metrics(getattr(status, "metrics", None))
264
+
265
+ def saw_metrics(self, metrics: Any) -> None:
266
+ seconds = metrics.get("inference_time") if isinstance(metrics, Mapping) else None
267
+ if isinstance(seconds, (int, float)) and not isinstance(seconds, bool):
268
+ self.units["inference_seconds"] = float(seconds)
269
+
270
+ def finish(self, error_type: str | None, result: Any = None) -> None:
271
+ """`result` is what fal returned, for the steps of a workflow run."""
272
+ if self.done:
273
+ return
274
+ self.done = True
275
+ start = self.record
276
+ _client.record(
277
+ Record.new(
278
+ PROVIDER,
279
+ start.model,
280
+ phase="finish",
281
+ request_id=start.request_id,
282
+ status="error" if error_type else "ok",
283
+ error_type=error_type,
284
+ duration_s=self._elapsed(),
285
+ units=self._units(),
286
+ user_id=start.user_id,
287
+ task_id=start.task_id,
288
+ parent_provider=start.parent_provider,
289
+ parent_request_id=start.parent_request_id,
290
+ call_name=start.call_name,
291
+ )
292
+ )
293
+ if result is not None:
294
+ _record_steps(
295
+ result, start.request_id, user_id=start.user_id, task_id=start.task_id, call_name=start.call_name
296
+ )
297
+
298
+ def completed(self, request_id: str | None, error_type: str | None, stopped: bool = False) -> None:
299
+ """The whole call seen here (run(), or a submit that failed): one "call" record. `stopped`: the app
300
+ stopped waiting (see cancelled()), so the status is "cancelled", not "error"."""
301
+ if self.done:
302
+ return
303
+ self.done = True
304
+ r = self.record
305
+ r.phase, r.request_id = "call", request_id
306
+ r.status, r.error_type = ("cancelled" if stopped else "error" if error_type else "ok"), error_type
307
+ r.duration_s, r.units = self._elapsed(), self._units()
308
+ _client.record(r)
309
+
310
+ def _elapsed(self) -> float:
311
+ return round(time.monotonic() - self._clock, 3)
312
+
313
+ def _units(self) -> dict[str, float]:
314
+ return dict(self.units)
315
+
316
+
317
+ class _Tracker:
318
+ """Shared by the sync and async wrappers: starts calls and remembers the open ones."""
319
+
320
+ def __init__(self, settings: Iterable[str]):
321
+ self.settings = tuple(settings)
322
+ self._open: OrderedDict[str, _Call] = OrderedDict()
323
+ self._lock = threading.Lock()
324
+
325
+ def start(
326
+ self,
327
+ application: str,
328
+ arguments: Any,
329
+ *,
330
+ settings: Iterable[str] | None = None,
331
+ started: tuple[float, float] | None = None,
332
+ ) -> _Call | None:
333
+ """Before the call: its record. None without an active client: nothing is done for the call."""
334
+ if not _client.active():
335
+ return None
336
+ try:
337
+ arguments = arguments if isinstance(arguments, Mapping) else {}
338
+ return _Call(application, arguments, self.settings if settings is None else tuple(settings), started)
339
+ except Exception:
340
+ logger.exception("inference_tracker: could not start tracking a fal call")
341
+ return None
342
+
343
+ def submitted(self, call: _Call | None, request_id: str, *, keep: bool) -> None:
344
+ if call is None:
345
+ return
346
+ call.submitted(request_id)
347
+ if keep:
348
+ with self._lock:
349
+ self._open[request_id] = call
350
+ while len(self._open) > MAX_OPEN:
351
+ self._open.popitem(last=False)
352
+
353
+ def keep(self, call: _Call | None) -> None:
354
+ """Remembers a call that has its request id (and start record) but no finish yet."""
355
+ if call is None or not call.record.request_id or call.done:
356
+ return
357
+ with self._lock:
358
+ self._open[call.record.request_id] = call
359
+ while len(self._open) > MAX_OPEN:
360
+ self._open.popitem(last=False)
361
+
362
+ def take(self, request_id: Any) -> _Call | None:
363
+ with self._lock:
364
+ return self._open.pop(request_id, None)
365
+
366
+ def peek(self, request_id: Any) -> _Call | None:
367
+ with self._lock:
368
+ return self._open.get(request_id)
369
+
370
+ def finish(self, call: _Call | None, error_type: str | None, result: Any = None) -> None:
371
+ if call is not None:
372
+ self.take(call.record.request_id)
373
+ call.finish(error_type, result)
374
+
375
+
376
+ # --- the wrappers ----------------------------------------------------------------------------------
377
+
378
+
379
+ class _Handle:
380
+ """Stands in for fal's request handle: same attributes and methods, and the finish gets recorded."""
381
+
382
+ def __init__(self, handle: Any, call: _Call | None, tracker: _Tracker):
383
+ self._handle, self._call, self._tracker = handle, call, tracker
384
+
385
+ def __getattr__(self, name: str) -> Any:
386
+ return getattr(self._handle, name)
387
+
388
+ def status(self, **kwargs: Any) -> Any:
389
+ status = self._handle.status(**kwargs)
390
+ self._saw(status)
391
+ return status
392
+
393
+ def iter_events(self, **kwargs: Any) -> Any:
394
+ for status in self._handle.iter_events(**kwargs):
395
+ self._saw(status)
396
+ yield status
397
+
398
+ def get(self, **kwargs: Any) -> Any:
399
+ try:
400
+ result = self._handle.get(**kwargs)
401
+ except BaseException as e:
402
+ self._failed(e)
403
+ raise
404
+ _safe(self._tracker.finish, self._call, None, result)
405
+ return result
406
+
407
+ def cancel(self) -> None:
408
+ self._handle.cancel()
409
+ _safe(self._tracker.finish, self._call, "cancelled")
410
+
411
+ def _saw(self, status: Any) -> None:
412
+ if self._call is not None:
413
+ _safe(self._call.saw, status)
414
+
415
+ def _failed(self, error: BaseException) -> None:
416
+ if not cancelled(error): # the app stopped waiting: fal may still be running it, so no finish
417
+ _safe(self._tracker.finish, self._call, _error_type(error))
418
+
419
+
420
+ class _AsyncHandle(_Handle):
421
+ async def status(self, **kwargs: Any) -> Any:
422
+ status = await self._handle.status(**kwargs)
423
+ self._saw(status)
424
+ return status
425
+
426
+ async def iter_events(self, **kwargs: Any) -> Any:
427
+ async for status in self._handle.iter_events(**kwargs):
428
+ self._saw(status)
429
+ yield status
430
+
431
+ async def get(self, **kwargs: Any) -> Any:
432
+ try:
433
+ result = await self._handle.get(**kwargs)
434
+ except BaseException as e:
435
+ self._failed(e)
436
+ raise
437
+ _safe(self._tracker.finish, self._call, None, result)
438
+ return result
439
+
440
+ async def cancel(self) -> None:
441
+ await self._handle.cancel()
442
+ _safe(self._tracker.finish, self._call, "cancelled")
443
+
444
+
445
+ class _Client:
446
+ """Stands in for fal_client.SyncClient."""
447
+
448
+ _handle_class: type[_Handle] = _Handle
449
+
450
+ def __init__(self, client: Any, tracker: _Tracker):
451
+ self._client, self._tracker = client, tracker
452
+ self._watching = False # whether the response hook that reads request ids for run() is in place
453
+
454
+ def __getattr__(self, name: str) -> Any:
455
+ return getattr(self._client, name)
456
+
457
+ def submit(self, application: str, arguments: Any, **kwargs: Any) -> Any:
458
+ call = self._tracker.start(application, arguments)
459
+ try:
460
+ handle = self._client.submit(application, arguments, **kwargs)
461
+ except BaseException as e:
462
+ self._failed(call, e)
463
+ raise
464
+ # A result that goes to a webhook is finished by webhook(), not by this process.
465
+ self._submitted(call, handle, keep=kwargs.get("webhook_url") is None)
466
+ return self._handle_class(handle, call, self._tracker)
467
+
468
+ def subscribe(self, application: str, arguments: Any, **kwargs: Any) -> Any:
469
+ call = self._tracker.start(application, arguments)
470
+ kwargs["on_enqueue"] = self._on_enqueue(call, kwargs.get("on_enqueue"))
471
+ try:
472
+ result = self._client.subscribe(application, arguments, **kwargs)
473
+ except BaseException as e:
474
+ self._failed(call, e)
475
+ raise
476
+ _safe(self._tracker.finish, call, None, result)
477
+ return result
478
+
479
+ def run(self, application: str, arguments: Any, **kwargs: Any) -> Any:
480
+ call = self._tracker.start(application, arguments)
481
+ if not self._watching:
482
+ self._watching = True
483
+ _watch_request_ids(getattr(self._client, "_client", None), is_async=False)
484
+ token = _seen_request_id.set(None)
485
+ try:
486
+ result = self._client.run(application, arguments, **kwargs)
487
+ except BaseException as e:
488
+ self._ran(call, token, e)
489
+ raise
490
+ self._ran(call, token, None)
491
+ return result
492
+
493
+ def result(self, application: str, request_id: str) -> Any:
494
+ call = self._tracker.take(request_id)
495
+ try:
496
+ result = self._client.result(application, request_id)
497
+ except BaseException as e:
498
+ self._result_failed(call, e)
499
+ raise
500
+ _safe(self._tracker.finish, call, None, result)
501
+ return result
502
+
503
+ def get_handle(self, application: str, request_id: str) -> Any:
504
+ handle = self._client.get_handle(application, request_id)
505
+ return self._handle_class(handle, self._tracker.take(request_id), self._tracker)
506
+
507
+ def cancel(self, application: str, request_id: str) -> Any:
508
+ result = self._client.cancel(application, request_id)
509
+ _safe(self._tracker.finish, self._tracker.take(request_id), "cancelled")
510
+ return result
511
+
512
+ # --- shared steps ---
513
+
514
+ def _submitted(self, call: _Call | None, handle: Any, *, keep: bool) -> None:
515
+ _safe(self._tracker.submitted, call, getattr(handle, "request_id", None), keep=keep)
516
+
517
+ def _on_enqueue(self, call: _Call | None, user_callback: Callable[[str], None] | None) -> Callable[[str], None]:
518
+ def on_enqueue(request_id: str) -> None:
519
+ _safe(self._tracker.submitted, call, request_id, keep=False)
520
+ if user_callback is not None:
521
+ user_callback(request_id)
522
+
523
+ return on_enqueue
524
+
525
+ def _failed(self, call: _Call | None, error: BaseException) -> None:
526
+ """subscribe() or submit() raised: a call that never got a request id is one failed (or cancelled)
527
+ "call" record; one that did is finished with the error, or, when the app stopped waiting, left open
528
+ for a later result() to finish."""
529
+ if call is None:
530
+ return
531
+ if call.record.request_id is None:
532
+ _safe(call.completed, None, _error_type(error), cancelled(error))
533
+ elif cancelled(error):
534
+ _safe(self._tracker.keep, call)
535
+ else:
536
+ _safe(self._tracker.finish, call, _error_type(error))
537
+
538
+ def _result_failed(self, call: _Call | None, error: BaseException) -> None:
539
+ if cancelled(error):
540
+ _safe(self._tracker.keep, call) # still open: the result can be fetched again
541
+ else:
542
+ _safe(self._tracker.finish, call, _error_type(error))
543
+
544
+ def _ran(self, call: _Call | None, token: contextvars.Token, error: BaseException | None) -> None:
545
+ request_id = _seen_request_id.get()
546
+ _seen_request_id.reset(token)
547
+ if call is not None:
548
+ error_type = _error_type(error) if error is not None else None
549
+ _safe(call.completed, request_id, error_type, cancelled(error))
550
+
551
+
552
+ class _AsyncClient(_Client):
553
+ """Stands in for fal_client.AsyncClient."""
554
+
555
+ _handle_class = _AsyncHandle
556
+
557
+ async def submit(self, application: str, arguments: Any, **kwargs: Any) -> Any:
558
+ call = self._tracker.start(application, arguments)
559
+ try:
560
+ handle = await self._client.submit(application, arguments, **kwargs)
561
+ except BaseException as e:
562
+ self._failed(call, e)
563
+ raise
564
+ self._submitted(call, handle, keep=kwargs.get("webhook_url") is None)
565
+ return self._handle_class(handle, call, self._tracker)
566
+
567
+ async def subscribe(self, application: str, arguments: Any, **kwargs: Any) -> Any:
568
+ call = self._tracker.start(application, arguments)
569
+ kwargs["on_enqueue"] = self._on_enqueue(call, kwargs.get("on_enqueue"))
570
+ try:
571
+ result = await self._client.subscribe(application, arguments, **kwargs)
572
+ except BaseException as e:
573
+ self._failed(call, e)
574
+ raise
575
+ _safe(self._tracker.finish, call, None, result)
576
+ return result
577
+
578
+ async def run(self, application: str, arguments: Any, **kwargs: Any) -> Any:
579
+ call = self._tracker.start(application, arguments)
580
+ if not self._watching:
581
+ self._watching = True
582
+ http = getattr(self._client, "_client", None)
583
+ if inspect.isawaitable(http): # fal's async client builds its session on first use
584
+ try:
585
+ http = await http
586
+ except Exception:
587
+ http = None
588
+ _watch_request_ids(http, is_async=True)
589
+ token = _seen_request_id.set(None)
590
+ try:
591
+ result = await self._client.run(application, arguments, **kwargs)
592
+ except BaseException as e:
593
+ self._ran(call, token, e)
594
+ raise
595
+ self._ran(call, token, None)
596
+ return result
597
+
598
+ async def result(self, application: str, request_id: str) -> Any:
599
+ call = self._tracker.take(request_id)
600
+ try:
601
+ result = await self._client.result(application, request_id)
602
+ except BaseException as e:
603
+ self._result_failed(call, e)
604
+ raise
605
+ _safe(self._tracker.finish, call, None, result)
606
+ return result
607
+
608
+ async def get_handle(self, application: str, request_id: str) -> Any:
609
+ handle = await self._client.get_handle(application, request_id)
610
+ return self._handle_class(handle, self._tracker.take(request_id), self._tracker)
611
+
612
+ async def cancel(self, application: str, request_id: str) -> Any:
613
+ result = await self._client.cancel(application, request_id)
614
+ _safe(self._tracker.finish, self._tracker.take(request_id), "cancelled")
615
+ return result
616
+
617
+
618
+ # Calls these wrappers record themselves aren't recorded again by the HTTP tracking attached at init().
619
+ for _cls in (_Client, _AsyncClient, _Handle, _AsyncHandle):
620
+ _bypass.methods(_cls)
621
+
622
+
623
+ # --- over plain HTTP ---------------------------------------------------------------------------------
624
+
625
+ QUEUE_HOSTS = frozenset({"queue.fal.run", "queue.falrun.com"}) # with the backup domain fal_client falls back to
626
+ RUN_HOSTS = frozenset({"fal.run", "falrun.com"})
627
+ ERROR_TYPE_HEADER = "x-fal-error-type"
628
+ BILLABLE_UNITS_HEADER = "x-fal-billable-units" # fal's own billing count, when an answer carries it
629
+ # .../requests/<id>, .../requests/<id>/status, .../requests/<id>/cancel: the queue's URLs for one request
630
+ _REQUEST_PATH = re.compile(r"^/(?P<app>.+?)/requests/(?P<id>[^/]+)(?P<rest>/.*)?$")
631
+
632
+ # Requests submitted over plain HTTP and not finished yet, shared by every watched session: the result is
633
+ # often fetched with another session than the one that submitted.
634
+ _http_calls = _Tracker(SETTINGS)
635
+
636
+
637
+ def track_http(client: Any, *, settings: Iterable[str] = SETTINGS) -> Any:
638
+ """For apps that call fal's HTTP API themselves, without fal_client's methods. Watches the client's
639
+ answers from fal's hosts and returns the same client, of the same type:
640
+
641
+ http = inference_tracker.fal.track_http(httpx.Client()) # or httpx.AsyncClient, requests.Session
642
+
643
+ - POST https://queue.fal.run/<endpoint>: a "start" record with the request id from the answer
644
+ (not kept open when the URL has ?fal_webhook=...: webhook() records that finish).
645
+ - GET .../requests/<id>: the "finish" of a request submitted here, ok or with fal's error code, with
646
+ the inference time from a completed status seen before it and fal's x-fal-billable-units header
647
+ when the answer has it. An error answer that doesn't say what failed (no fal code, not a 5xx: the
648
+ request may still be running) leaves the request open. Submitted with the workflow envelope
649
+ header, the result's steps are recorded as with track().
650
+ - PUT .../requests/<id>/cancel, accepted: the finish, "cancelled".
651
+ - POST https://fal.run/<endpoint>: one "call" record with the request id from the x-fal-request-id
652
+ header.
653
+
654
+ Everything else (other hosts, status streams, uploads) passes through unseen. A failed answer's error
655
+ type is fal's code (x-fal-error-type, or the body's error_type or detail), else "http_<status>". A 5xx
656
+ without fal's request id header came from fal's gateway, not the app, and isn't recorded (fal_client
657
+ retries those). A request that gets no answer at all (a timeout, a broken connection) may still have
658
+ reached fal: a submit or run() without an answer is one "call" record with the exception's class name
659
+ as error type and no request id ("cancelled" when the app cancelled it); a status, result or cancel
660
+ request without one changes nothing (the request stays open).
661
+
662
+ A fal_client.SyncClient, or a subclass whose own methods call fal over HTTP, can be passed as it is:
663
+ its session is watched, so its SDK methods are recorded the same way. Use either track() or
664
+ track_http() on one client, not both, or calls are recorded twice. For a fal_client.AsyncClient (or a
665
+ subclass), whose session is made on first use, pass the session: track_http(await client._client)."""
666
+ watcher = _HttpWatcher(settings)
667
+ _attach.learn(watcher)
668
+ try:
669
+ if _http.watch(client, watcher):
670
+ return client
671
+ if inspect.iscoroutinefunction(getattr(client, "submit", None)):
672
+ logger.warning("inference_tracker: for a fal_client.AsyncClient, pass its session: await client._client")
673
+ return client
674
+ if not _http.watch(getattr(client, "_client", None), watcher): # fal_client.SyncClient's session
675
+ logger.warning("inference_tracker: can't watch a %s for fal calls", type(client).__name__)
676
+ except Exception:
677
+ logger.exception("inference_tracker: could not watch a client for fal calls")
678
+ return client
679
+
680
+
681
+ class _HttpWatcher:
682
+ name = "fal"
683
+
684
+ def __init__(self, settings: Iterable[str]):
685
+ self.settings = tuple(settings)
686
+
687
+ def accepts(self, host: str) -> bool:
688
+ return host in QUEUE_HOSTS or host in RUN_HOSTS
689
+
690
+ def wants_body(self, ex: _http.Exchange) -> bool:
691
+ kind, request_id, _ = _route(ex)
692
+ if kind == "submit":
693
+ return True # the request id is in it; a failed one says why
694
+ if kind == "run":
695
+ return not ex.ok or _asks_envelope(ex)
696
+ call = _http_calls.peek(request_id)
697
+ if kind == "status":
698
+ return call is not None and ex.ok
699
+ if kind == "result":
700
+ return call is not None and (not ex.ok or call.envelope)
701
+ return False
702
+
703
+ def seen(self, ex: _http.Exchange) -> None:
704
+ kind, request_id, model = _route(ex)
705
+ if kind == "submit":
706
+ self._submitted(ex, model)
707
+ elif kind == "run":
708
+ self._ran(ex, model)
709
+ elif kind == "status":
710
+ call = _http_calls.peek(request_id)
711
+ if call is not None and isinstance(ex.body, Mapping) and ex.body.get("status") == "COMPLETED":
712
+ call.saw_metrics(ex.body.get("metrics"))
713
+ elif kind == "result":
714
+ self._result(ex, _http_calls.peek(request_id))
715
+ elif kind == "cancel" and ex.ok:
716
+ _http_calls.finish(_http_calls.peek(request_id), "cancelled")
717
+
718
+ def failed(self, ex: _http.Exchange) -> None:
719
+ kind, _, model = _route(ex)
720
+ if kind in ("submit", "run") and (call := self._start(ex, model)) is not None:
721
+ call.completed(None, _http.error_type(ex), cancelled(ex.error))
722
+
723
+ def _start(self, ex: _http.Exchange, model: str) -> _Call | None:
724
+ arguments = ex.request_json() if self.settings else None # read only for the settings copied from it
725
+ return _http_calls.start(model, arguments, settings=self.settings, started=(ex.started_at, ex.clock))
726
+
727
+ def _submitted(self, ex: _http.Exchange, model: str) -> None:
728
+ if not ex.ok:
729
+ if _from_fal(ex) and (call := self._start(ex, model)) is not None:
730
+ call.completed(ex.headers.get(REQUEST_ID_HEADER), _http_error_type(ex) or f"http_{ex.status}")
731
+ return
732
+ request_id = ex.body.get("request_id") if isinstance(ex.body, Mapping) else None
733
+ if not isinstance(request_id, str) or not request_id:
734
+ return
735
+ call = self._start(ex, model)
736
+ if call is not None:
737
+ call.envelope = _asks_envelope(ex)
738
+ _http_calls.submitted(call, request_id, keep="fal_webhook" not in ex.query)
739
+
740
+ def _ran(self, ex: _http.Exchange, model: str) -> None:
741
+ if not ex.ok and not _from_fal(ex):
742
+ return
743
+ call = self._start(ex, model)
744
+ if call is None:
745
+ return
746
+ _billable_units(ex, call)
747
+ request_id = ex.headers.get(REQUEST_ID_HEADER)
748
+ call.completed(request_id, None if ex.ok else _http_error_type(ex) or f"http_{ex.status}")
749
+ if ex.ok and _asks_envelope(ex):
750
+ _safe(_record_steps, ex.body, request_id)
751
+
752
+ def _result(self, ex: _http.Exchange, call: _Call | None) -> None:
753
+ if call is None:
754
+ return # not submitted here (or already finished): nothing to finish
755
+ error_type = None if ex.ok else _http_error_type(ex)
756
+ if not ex.ok and error_type is None:
757
+ if ex.status < 500:
758
+ return # doesn't say the request failed: it may still be running
759
+ error_type = f"http_{ex.status}"
760
+ _billable_units(ex, call)
761
+ _http_calls.finish(call, error_type, ex.body if ex.ok and call.envelope else None)
762
+
763
+
764
+ def _route(ex: _http.Exchange) -> tuple[str | None, str | None, str]:
765
+ """What a request to fal's hosts was: ("submit" | "run" | "status" | "result" | "cancel" | None, the
766
+ request id in the URL, the endpoint in the URL)."""
767
+ if ex.host in RUN_HOSTS:
768
+ return "run", None, ex.path.strip("/")
769
+ match = _REQUEST_PATH.match(ex.path)
770
+ if match is None:
771
+ return ("submit" if ex.method == "POST" else None), None, ex.path.strip("/")
772
+ rest = (match["rest"] or "").rstrip("/")
773
+ kind = {("GET", ""): "result", ("GET", "/status"): "status", ("PUT", "/cancel"): "cancel"}.get((ex.method, rest))
774
+ return kind, match["id"], match["app"]
775
+
776
+
777
+ def _asks_envelope(ex: _http.Exchange) -> bool:
778
+ return str(ex.request_headers.get(WORKFLOW_ENVELOPE_HEADER, "")).lower() == "true"
779
+
780
+
781
+ def _from_fal(ex: _http.Exchange) -> bool:
782
+ """False for a 5xx that fal's gateway sent (no request id): the request never reached the app."""
783
+ return ex.status < 500 or REQUEST_ID_HEADER in ex.headers
784
+
785
+
786
+ def _http_error_type(ex: _http.Exchange) -> str | None:
787
+ """fal's code for a failed answer: the x-fal-error-type header, or the body's error_type or detail.
788
+ Never the message. None when the answer has none."""
789
+ found = code(ex.headers.get(ERROR_TYPE_HEADER))
790
+ if found is not None:
791
+ return found
792
+ body = ex.body
793
+ if isinstance(body, Mapping):
794
+ return code(body.get("error_type")) or _detail_code(body)
795
+ return None
796
+
797
+
798
+ def _billable_units(ex: _http.Exchange, call: _Call) -> None:
799
+ units = _http.header_number(ex.headers, BILLABLE_UNITS_HEADER)
800
+ if units is not None:
801
+ call.units["billable_units"] = units
802
+
803
+
804
+ # --- helpers ----------------------------------------------------------------------------------
805
+
806
+ # The request id fal's last answer carried, for run(), whose result has no id in it. Set by a response
807
+ # hook on the client's httpx session; per thread or task, like the context.
808
+ _seen_request_id: contextvars.ContextVar[str | None] = contextvars.ContextVar(
809
+ "inference_tracker_fal_request", default=None
810
+ )
811
+
812
+
813
+ def _watch_request_ids(http: Any, is_async: bool) -> None:
814
+ """Adds a response hook to fal's httpx session (the client's `_client`) that keeps the request id
815
+ header. Without a session that takes hooks, run() records without a request id."""
816
+ hooks = getattr(http, "event_hooks", None)
817
+ if not isinstance(hooks, Mapping):
818
+ return
819
+
820
+ def remember(response: Any) -> None:
821
+ _seen_request_id.set(response.headers.get(REQUEST_ID_HEADER))
822
+
823
+ async def remember_async(response: Any) -> None:
824
+ remember(response)
825
+
826
+ try:
827
+ http.event_hooks = {**hooks, "response": [*hooks.get("response", []), remember_async if is_async else remember]}
828
+ except Exception:
829
+ logger.debug("inference_tracker: could not watch fal's responses for request ids", exc_info=True)
830
+
831
+
832
+ def _error_type(error: BaseException) -> str:
833
+ """fal's error code when its exception carries one, else the exception's class name. Never a message."""
834
+ return code(getattr(error, "error_type", None)) or error_name(error)
835
+
836
+
837
+ def _safe(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
838
+ try:
839
+ return fn(*args, **kwargs)
840
+ except Exception:
841
+ logger.exception("inference_tracker: tracking a fal call failed")
842
+ return None