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,380 @@
1
+ """Tracks calls to our own Modal apps, made with the modal package or over HTTP to their web endpoints.
2
+
3
+ import inference_tracker
4
+
5
+ generate = inference_tracker.modal.function("video-app", "generate") # modal.Function.from_name, tracked
6
+ result = generate.remote(args) # or await generate.remote.aio(args)
7
+ call = generate.spawn(args); ...; result = call.get()
8
+
9
+ http = inference_tracker.modal.track_http(httpx.Client(), apps=["video-app"]) # web endpoints
10
+ http.post("https://acme--video-app-generate.modal.run/", json=args)
11
+
12
+ Modal bills machine time (GPU, CPU, memory) by app, not by call. Each record says which app and function
13
+ ran, when and for how long, so the server can split an app's bill over the calls that ran on it. The model
14
+ is "<app>/<function>" (a class method: "<app>/<Class>.<method>"), the Modal function call id ("fc-...") is
15
+ the request id. Nothing of the arguments or the result is recorded. The call itself is never changed, and
16
+ tracking never raises: a problem in it is logged and the call goes on as if nothing happened.
17
+
18
+ What is recorded:
19
+
20
+ - remote() / remote.aio(): one "call" record with the time it took and whether it raised (the exception's
21
+ class name). Without a request id: the modal package makes the function call id inside remote() and
22
+ doesn't hand it back. When the id matters (the function makes tracked calls of its own, which name it
23
+ as their parent), use spawn() and get(), which give it.
24
+ - spawn() / spawn.aio(): a "start" record with the FunctionCall's id. get() / get.aio() on what it returns
25
+ is the "finish" (a get(timeout=...) that times out while the call still runs isn't, nor a get the app
26
+ cancels or stops waiting for: the call goes on running on Modal); cancel() finishes it as "cancelled".
27
+ A FunctionCall fetched again by id (FunctionCall.from_id) in another process isn't
28
+ tracked: the start has no finish then.
29
+ - HTTP to a web endpoint (track_http): one "call" record per answer, with the id from Modal's
30
+ modal-function-call-id header. Long requests that Modal redirects (303) until the result is ready are
31
+ one record, from the first request to the final answer. A request that gets no answer (a timeout, a
32
+ broken connection) is one record too, with the exception's class name and no id: it may have run.
33
+
34
+ remote() or a web request the app stops waiting for (cancelled, or a timeout around it) is recorded with
35
+ status "cancelled", not "error".
36
+
37
+ map(), starmap(), for_each(), spawn_map() and remote_gen() pass through untracked.
38
+
39
+ Code running inside a Modal function that makes AI calls of its own: inside() makes the function call it is
40
+ serving the parent of every tracked call in the block.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import logging
46
+ import threading
47
+ import time
48
+ from collections import OrderedDict
49
+ from collections.abc import Callable, Generator, Iterable
50
+ from contextlib import contextmanager
51
+ from typing import Any
52
+ from urllib.parse import parse_qs, urlsplit
53
+
54
+ from . import _attach, _client, _http
55
+ from ._context import Context, context, current
56
+ from ._record import Record, cancelled, error_name
57
+
58
+ logger = logging.getLogger("inference_tracker")
59
+
60
+ PROVIDER = "modal"
61
+ CALL_ID_HEADER = "modal-function-call-id"
62
+ CALL_ID_PARAM = "__modal_function_call_id" # in the URL Modal redirects a long web request to
63
+ HOST_SUFFIX = ".modal.run"
64
+
65
+
66
+ def function(app_name: str, name: str, **kwargs: Any) -> Any:
67
+ """modal.Function.from_name(app_name, name, **kwargs), tracked as "<app_name>/<name>"."""
68
+ import modal
69
+
70
+ return track(modal.Function.from_name(app_name, name, **kwargs), f"{app_name}/{name}")
71
+
72
+
73
+ def track(fn: Any, model: str) -> Any:
74
+ """Wraps a modal.Function (or a method of a modal.Cls instance) so that remote() and spawn() are
75
+ recorded. `model` is "<app>/<function>", as Modal names them:
76
+
77
+ fn = modal.Function.from_name("video-app", "generate")
78
+ generate = inference_tracker.modal.track(fn, "video-app/generate")
79
+
80
+ upscaler = modal.Cls.from_name("video-app", "Upscaler")()
81
+ upscale = inference_tracker.modal.track(upscaler.run, "video-app/Upscaler.run")
82
+
83
+ Everything else is the function's own. with_options(gpu=...) gives a tracked function too, with the
84
+ GPU noted (it changes the price)."""
85
+ return _Function(fn, model, {})
86
+
87
+
88
+ @contextmanager
89
+ def inside(call_id: str | None = None) -> Generator[Context, None, None]:
90
+ """In a Modal function: every tracked call in the block gets the function call being served as its parent.
91
+
92
+ @app.function()
93
+ def generate(args):
94
+ with inference_tracker.modal.inside():
95
+ ...
96
+
97
+ The id is modal.current_function_call_id(), or `call_id` when given. When there is none (the code runs
98
+ outside Modal), the block runs as if inside() weren't there."""
99
+ call_id = call_id or _current_call_id()
100
+ if not call_id:
101
+ logger.debug("inference_tracker: no current Modal function call, so calls in this block get no parent")
102
+ yield current()
103
+ return
104
+ with context(parent_provider=PROVIDER, parent_request_id=call_id) as ctx:
105
+ yield ctx
106
+
107
+
108
+ def _current_call_id() -> str | None:
109
+ try:
110
+ import modal
111
+
112
+ call_id = modal.current_function_call_id()
113
+ except Exception:
114
+ return None
115
+ return call_id if isinstance(call_id, str) and call_id else None
116
+
117
+
118
+ # --- one call ----------------------------------------------------------------------------------
119
+
120
+
121
+ class _Call:
122
+ """The record of one call while this process follows it."""
123
+
124
+ def __init__(self, model: str | None, settings: dict[str, Any], started: tuple[float, float] | None = None):
125
+ started_at, self._clock = started or (time.time(), time.monotonic())
126
+ self.record = Record.new(PROVIDER, model, phase="start", started_at=started_at, settings=dict(settings))
127
+ self.done = False
128
+
129
+ def spawned(self, call_id: Any) -> None:
130
+ self.record.request_id = call_id if isinstance(call_id, str) and call_id else None
131
+ _client.record(self.record)
132
+
133
+ def finish(self, error_type: str | None) -> None:
134
+ if self.done:
135
+ return
136
+ self.done = True
137
+ start = self.record
138
+ _client.record(
139
+ Record.new(
140
+ PROVIDER,
141
+ start.model,
142
+ phase="finish",
143
+ request_id=start.request_id,
144
+ status="error" if error_type else "ok",
145
+ error_type=error_type,
146
+ duration_s=self._elapsed(),
147
+ user_id=start.user_id,
148
+ task_id=start.task_id,
149
+ parent_provider=start.parent_provider,
150
+ parent_request_id=start.parent_request_id,
151
+ call_name=start.call_name,
152
+ )
153
+ )
154
+
155
+ def completed(self, request_id: str | None, error_type: str | None, stopped: bool = False) -> None:
156
+ """The whole call seen here: one "call" record. `stopped`: the app stopped waiting, so "cancelled"."""
157
+ if self.done:
158
+ return
159
+ self.done = True
160
+ r = self.record
161
+ r.phase, r.request_id = "call", request_id
162
+ r.status, r.error_type = ("cancelled" if stopped else "error" if error_type else "ok"), error_type
163
+ r.duration_s = self._elapsed()
164
+ _client.record(r)
165
+
166
+ def _elapsed(self) -> float:
167
+ return round(time.monotonic() - self._clock, 3)
168
+
169
+
170
+ def _start(model: str, settings: dict[str, Any]) -> _Call | None:
171
+ if not _client.active():
172
+ return None
173
+ try:
174
+ return _Call(model, settings)
175
+ except Exception:
176
+ logger.exception("inference_tracker: could not start tracking a Modal call")
177
+ return None
178
+
179
+
180
+ # --- the wrappers ----------------------------------------------------------------------------------
181
+
182
+
183
+ class _Method:
184
+ """Stands in for one of modal's methods: called as it is, or awaited through .aio, like the original.
185
+ `before()` runs first; `after(state, result, error)` runs when the call returns (and gives back what the
186
+ app gets) or raises."""
187
+
188
+ def __init__(self, method: Any, before: Callable[[], Any], after: Callable[[Any, Any, BaseException | None], Any]):
189
+ self._method, self._before, self._after = method, before, after
190
+
191
+ def __getattr__(self, name: str) -> Any:
192
+ return getattr(self._method, name)
193
+
194
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
195
+ state = _safe(self._before)
196
+ try:
197
+ result = self._method(*args, **kwargs)
198
+ except BaseException as e:
199
+ _safe(self._after, state, None, e)
200
+ raise
201
+ return self._done(state, result)
202
+
203
+ async def aio(self, *args: Any, **kwargs: Any) -> Any:
204
+ state = _safe(self._before)
205
+ try:
206
+ result = await self._method.aio(*args, **kwargs)
207
+ except BaseException as e:
208
+ _safe(self._after, state, None, e)
209
+ raise
210
+ return self._done(state, result)
211
+
212
+ def _done(self, state: Any, result: Any) -> Any:
213
+ try:
214
+ return self._after(state, result, None)
215
+ except Exception:
216
+ logger.exception("inference_tracker: tracking a Modal call failed")
217
+ return result
218
+
219
+
220
+ class _Function:
221
+ """Stands in for a modal.Function: remote() and spawn() are recorded, the rest is the function's own."""
222
+
223
+ def __init__(self, function: Any, model: str, settings: dict[str, Any]):
224
+ self._function, self._model, self._settings = function, model, settings
225
+
226
+ def __getattr__(self, name: str) -> Any:
227
+ return getattr(self._function, name)
228
+
229
+ def __repr__(self) -> str:
230
+ return f"<tracked {self._function!r}>"
231
+
232
+ @property
233
+ def remote(self) -> _Method:
234
+ def after(call: _Call | None, result: Any, error: BaseException | None) -> Any:
235
+ if call is not None:
236
+ call.completed(None, None if error is None else error_name(error), cancelled(error))
237
+ return result
238
+
239
+ return _Method(self._function.remote, lambda: _start(self._model, self._settings), after)
240
+
241
+ @property
242
+ def spawn(self) -> _Method:
243
+ def after(call: _Call | None, function_call: Any, error: BaseException | None) -> Any:
244
+ if call is None:
245
+ return function_call
246
+ if error is not None: # never got a function call id: one failed (or cancelled) "call" record
247
+ call.completed(None, error_name(error), cancelled(error))
248
+ return None
249
+ call.spawned(getattr(function_call, "object_id", None))
250
+ return _FunctionCall(function_call, call)
251
+
252
+ return _Method(self._function.spawn, lambda: _start(self._model, self._settings), after)
253
+
254
+ def with_options(self, **options: Any) -> _Function:
255
+ settings = dict(self._settings)
256
+ if isinstance(options.get("gpu"), (str, list)):
257
+ settings["gpu"] = options["gpu"]
258
+ return _Function(self._function.with_options(**options), self._model, settings)
259
+
260
+
261
+ class _FunctionCall:
262
+ """Stands in for the modal.FunctionCall spawn() returns: get() and cancel() finish the call."""
263
+
264
+ def __init__(self, function_call: Any, call: _Call):
265
+ self._function_call, self._call = function_call, call
266
+
267
+ def __getattr__(self, name: str) -> Any:
268
+ return getattr(self._function_call, name)
269
+
270
+ def __repr__(self) -> str:
271
+ return f"<tracked {self._function_call!r}>"
272
+
273
+ @property
274
+ def get(self) -> _Method:
275
+ def after(_: Any, result: Any, error: BaseException | None) -> Any:
276
+ # modal's "no result yet" for get(timeout=...) (a TimeoutError), or the app cancelling the wait:
277
+ # the call is still running on Modal, so it isn't finished.
278
+ if cancelled(error):
279
+ return result
280
+ self._call.finish(None if error is None else error_name(error))
281
+ return result
282
+
283
+ return _Method(self._function_call.get, lambda: None, after)
284
+
285
+ @property
286
+ def cancel(self) -> _Method:
287
+ def after(_: Any, result: Any, error: BaseException | None) -> Any:
288
+ if error is None:
289
+ self._call.finish("cancelled")
290
+ return result
291
+
292
+ return _Method(self._function_call.cancel, lambda: None, after)
293
+
294
+
295
+ # --- over HTTP ---------------------------------------------------------------------------------------
296
+
297
+ # Long web requests: Modal answers 303 with the function call id until the result is ready. The first
298
+ # request's time is kept by call id until the final answer, which may come to another watched session;
299
+ # beyond this many, the oldest is forgotten.
300
+ MAX_OPEN = 1000
301
+ _redirected: OrderedDict[str, tuple[float, float]] = OrderedDict()
302
+ _redirected_lock = threading.Lock()
303
+
304
+
305
+ def track_http(client: Any, *, apps: Iterable[str] = ()) -> Any:
306
+ """Watches an httpx.Client, httpx.AsyncClient or requests.Session for calls to Modal web endpoints
307
+ (https://<workspace>--<label>.modal.run/...) and returns the same client. One "call" record per call.
308
+
309
+ Modal names a web endpoint's host "<app>-<function>" (the label), which can't be split where both have
310
+ dashes: list the app names in `apps` and the model is "<app>/<function>"; a host that starts with none
311
+ of them (a custom label) keeps the label as its model. A trailing "-dev" (modal serve) is dropped."""
312
+ try:
313
+ watcher = _HttpWatcher(apps)
314
+ _attach.learn(watcher)
315
+ if not _http.watch(client, watcher):
316
+ logger.warning("inference_tracker: can't watch a %s for Modal calls", type(client).__name__)
317
+ except Exception:
318
+ logger.exception("inference_tracker: could not watch a client for Modal calls")
319
+ return client
320
+
321
+
322
+ class _HttpWatcher:
323
+ name = "modal"
324
+
325
+ def __init__(self, apps: Iterable[str]):
326
+ # Longest first, so "video-app-v2" wins over "video-app".
327
+ self.apps = sorted({a for a in apps if isinstance(a, str) and a}, key=len, reverse=True)
328
+
329
+ def accepts(self, host: str) -> bool:
330
+ return host.endswith(HOST_SUFFIX)
331
+
332
+ def wants_body(self, ex: _http.Exchange) -> bool:
333
+ return False
334
+
335
+ def failed(self, ex: _http.Exchange) -> None:
336
+ call_id = _param(ex.query) # a redirected request's call id, in its URL
337
+ with _redirected_lock:
338
+ started = _redirected.pop(call_id, None) if call_id else None
339
+ call = _Call(self.model(ex.host), {}, started or (ex.started_at, ex.clock))
340
+ call.completed(call_id, _http.error_type(ex), cancelled(ex.error))
341
+
342
+ def seen(self, ex: _http.Exchange) -> None:
343
+ call_id = ex.headers.get(CALL_ID_HEADER) or _param(ex.query)
344
+ if 300 <= ex.status < 400:
345
+ call_id = call_id or _param(parse_qs(urlsplit(ex.headers.get("location") or "").query))
346
+ if call_id: # not done yet: the final answer comes from the URL Modal redirects to
347
+ with _redirected_lock:
348
+ _redirected.setdefault(call_id, (ex.started_at, ex.clock))
349
+ while len(_redirected) > MAX_OPEN:
350
+ _redirected.popitem(last=False)
351
+ return
352
+ with _redirected_lock:
353
+ started = _redirected.pop(call_id, None) if call_id else None
354
+ call = _Call(self.model(ex.host), {}, started or (ex.started_at, ex.clock))
355
+ call.completed(call_id or None, None if ex.ok else f"http_{ex.status}")
356
+
357
+ def model(self, host: str) -> str:
358
+ label = host[: -len(HOST_SUFFIX)].partition("--")[2] or host[: -len(HOST_SUFFIX)]
359
+ label = label.removesuffix("-dev")
360
+ for app in self.apps:
361
+ prefix = app.lower() + "-"
362
+ if label.startswith(prefix) and len(label) > len(prefix):
363
+ return f"{app}/{label[len(prefix) :]}"
364
+ return label
365
+
366
+
367
+ def _param(query: dict[str, list[str]]) -> str | None:
368
+ values = query.get(CALL_ID_PARAM)
369
+ return values[0] if values and values[0] else None
370
+
371
+
372
+ # --- helpers ----------------------------------------------------------------------------------
373
+
374
+
375
+ def _safe(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
376
+ try:
377
+ return fn(*args, **kwargs)
378
+ except Exception:
379
+ logger.exception("inference_tracker: tracking a Modal call failed")
380
+ return None