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,371 @@
1
+ """Collects records in memory and sends them to the ingest endpoint in batches.
2
+
3
+ inference_tracker.init("https://<key>@<host>") # at startup, or before each request: see init()
4
+ inference_tracker.record(record) # the wrappers call this; never blocks, never raises
5
+ inference_tracker.flush() # send what's waiting now
6
+
7
+ Two ways to run:
8
+ - background=True (default): a thread sends every few seconds, or as soon as a batch is full.
9
+ For processes that keep running between requests (our fal apps, servers).
10
+ - background=False: no thread; records go out only on flush(). For runtimes that freeze the
11
+ process once the response is sent (Cloud Functions, Cloud Run's default, Lambda), where a
12
+ background thread can't be relied on. Use context(..., flush=True) to flush at the end of the work.
13
+
14
+ flush() runs in the app's request, so it is short: one try per batch, for at most flush_timeout
15
+ seconds (1 by default), and no waiting on a busy server (429, Retry-After, backoff): what isn't
16
+ through stays queued for the next flush. After a flush that didn't get everything through, flushes
17
+ are skipped for flush_pause seconds (60 by default), so a slow or down server costs one request a
18
+ second, not every request. The background thread and shutdown() keep retrying with growing waits.
19
+
20
+ Failures never reach the app. Every record ends up either delivered or in the log:
21
+ - A busy or broken server (429, 5xx, no answer) is retried with growing waits (or, in flush(), on
22
+ the next flush). A batch that still isn't through when time runs out stays at the front of the
23
+ queue for the next try, and is written once to the "inference_tracker" log as JSON lines
24
+ (`inference_tracker.unsent {...}`).
25
+ - A refused batch (any other 4xx) won't be accepted on a retry: it is logged and dropped.
26
+ - When the queue is full (the server has been down a long time), the oldest record is logged and dropped.
27
+ Every batch tells the server how many records weren't delivered since the last one that got
28
+ through (`lost`). Each record has its own id, so a record sent twice is stored once.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import atexit
34
+ import json
35
+ import logging
36
+ import os
37
+ import random
38
+ import threading
39
+ import time
40
+ from collections import deque
41
+ from collections.abc import Callable
42
+ from typing import Any
43
+ from urllib.parse import unquote, urlsplit
44
+
45
+ from . import _transport as transport
46
+ from ._record import Record
47
+ from ._version import __version__
48
+
49
+ logger = logging.getLogger("inference_tracker")
50
+
51
+ _SDK = {"name": "inference-tracker-python", "version": __version__}
52
+
53
+
54
+ class Client:
55
+ def __init__(
56
+ self,
57
+ url: str,
58
+ key: str,
59
+ app: str,
60
+ environment: str | None = None,
61
+ *,
62
+ background: bool = True,
63
+ batch_size: int = 100,
64
+ flush_interval: float = 5.0,
65
+ max_queue: int = 10_000,
66
+ retry_for: float = 60.0,
67
+ request_timeout: float = 10.0,
68
+ first_retry_delay: float = 1.0,
69
+ flush_timeout: float = 1.0,
70
+ flush_pause: float = 60.0,
71
+ post: Callable[..., transport.Result] = transport.post,
72
+ ):
73
+ self.url, self.key, self.app, self.environment = url, key, app, environment
74
+ self.batch_size, self.flush_interval, self.max_queue = batch_size, flush_interval, max_queue
75
+ self.retry_for, self.request_timeout, self.first_retry_delay = retry_for, request_timeout, first_retry_delay
76
+ self.flush_timeout, self.flush_pause = flush_timeout, flush_pause
77
+ self._post = post
78
+ self._paused_until = 0.0 # time.monotonic() before which flush() doesn't try: the last one failed
79
+ self._queue: deque[dict[str, Any]] = deque()
80
+ self._lock = threading.Lock() # guards the queue and the counter
81
+ self.lost = 0 # records not delivered since the last batch that got through (reported, then reset)
82
+ self._logged: set[str] = set() # ids already written to the log, so a retried batch isn't logged twice
83
+ self._wake = threading.Event()
84
+ self._stop = threading.Event()
85
+ self._thread: threading.Thread | None = None
86
+ if background:
87
+ self._thread = threading.Thread(target=self._run, name="inference_tracker", daemon=True)
88
+ self._thread.start()
89
+
90
+ # --- adding -------------------------------------------------------------------------
91
+
92
+ def record(self, record: Record) -> None:
93
+ try:
94
+ wire = record.to_wire()
95
+ with self._lock:
96
+ overflow = [self._queue.popleft()] if len(self._queue) >= self.max_queue else [] # oldest first
97
+ self._queue.append(wire)
98
+ full = len(self._queue) >= self.batch_size
99
+ self._drop(overflow)
100
+ if full:
101
+ self._wake.set()
102
+ except Exception:
103
+ logger.exception("inference_tracker: could not queue a record")
104
+
105
+ def pending(self) -> int:
106
+ with self._lock:
107
+ return len(self._queue)
108
+
109
+ # --- sending ------------------------------------------------------------------------
110
+
111
+ def flush(self, timeout: float | None = None) -> bool:
112
+ """Sends what's waiting, in the app's time: one try per batch, for at most `timeout` seconds
113
+ (flush_timeout when None), never waiting on a busy server. True when nothing is left. After a
114
+ flush that didn't get everything through, flushes are skipped (False) for flush_pause seconds:
115
+ the records stay queued for the next one."""
116
+ try:
117
+ if self.paused():
118
+ return self.pending() == 0
119
+ deadline = time.monotonic() + (self.flush_timeout if timeout is None else timeout)
120
+ done = self._drain(deadline=deadline, mode="flush")
121
+ if not done:
122
+ with self._lock:
123
+ self._paused_until = time.monotonic() + self.flush_pause
124
+ return done
125
+ except Exception:
126
+ logger.exception("inference_tracker: flush failed")
127
+ return False
128
+
129
+ def paused(self) -> bool:
130
+ """Whether flush() skips sending for now, after one that didn't get everything through."""
131
+ with self._lock:
132
+ return time.monotonic() < self._paused_until
133
+
134
+ def shutdown(self, timeout: float = 5.0) -> None:
135
+ """Stops the thread and sends what's left, retrying for up to `timeout` seconds."""
136
+ self._stop.set()
137
+ self._wake.set()
138
+ if self._thread is not None:
139
+ self._thread.join(timeout=1.0)
140
+ try:
141
+ self._drain(deadline=time.monotonic() + timeout, mode="shutdown")
142
+ except Exception:
143
+ logger.exception("inference_tracker: sending at shutdown failed")
144
+
145
+ def _run(self) -> None:
146
+ while not self._stop.is_set():
147
+ self._wake.wait(self.flush_interval)
148
+ self._wake.clear()
149
+ if self._stop.is_set():
150
+ return # shutdown() sends the rest
151
+ try:
152
+ self._drain(deadline=time.monotonic() + self.retry_for, mode="background")
153
+ except Exception:
154
+ logger.exception("inference_tracker: background send failed")
155
+
156
+ def _drain(self, deadline: float, mode: str) -> bool:
157
+ """mode: "flush" (one try per batch, no waiting), "background" (retries, stops on shutdown) or
158
+ "shutdown" (retries until the deadline)."""
159
+ while True:
160
+ if _left(deadline) <= 0:
161
+ return self.pending() == 0 # out of time: what's left stays queued
162
+ batch = self._take()
163
+ if not batch:
164
+ return True
165
+ if not self._send(batch, deadline, mode):
166
+ # Not sent in time: log it (once) and keep it at the front for the next try.
167
+ self._log_unsent(batch)
168
+ self._put_back(batch)
169
+ return False
170
+
171
+ def _send(self, batch: list[dict[str, Any]], deadline: float, mode: str) -> bool:
172
+ """True when the batch is done with (sent, or refused for good); False when time ran out (or, in a
173
+ flush, when the first try didn't get through)."""
174
+ delay = self.first_retry_delay
175
+ while True:
176
+ with self._lock:
177
+ lost = self.lost
178
+ body = {"sdk": _SDK, "app": self.app, "environment": self.environment, "lost": lost, "records": batch}
179
+ result = self._post(self.url, self.key, body, min(self.request_timeout, _left(deadline)))
180
+ if result.outcome == "sent":
181
+ with self._lock:
182
+ self.lost -= lost
183
+ self._logged.difference_update(w["id"] for w in batch)
184
+ self._paused_until = 0.0 # the server is back: flushes try again
185
+ return True
186
+ if result.outcome == "rejected":
187
+ logger.warning(
188
+ "inference_tracker: ingest refused a batch of %d records (HTTP %s)", len(batch), result.status
189
+ )
190
+ self._log_unsent(batch)
191
+ with self._lock:
192
+ self.lost += len(batch)
193
+ self._logged.difference_update(w["id"] for w in batch)
194
+ return True
195
+ if mode == "flush":
196
+ return False # in the app's request: never wait on a busy server, the next flush tries again
197
+ wait = result.retry_after if result.retry_after is not None else delay * random.uniform(1.0, 1.5)
198
+ if wait > _left(deadline):
199
+ return False
200
+ if mode == "background":
201
+ if self._stop.wait(wait): # shutting down: hand the batch back to shutdown's flush
202
+ return False
203
+ else:
204
+ time.sleep(wait)
205
+ delay = min(delay * 2, 30.0)
206
+
207
+ # --- queue helpers ------------------------------------------------------------------
208
+
209
+ def _take(self) -> list[dict[str, Any]]:
210
+ with self._lock:
211
+ return [self._queue.popleft() for _ in range(min(self.batch_size, len(self._queue)))]
212
+
213
+ def _put_back(self, batch: list[dict[str, Any]]) -> None:
214
+ with self._lock:
215
+ self._queue.extendleft(reversed(batch))
216
+ overflow = [self._queue.popleft() for _ in range(max(0, len(self._queue) - self.max_queue))]
217
+ self._drop(overflow)
218
+
219
+ def _drop(self, wires: list[dict[str, Any]]) -> None:
220
+ """Records leaving memory without being sent: logged so they can be recovered, and counted."""
221
+ if wires:
222
+ self._log_unsent(wires)
223
+ with self._lock:
224
+ self.lost += len(wires)
225
+ self._logged.difference_update(w["id"] for w in wires)
226
+
227
+ def _log_unsent(self, wires: list[dict[str, Any]]) -> None:
228
+ with self._lock:
229
+ new = [w for w in wires if w["id"] not in self._logged]
230
+ self._logged.update(w["id"] for w in new)
231
+ for wire in new:
232
+ logger.warning("inference_tracker.unsent %s", json.dumps(wire, separators=(",", ":")))
233
+
234
+
235
+ def _left(deadline: float) -> float:
236
+ return max(0.0, deadline - time.monotonic())
237
+
238
+
239
+ # --- the process-wide client ---------------------------------------------------------------
240
+
241
+ _client: Client | None = None
242
+ _NOT_YET = object()
243
+ _settings: Any = _NOT_YET # what the last init() was given: a client's values, or None for "nothing to send to"
244
+ _client_lock = threading.Lock()
245
+ # Called by flush() and shutdown() with their deadline, before sending: for wrappers whose provider SDK
246
+ # records a call on its own thread a moment after the call returns (litellm), so it is in this flush.
247
+ _before_flush: list[Callable[[float], None]] = []
248
+
249
+
250
+ # The whole setup in one string, like a Sentry DSN: "https://<key>@<host>", the address records go to with the
251
+ # key in it. Set in this variable, it wins over what the code passes.
252
+ DSN_ENV = "INFERENCE_TRACKER_DSN"
253
+ DEFAULT_PATH = "/api/ingest"
254
+
255
+
256
+ def parse_dsn(dsn: Any) -> tuple[str, str] | None:
257
+ """(url, key) from "https://<key>@<host>[/path]", None when it isn't one. The path is /api/ingest unless given."""
258
+ if not isinstance(dsn, str):
259
+ return None
260
+ try:
261
+ parts = urlsplit(dsn.strip())
262
+ if parts.scheme not in ("http", "https") or not parts.username or not parts.hostname or parts.password:
263
+ return None
264
+ host = parts.hostname + (f":{parts.port}" if parts.port else "")
265
+ path = parts.path if parts.path not in ("", "/") else DEFAULT_PATH
266
+ return f"{parts.scheme}://{host}{path}", unquote(parts.username)
267
+ except ValueError:
268
+ return None
269
+
270
+
271
+ def init(
272
+ url: str | None = None,
273
+ key: str | None = None,
274
+ app: str | None = None,
275
+ environment: str | None = None,
276
+ **options: Any,
277
+ ) -> Client | None:
278
+ """Starts sending.
279
+
280
+ inference_tracker.init("https://<key>@<host>", environment="prod")
281
+
282
+ The first argument is the string the product gives when a key is made: where records go, with the key in it.
283
+ INFERENCE_TRACKER_DSN, when set, wins over it, so it can be replaced without changing the code. Nothing else
284
+ from the environment changes where records go: an old INFERENCE_TRACKER_URL or INFERENCE_TRACKER_KEY is ignored.
285
+ The environment comes from INFERENCE_TRACKER_ENVIRONMENT when not passed.
286
+
287
+ The older form, init(url=..., key=..., app=...), works as before: there INFERENCE_TRACKER_URL and
288
+ INFERENCE_TRACKER_KEY win over what's passed, and INFERENCE_TRACKER_APP fills in the app. Without a url and key
289
+ (and, in the older form, an app) nothing is sent and every call stays a no-op.
290
+
291
+ Safe to call from several threads at once, and cheap to call again: with the same values it returns the
292
+ client already running, so an app can call it at the start of every request instead of keeping a flag of
293
+ its own. Other values replace the client (the old one sends what it has, without holding up the others)."""
294
+ global _client, _settings
295
+ attach = options.pop("attach", True)
296
+ env_dsn = os.environ.get(DSN_ENV)
297
+ dsn = parse_dsn(env_dsn) if env_dsn else None
298
+ if env_dsn and dsn is None:
299
+ logger.warning("inference_tracker: %s isn't a https://<key>@<host> string; ignored", DSN_ENV)
300
+ dsn = dsn or (parse_dsn(url) if key is None else None)
301
+ if dsn is not None:
302
+ url, key = dsn
303
+ app = app or os.environ.get("INFERENCE_TRACKER_APP") or "" # the key decides the project
304
+ else:
305
+ url = os.environ.get("INFERENCE_TRACKER_URL") or url
306
+ key = os.environ.get("INFERENCE_TRACKER_KEY") or key
307
+ app = app or os.environ.get("INFERENCE_TRACKER_APP")
308
+ environment = environment or os.environ.get("INFERENCE_TRACKER_ENVIRONMENT")
309
+ settings = (url, key, app, environment, options) if url and key and (app or dsn is not None) else None
310
+ with _client_lock:
311
+ if settings == _settings and (settings is None or _client is not None):
312
+ return _client # the same values again: nothing to do (and, without values, said once already)
313
+ old = _client
314
+ try:
315
+ _client = Client(url, key, app or "", environment, **options) if settings is not None else None # type: ignore[arg-type]
316
+ except Exception:
317
+ logger.exception("inference_tracker: could not start; records won't be sent")
318
+ _client = None
319
+ _settings = settings if _client is not None else None
320
+ new = _client
321
+ if settings is None:
322
+ logger.warning("inference_tracker: no address and key set; records won't be sent")
323
+ if old is not None:
324
+ old.shutdown() # outside the lock: calls that come meanwhile already see the new client
325
+ if new is not None and attach:
326
+ from . import _attach
327
+
328
+ _attach.attach()
329
+ return new
330
+
331
+
332
+ def active() -> bool:
333
+ """Whether records are being kept: the wrappers do nothing (read no answer, parse no body) when not."""
334
+ return _client is not None
335
+
336
+
337
+ def record(r: Record) -> None:
338
+ client = _client
339
+ if client is not None:
340
+ client.record(r)
341
+
342
+
343
+ def flush(timeout: float | None = None) -> bool:
344
+ """Sends what's waiting, briefly: see Client.flush. `timeout` defaults to init's flush_timeout (1 second)."""
345
+ client = _client
346
+ if client is None:
347
+ return True
348
+ timeout = client.flush_timeout if timeout is None else timeout
349
+ if not client.paused():
350
+ started = time.monotonic()
351
+ _wait_for_late_records(started + timeout / 2) # half of the time at most, the rest is for sending
352
+ timeout = max(timeout / 2, timeout - (time.monotonic() - started))
353
+ return client.flush(timeout)
354
+
355
+
356
+ def shutdown(timeout: float = 5.0) -> None:
357
+ client = _client
358
+ if client is not None:
359
+ _wait_for_late_records(time.monotonic() + timeout)
360
+ client.shutdown(timeout)
361
+
362
+
363
+ def _wait_for_late_records(deadline: float) -> None:
364
+ for hook in list(_before_flush):
365
+ try:
366
+ hook(deadline)
367
+ except Exception:
368
+ logger.exception("inference_tracker: waiting for records before a flush failed")
369
+
370
+
371
+ atexit.register(shutdown)
@@ -0,0 +1,64 @@
1
+ """Which of the app's functions made a call: the record's "code.functions".
2
+
3
+ ["app.features.suggest.prompt_suggestions", "app.handlers.on_request"] # nearest first
4
+
5
+ The chain is how the product tells calls apart, so names never need to be written in the code: two features
6
+ that share one helper differ in the next function up. The product shows a name given there, never these.
7
+
8
+ Only the app's own code counts: frames from the standard library, from installed packages (site-packages,
9
+ the provider SDKs among them) and from this library are skipped. Each frame is "module.function" (the
10
+ function's qualified name, so methods keep their class), never a file path, which differs per machine.
11
+ An app that is itself installed as a package (in site-packages) shows no chain.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import sys
18
+ import sysconfig
19
+ import threading
20
+ from types import FrameType
21
+
22
+ DEPTH = 5 # how many of the app's functions are kept
23
+
24
+ _HERE = os.path.dirname(os.path.abspath(__file__))
25
+ _NOT_APP: tuple[str, ...] = tuple(
26
+ {os.path.abspath(p) for k in ("stdlib", "platstdlib", "purelib", "platlib") if (p := sysconfig.get_paths().get(k))}
27
+ | {_HERE}
28
+ )
29
+ _known: dict[str, bool] = {}
30
+ _known_lock = threading.Lock()
31
+
32
+
33
+ def _is_app(filename: str) -> bool:
34
+ seen = _known.get(filename)
35
+ if seen is not None:
36
+ return seen
37
+ path = os.path.abspath(filename) if not filename.startswith("<") else ""
38
+ app = (
39
+ bool(path)
40
+ and not path.startswith(_NOT_APP)
41
+ and not any(part in ("site-packages", "dist-packages") for part in path.split(os.sep))
42
+ )
43
+ with _known_lock:
44
+ if len(_known) > 10_000:
45
+ _known.clear()
46
+ _known[filename] = app
47
+ return app
48
+
49
+
50
+ def functions(depth: int = DEPTH, frame: FrameType | None = None) -> list[str]:
51
+ """The app's functions on the current stack (or from `frame` up), nearest first. Never raises."""
52
+ out: list[str] = []
53
+ try:
54
+ f = frame if frame is not None else sys._getframe(1)
55
+ while f is not None and len(out) < depth:
56
+ code = f.f_code
57
+ if _is_app(code.co_filename):
58
+ module = f.f_globals.get("__name__") or "?"
59
+ name = getattr(code, "co_qualname", code.co_name) # Python 3.11+ keeps the class
60
+ out.append(f"{module}.{name}")
61
+ f = f.f_back
62
+ except Exception:
63
+ return out
64
+ return out
@@ -0,0 +1,98 @@
1
+ """Who a call is for: the user, the task, and the call that made it. And which call in the code it is.
2
+
3
+ Set once where work starts, read by every tracked call inside it:
4
+
5
+ with inference_tracker.context(user_id=uid, task_id=task.id):
6
+ ... # every tracked call in here is tagged with uid and task.id
7
+
8
+ A call made inside another call (a model called by one of our fal apps) names that call as its
9
+ parent, the way the provider's bill knows it: the provider and its request id.
10
+
11
+ with inference_tracker.context(parent_provider="fal", parent_request_id=rid):
12
+ ...
13
+
14
+ The server finds the user and task of such a call by walking up its parents, so the app inside
15
+ doesn't need to be told them.
16
+
17
+ Two places in the code can call the same model (an agent that plans an edit, and prompt suggestions,
18
+ both on one Gemini model). A name for the call tells their records apart, and gives cost per call:
19
+
20
+ with inference_tracker.context(call_name="prompt-suggestions"):
21
+ ...
22
+
23
+ Built on contextvars, so each asyncio task (and each request in a server that runs several at
24
+ once) keeps its own values. asyncio.to_thread copies them into the thread; a plain
25
+ ThreadPoolExecutor does not (use contextvars.copy_context().run).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import contextvars
31
+ from collections.abc import Generator
32
+ from contextlib import contextmanager
33
+ from dataclasses import dataclass, replace
34
+ from typing import Any
35
+
36
+ _MAX_LEN = 256
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Context:
41
+ user_id: str | None = None
42
+ task_id: str | None = None
43
+ # The call that made this one, as its provider knows it: "fal" and fal's request id, say.
44
+ parent_provider: str | None = None
45
+ parent_request_id: str | None = None
46
+ # Which call in the app's code this is, e.g. "prompt-suggestions". Set where the call is made.
47
+ call_name: str | None = None
48
+
49
+
50
+ _current: contextvars.ContextVar[Context] = contextvars.ContextVar("inference_tracker_context", default=Context()) # noqa: B039 (Context is frozen)
51
+ # Inside a context(flush=True) block: an inner block with flush=True leaves the flush to the outer one.
52
+ _flushing: contextvars.ContextVar[bool] = contextvars.ContextVar("inference_tracker_flushing", default=False)
53
+
54
+
55
+ def current() -> Context:
56
+ return _current.get()
57
+
58
+
59
+ @contextmanager
60
+ def context(
61
+ *,
62
+ user_id: Any = None,
63
+ task_id: Any = None,
64
+ parent_provider: Any = None,
65
+ parent_request_id: Any = None,
66
+ call_name: Any = None,
67
+ flush: bool = False,
68
+ ) -> Generator[Context, None, None]:
69
+ """Values left out are kept from the outer context. flush=True sends what's waiting when the
70
+ block ends: for runtimes that freeze the process after the response (see _client.py). Only the
71
+ outermost block with flush=True flushes: blocks inside it leave it to that one, so nesting them
72
+ costs one flush, not one per block."""
73
+ given = {
74
+ "user_id": user_id,
75
+ "task_id": task_id,
76
+ "parent_provider": parent_provider,
77
+ "parent_request_id": parent_request_id,
78
+ "call_name": call_name,
79
+ }
80
+ changes = {k: c for k, v in given.items() if v is not None and (c := _clean(v)) is not None}
81
+ token = _current.set(replace(_current.get(), **changes))
82
+ flushes = flush and not _flushing.get()
83
+ flushing = _flushing.set(True) if flushes else None
84
+ try:
85
+ yield _current.get()
86
+ finally:
87
+ if flushing is not None:
88
+ _flushing.reset(flushing)
89
+ _current.reset(token)
90
+ if flushes:
91
+ from ._client import flush as _flush
92
+
93
+ _flush()
94
+
95
+
96
+ def _clean(value: Any) -> str | None:
97
+ text = str(value).strip()[:_MAX_LEN]
98
+ return text or None