pilot-fish 0.0.1__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.
pilot_fish/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from .monitor import Monitor
4
+ from .probe import Tap
5
+ from .sinks import JsonlSink
6
+
7
+ try:
8
+ __version__ = version("pilot-fish")
9
+ except PackageNotFoundError:
10
+ __version__ = "0.0.0"
11
+
12
+ __all__ = ["JsonlSink", "Monitor", "Tap"]
pilot_fish/monitor.py ADDED
@@ -0,0 +1,413 @@
1
+ import os
2
+ import sys
3
+ import sysconfig
4
+ import threading
5
+ import time
6
+ from itertools import count
7
+ from types import CodeType, FunctionType, MethodType
8
+
9
+ from .ring_buffer import SPSCRingBuffer
10
+
11
+ from .probe import Tap, TapMethod
12
+
13
+ from .registry import type_registry
14
+
15
+ TOOL_ID = sys.monitoring.PROFILER_ID
16
+ EVENTS = sys.monitoring.events
17
+
18
+ PY_START = type_registry.register_type("py_start")
19
+ PY_RETURN = type_registry.register_type("py_return")
20
+ PY_UNWIND = type_registry.register_type("py_unwind")
21
+ PY_YIELD = type_registry.register_type("py_yield")
22
+ PY_RESUME = type_registry.register_type("py_resume")
23
+ PY_THROW = type_registry.register_type("py_throw")
24
+ C_CALL = type_registry.register_type("c_call")
25
+ C_RETURN = type_registry.register_type("c_return")
26
+ C_RAISE = type_registry.register_type("c_raise")
27
+
28
+ _PYTHON_CALLABLE_TYPES = frozenset({FunctionType, MethodType, TapMethod})
29
+
30
+
31
+ def _library_prefixes() -> tuple[str, ...]:
32
+ install_paths = sysconfig.get_paths()
33
+ prefixes = set()
34
+ for path_name in ("stdlib", "platstdlib", "purelib", "platlib"):
35
+ path = install_paths.get(path_name)
36
+ if path:
37
+ prefixes.add(path.rstrip(os.sep) + os.sep)
38
+ prefixes.add(os.path.realpath(path).rstrip(os.sep) + os.sep)
39
+ return tuple(prefixes)
40
+
41
+ _LIBRARY_PREFIXES = _library_prefixes()
42
+
43
+
44
+ def _code_objects_of(cls) -> set[CodeType]:
45
+ return {
46
+ member.__code__
47
+ for base_class in cls.__mro__
48
+ for member in vars(base_class).values()
49
+ if isinstance(member, FunctionType)
50
+ }
51
+
52
+ class ThreadState:
53
+
54
+ __slots__ = ("call_stack", "drained", "push", "ring", "thread")
55
+
56
+ def __init__(self, ring_capacity: int):
57
+ self.call_stack: list[tuple[int, CodeType, int | None]] = []
58
+ self.ring: SPSCRingBuffer = SPSCRingBuffer(ring_capacity)
59
+ self.push = self.ring.push # the method itself, not a call to it
60
+ self.thread = threading.current_thread()
61
+ self.drained = threading.Event()
62
+
63
+ class Engine:
64
+
65
+ def __init__(self, monitor, sink, polling_interval=0.1):
66
+ self.monitor = monitor
67
+ self.sink = sink
68
+ self.polling_interval = polling_interval
69
+
70
+ self._stop_event = threading.Event()
71
+ self._thread = threading.Thread(target=self._run, name='pilot-fish', daemon=True)
72
+
73
+ self._code_ids: dict[CodeType, int] = {}
74
+
75
+ def start(self):
76
+ self._thread.start()
77
+
78
+ def stop(self):
79
+ self._stop_event.set()
80
+ self._thread.join()
81
+ self._drain_all()
82
+ self.sink.flush()
83
+
84
+ def _run(self):
85
+ self.monitor._thread_local.thread_state = None
86
+ while not self._stop_event.is_set():
87
+ self._drain_all()
88
+ self._stop_event.wait(self.polling_interval)
89
+
90
+ def _write_batch(self, thread_state: ThreadState, rows: list):
91
+ newly_seen_functions = []
92
+ encoded_rows = []
93
+ for kind, call_id, parent_id, code_object, bytecode_offset, timestamp, extra in rows:
94
+ code_id = self._code_ids.get(code_object)
95
+ if code_id is None:
96
+ code_id = self._code_ids[code_object] = len(self._code_ids) + 1
97
+ newly_seen_functions.append(
98
+ (
99
+ code_id,
100
+ code_object.co_qualname,
101
+ code_object.co_filename,
102
+ code_object.co_firstlineno,
103
+ )
104
+ )
105
+ encoded_rows.append((kind, call_id, parent_id, code_id, bytecode_offset, timestamp, extra))
106
+
107
+ if newly_seen_functions:
108
+ self.sink.write_batch(("codes", newly_seen_functions))
109
+ self.sink.write_batch(("events", thread_state.thread.name, encoded_rows))
110
+
111
+
112
+ def _drain_all(self):
113
+ with self.monitor._thread_states_lock:
114
+ thread_states = list(self.monitor._thread_states)
115
+ for thread_state in thread_states:
116
+ rows = thread_state.ring.drain()
117
+ if rows:
118
+ self._write_batch(thread_state, rows)
119
+
120
+
121
+ class Monitor:
122
+
123
+ def __init__(self, sink, tap: Tap | None = None, ring_capacity: int = 1 << 18):
124
+ self.ring_capacity = ring_capacity
125
+
126
+ self._thread_local = threading.local()
127
+ self._thread_states: list[ThreadState] = []
128
+ self._thread_states_lock = threading.Lock()
129
+ self._is_user_code_cache: dict[CodeType, bool] = {}
130
+ self._call_id_counter = count(1)
131
+ self._suspended_generator_calls: dict[int, tuple] = {}
132
+ self._callbacks: dict[int, object] = {}
133
+
134
+ self.tap = tap if tap is not None else Tap()
135
+
136
+ self._events = (
137
+ EVENTS.PY_START
138
+ | EVENTS.PY_RETURN
139
+ | EVENTS.PY_UNWIND
140
+ | EVENTS.PY_YIELD
141
+ | EVENTS.PY_RESUME
142
+ | EVENTS.PY_THROW
143
+ | EVENTS.CALL
144
+ )
145
+
146
+ self._excluded_code_objects = (
147
+ _code_objects_of(Monitor)
148
+ | _code_objects_of(ThreadState)
149
+ | _code_objects_of(Engine)
150
+ | _code_objects_of(SPSCRingBuffer)
151
+ | _code_objects_of(type(sink))
152
+ | _code_objects_of(Tap)
153
+ | _code_objects_of(TapMethod)
154
+ | self.tap.extension_code_objects
155
+ )
156
+ self.engine = Engine(self, sink)
157
+
158
+ def _is_user_code(self, code_object: CodeType) -> bool:
159
+
160
+ cached_answer = self._is_user_code_cache.get(code_object)
161
+ if cached_answer is not None:
162
+ return cached_answer
163
+
164
+ filename = code_object.co_filename
165
+ if code_object in self._excluded_code_objects:
166
+ is_user_code = False
167
+ elif filename.startswith("<"):
168
+ is_user_code = filename.startswith("<ipython-input")
169
+ elif (
170
+ "site-packages" in filename
171
+ or "dist-packages" in filename
172
+ or filename.startswith(_LIBRARY_PREFIXES)
173
+ ):
174
+ is_user_code = False
175
+ else:
176
+ is_user_code = True
177
+
178
+ self._is_user_code_cache[code_object] = is_user_code
179
+ return is_user_code
180
+
181
+ def _get_or_create_thread_state(self) -> ThreadState:
182
+
183
+ try:
184
+ return self._thread_local.thread_state
185
+ except AttributeError:
186
+ thread_state = ThreadState(self.ring_capacity)
187
+ self._thread_local.thread_state = thread_state
188
+ with self._thread_states_lock:
189
+ self._thread_states.append(thread_state)
190
+ return thread_state
191
+
192
+ def _build_callbacks(self) -> dict[int, object]:
193
+ thread_local = self._thread_local
194
+ cached_is_user_code = self._is_user_code_cache.get
195
+ is_user_code = self._is_user_code
196
+ get_or_create_thread_state = self._get_or_create_thread_state
197
+ next_call_id = self._call_id_counter.__next__
198
+ suspended_generator_calls = self._suspended_generator_calls
199
+ current_time_ns = time.perf_counter_ns
200
+ get_frame = sys._getframe
201
+ python_callable_types = _PYTHON_CALLABLE_TYPES
202
+ DISABLE = sys.monitoring.DISABLE
203
+
204
+ def on_py_start(code_object, bytecode_offset):
205
+
206
+ is_user = cached_is_user_code(code_object)
207
+ if is_user is None:
208
+ is_user = is_user_code(code_object)
209
+ if not is_user:
210
+ return DISABLE
211
+
212
+ try:
213
+ thread_state = thread_local.thread_state
214
+ except AttributeError:
215
+ thread_state = get_or_create_thread_state()
216
+ if thread_state is None:
217
+ return
218
+
219
+ call_stack = thread_state.call_stack
220
+ call_id = next_call_id()
221
+ parent_id = call_stack[-1][0] if call_stack else None
222
+ call_stack.append((call_id, code_object, None))
223
+
224
+ timestamp = current_time_ns()
225
+ thread_state.push((PY_START, call_id, parent_id, code_object, bytecode_offset, timestamp, None))
226
+
227
+ def on_py_return(code_object, bytecode_offset, return_value):
228
+
229
+ timestamp = current_time_ns()
230
+
231
+ try:
232
+ thread_state = thread_local.thread_state
233
+ except AttributeError:
234
+ thread_state = None
235
+ if thread_state is not None:
236
+ call_stack = thread_state.call_stack
237
+ if call_stack and call_stack[-1][1] is code_object:
238
+ call_id = call_stack.pop()[0]
239
+ thread_state.push((PY_RETURN, call_id, None, code_object, bytecode_offset, timestamp, None))
240
+ return
241
+
242
+ is_user = cached_is_user_code(code_object)
243
+ if is_user is None:
244
+ is_user = is_user_code(code_object)
245
+ if not is_user:
246
+ return DISABLE
247
+
248
+ def on_py_unwind(code_object, bytecode_offset, exception):
249
+
250
+ timestamp = current_time_ns()
251
+
252
+ try:
253
+ thread_state = thread_local.thread_state
254
+ except AttributeError:
255
+ return
256
+ if thread_state is None:
257
+ return
258
+
259
+ call_stack = thread_state.call_stack
260
+ if call_stack and call_stack[-1][1] is code_object:
261
+ call_id = call_stack.pop()[0]
262
+ exception_name = type(exception).__qualname__
263
+ thread_state.push((PY_UNWIND, call_id, None, code_object, bytecode_offset, timestamp, exception_name))
264
+
265
+ def on_py_yield(code_object, bytecode_offset, yielded_value):
266
+
267
+ timestamp = current_time_ns()
268
+
269
+ try:
270
+ thread_state = thread_local.thread_state
271
+ except AttributeError:
272
+ thread_state = None
273
+ if thread_state is not None:
274
+ call_stack = thread_state.call_stack
275
+ if call_stack and call_stack[-1][1] is code_object:
276
+ suspended_call = call_stack.pop()
277
+ generator_frame = get_frame(1)
278
+ suspended_generator_calls[id(generator_frame)] = suspended_call
279
+ thread_state.push((PY_YIELD, suspended_call[0], None, code_object, bytecode_offset, timestamp, None))
280
+ return
281
+
282
+ is_user = cached_is_user_code(code_object)
283
+ if is_user is None:
284
+ is_user = is_user_code(code_object)
285
+ if not is_user:
286
+ return DISABLE
287
+
288
+ def resume_generator_call(kind, code_object, bytecode_offset, extra):
289
+
290
+ generator_frame = get_frame(2)
291
+ suspended_call = suspended_generator_calls.pop(id(generator_frame), None)
292
+ if suspended_call is None:
293
+ return # the generator started before monitoring began
294
+
295
+ try:
296
+ thread_state = thread_local.thread_state
297
+ except AttributeError:
298
+ thread_state = get_or_create_thread_state()
299
+ if thread_state is None:
300
+ return
301
+
302
+ thread_state.call_stack.append(suspended_call)
303
+ timestamp = current_time_ns()
304
+ thread_state.push((kind, suspended_call[0], None, code_object, bytecode_offset, timestamp, extra))
305
+
306
+ def on_py_resume(code_object, bytecode_offset):
307
+
308
+ is_user = cached_is_user_code(code_object)
309
+ if is_user is None:
310
+ is_user = is_user_code(code_object)
311
+ if not is_user:
312
+ return DISABLE
313
+
314
+ resume_generator_call(PY_RESUME, code_object, bytecode_offset, None)
315
+
316
+ def on_py_throw(code_object, bytecode_offset, exception):
317
+
318
+ if cached_is_user_code(code_object):
319
+ exception_name = type(exception).__qualname__
320
+ resume_generator_call(PY_THROW, code_object, bytecode_offset, exception_name)
321
+
322
+ def on_call(code_object, bytecode_offset, called_object, first_argument):
323
+
324
+ is_user = cached_is_user_code(code_object)
325
+ if is_user is None:
326
+ is_user = is_user_code(code_object)
327
+ if not is_user:
328
+ return DISABLE # also silences C_RETURN and C_RAISE at this call site
329
+
330
+ if type(called_object) in python_callable_types:
331
+ return # PY_START records Python calls; can't DISABLE, the call site may call C later
332
+
333
+ try:
334
+ thread_state = thread_local.thread_state
335
+ except AttributeError:
336
+ thread_state = get_or_create_thread_state()
337
+ if thread_state is None:
338
+ return
339
+
340
+ call_stack = thread_state.call_stack
341
+ call_id = next_call_id()
342
+ parent_id = call_stack[-1][0] if call_stack else None
343
+ call_stack.append((call_id, code_object, bytecode_offset))
344
+
345
+ called_name = (
346
+ getattr(called_object, "__qualname__", None)
347
+ or getattr(called_object, "__name__", None)
348
+ or type(called_object).__qualname__
349
+ )
350
+ called_module = getattr(called_object, "__module__", None)
351
+ timestamp = current_time_ns()
352
+ thread_state.push((C_CALL, call_id, parent_id, code_object, bytecode_offset, timestamp, (called_name, called_module)))
353
+
354
+ def make_on_c_call_end(kind):
355
+
356
+ def on_c_call_end(code_object, bytecode_offset, called_object, first_argument):
357
+
358
+ timestamp = current_time_ns()
359
+
360
+ try:
361
+ thread_state = thread_local.thread_state
362
+ except AttributeError:
363
+ return
364
+ if thread_state is None:
365
+ return
366
+
367
+ call_stack = thread_state.call_stack
368
+ if call_stack:
369
+ call_id, call_code_object, call_site_offset = call_stack[-1]
370
+ if call_code_object is code_object and call_site_offset == bytecode_offset:
371
+ call_stack.pop()
372
+ thread_state.push((kind, call_id, None, code_object, bytecode_offset, timestamp, None))
373
+
374
+ return on_c_call_end
375
+
376
+ callbacks = {
377
+ EVENTS.PY_START: on_py_start,
378
+ EVENTS.PY_RETURN: on_py_return,
379
+ EVENTS.PY_UNWIND: on_py_unwind,
380
+ EVENTS.PY_YIELD: on_py_yield,
381
+ EVENTS.PY_RESUME: on_py_resume,
382
+ EVENTS.PY_THROW: on_py_throw,
383
+ EVENTS.CALL: on_call,
384
+ EVENTS.C_RETURN: make_on_c_call_end(C_RETURN),
385
+ EVENTS.C_RAISE: make_on_c_call_end(C_RAISE)
386
+ }
387
+ return callbacks
388
+
389
+ def __enter__(self):
390
+ current_tool_name = sys.monitoring.get_tool(TOOL_ID)
391
+ if current_tool_name is None:
392
+ sys.monitoring.use_tool_id(TOOL_ID, "pytap")
393
+ elif current_tool_name != "pytap":
394
+ raise RuntimeError(f"tool id {TOOL_ID} is already used by {current_tool_name!r}")
395
+
396
+ self._callbacks = self._build_callbacks()
397
+ for event, callback in self._callbacks.items():
398
+ sys.monitoring.register_callback(TOOL_ID, event, callback)
399
+ sys.monitoring.restart_events()
400
+ self.tap.monitor = self
401
+ sys.monitoring.set_events(TOOL_ID, self._events)
402
+ self.engine.start()
403
+ return self
404
+
405
+ def __exit__(self, exception_type, exception, traceback):
406
+ sys.monitoring.set_events(TOOL_ID, EVENTS.NO_EVENTS)
407
+ self.tap.monitor = None
408
+ for event in self._callbacks:
409
+ sys.monitoring.register_callback(TOOL_ID, event, None)
410
+ sys.monitoring.free_tool_id(TOOL_ID)
411
+
412
+ self.engine.stop()
413
+ return False
pilot_fish/probe.py ADDED
@@ -0,0 +1,57 @@
1
+ #%% Imports
2
+ import inspect
3
+ import time
4
+ from types import CodeType
5
+ from .registry import type_registry
6
+
7
+ #%% Create Classes
8
+
9
+ class TapMethod:
10
+
11
+ def __init__(self, tap, function):
12
+ self.tap = tap
13
+ self.function = function
14
+ self.type = type_registry.register_type(function.__name__)
15
+
16
+ def __call__(self, *args, **kwargs):
17
+ if self.tap.monitor is None:
18
+ return
19
+
20
+ value = self.function(*args, **kwargs)
21
+ self.tap._record(self.type, value)
22
+ return
23
+
24
+ class Tap:
25
+
26
+ def __init__(self):
27
+ self.monitor = None
28
+ self.extension_code_objects: set[CodeType] = set()
29
+ self.tapped_code_objects: set[CodeType] = set()
30
+
31
+ def __call__(self, function):
32
+ self.tapped_code_objects.add(inspect.unwrap(function).__code__)
33
+ return function
34
+
35
+ def extend(self, function):
36
+
37
+ function_name = function.__name__
38
+
39
+ if hasattr(Tap, function_name):
40
+ raise ValueError("Cannot name extension function after existing Tap function")
41
+
42
+ setattr(self, function_name, TapMethod(self, function))
43
+ self.extension_code_objects.add(inspect.unwrap(function).__code__)
44
+ return function
45
+
46
+ def _record(self, record_type: int, value):
47
+
48
+ try:
49
+ thread_state = self.monitor._thread_local.thread_state
50
+ except AttributeError:
51
+ return
52
+
53
+ if thread_state is None:
54
+ return
55
+
56
+ call_id, code_object, _ = thread_state.call_stack[-1]
57
+ thread_state.push((record_type, call_id, None, code_object, None, time.perf_counter_ns(), value))
pilot_fish/py.typed ADDED
File without changes
pilot_fish/registry.py ADDED
@@ -0,0 +1,30 @@
1
+ class TypeRegistry:
2
+
3
+ def __init__(self):
4
+ self.type_to_index: dict[str, int] = {}
5
+ self.index_to_type: dict[int, str] = {}
6
+ self.count = 0
7
+
8
+ def __len__(self) -> int:
9
+ return self.count
10
+
11
+ def __contains__(self, type_name: str) -> bool:
12
+ return type_name in self.type_to_index
13
+
14
+ def get_index(self, type_name: str) -> int:
15
+ return self.type_to_index[type_name]
16
+
17
+ def get_name(self, type_index: int) -> str:
18
+ return self.index_to_type[type_index]
19
+
20
+ def register_type(self, type_name: str) -> int:
21
+ if type_name in self.type_to_index:
22
+ return self.type_to_index[type_name]
23
+
24
+ idx = self.count
25
+ self.type_to_index[type_name] = idx
26
+ self.index_to_type[idx] = type_name
27
+ self.count += 1
28
+ return idx
29
+
30
+ type_registry = TypeRegistry()
@@ -0,0 +1,60 @@
1
+ import threading
2
+ from typing import Any
3
+
4
+
5
+ class SPSCRingBuffer:
6
+ def __init__(self, capacity):
7
+
8
+ if capacity <= 0 or capacity & (capacity - 1) != 0:
9
+ raise ValueError("Capacity must be a power of 2")
10
+
11
+ self._buffer = [None] * capacity
12
+ self._capacity = capacity
13
+ self._mask = capacity - 1
14
+
15
+ self._head = 0
16
+ self._tail = 0
17
+
18
+ self._head_fence = threading.Lock()
19
+ self._tail_fence = threading.Lock()
20
+
21
+ def push(self, item: Any) -> bool:
22
+
23
+ current_tail = self._tail
24
+
25
+ # Buffer is full of unread values
26
+ if self._head - current_tail >= self._capacity:
27
+ return False
28
+
29
+ head_index = self._head & self._mask
30
+ self._buffer[head_index] = item
31
+
32
+ self._head += 1
33
+
34
+ return True
35
+
36
+ def pop(self) -> Any | None:
37
+
38
+ current_head = self._head
39
+
40
+ # Buffer is empty, no values to read
41
+ if current_head - self._tail == 0:
42
+ return None
43
+
44
+ tail_index = self._tail & self._mask
45
+ item = self._buffer[tail_index]
46
+ self._buffer[tail_index] = None
47
+
48
+ self._tail += 1
49
+
50
+ return item
51
+
52
+
53
+ def drain(self) -> list:
54
+
55
+ head = self._head
56
+ tail = self._tail
57
+ buf, mask = self._buffer, self._mask
58
+ items = [buf[i & mask] for i in range(tail, head)]
59
+ self._tail = head
60
+ return items
pilot_fish/sinks.py ADDED
@@ -0,0 +1,25 @@
1
+ try:
2
+ import orjson
3
+
4
+ def _dumps(obj) -> bytes:
5
+ return orjson.dumps(obj, default=repr, option=orjson.OPT_APPEND_NEWLINE)
6
+ except ImportError:
7
+ import json
8
+
9
+ def _dumps(obj) -> bytes:
10
+ return (json.dumps(obj, default=repr, separators=(",", ":")) + "\n").encode()
11
+
12
+ class JsonlSink:
13
+ """One JSON array per line: ["codes", [...]] or ["events", thread, [...]]."""
14
+
15
+ def __init__(self, path):
16
+ self._f = open(path, "ab")
17
+
18
+ def write_batch(self, obj):
19
+ self._f.write(_dumps(obj)) # tuples → arrays
20
+
21
+ def flush(self):
22
+ self._f.flush()
23
+
24
+ def close(self):
25
+ self._f.close()
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: pilot-fish
3
+ Version: 0.0.1
4
+ Summary: A lightweight, zero-infrastructure python monitoring library that runs algongside your code. Tap functions to allow for custom telemetry.
5
+ Author: ShawnPatrick-Barhorst
6
+ Author-email: ShawnPatrick-Barhorst <shawnpatrick.barhorst@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Dist: orjson ; extra == 'fast'
10
+ Requires-Python: >=3.14
11
+ Project-URL: Repository, https://github.com/ShawnPatrick-Barhorst/pilot-fish
12
+ Provides-Extra: fast
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Pilot Fish
16
+
17
+ [![Python Version](https://img.shields.io/badge/python-3.14%2B-blue)](https://www.python.org/)
18
+ [![Package Manager](https://img.shields.io/badge/uv-supported-261230)](https://github.com/astral-sh/uv)
19
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
20
+
21
+ **Pilot Fish** is an extensible monitoring tool designed to run alongside your Python app, capturing every function call plus any custom data you choose to tap.
22
+
23
+
24
+
25
+ ---
26
+ ## Overview
27
+
28
+ Most monitoring tools assume you already have the infrastructure for them: a job queue with Flower, Prometheus to collect metrics, a SQL database to store it all. For a solo hobbyist that setup is rarely worth the effort, so most small projects end up with no monitoring at all.
29
+
30
+ Pilot Fish needs none of that. Wrap your code in a with block and it runs alongside your app, recording each of your functions to a local file. You can extend it with taps; small functions you write to record your own data.
31
+
32
+ ## Features
33
+
34
+ - **Zero infrastructure** — Impliment your monitor in less than 5 lines of code, without any pre-existing infrastructure.
35
+ - **Custom taps** — Collect custom telemetry by "tapping" a function and using it within your Monitor.
36
+ - **Thread-aware** — Works for multi-threaded applications on Python 3.14+, with or without the GIL.
37
+
38
+
39
+ ## Installation
40
+
41
+
42
+ Requires Python 3.14 or newer, regular or free-threaded.
43
+
44
+ ```bash
45
+ pip install pilot-fish
46
+ ```
47
+
48
+ or with uv:
49
+
50
+ ```bash
51
+ uv add pilot-fish
52
+ ```
53
+
54
+ ## Quickstart
55
+
56
+ ## Quick start
57
+
58
+ ### Without a tap
59
+
60
+ Wrap the part of your program you want to watch. Every call to your own functions is recorded to `trace.jsonl`.
61
+
62
+ ```python
63
+ from pilot_fish import Monitor, JsonlSink
64
+
65
+ with Monitor(JsonlSink("trace.jsonl")):
66
+ main()
67
+ ```
68
+
69
+ ### With a tap
70
+
71
+ A tap records your own data. Write a function that returns the value you care about, register it with `@tap.extend`, then call it through the tap anywhere in your code.
72
+
73
+ ```python
74
+ from pilot_fish import Monitor, JsonlSink, Tap
75
+
76
+ tap = Tap()
77
+
78
+ @tap.extend
79
+ def batch_size(batch):
80
+ return len(batch)
81
+
82
+ def process(batch):
83
+ tap.batch_size(batch)
84
+ ...
85
+
86
+ with Monitor(JsonlSink("trace.jsonl"), tap=tap):
87
+ process([1, 2, 3])
88
+ ```
89
+
90
+ Each value is recorded against the call it happened in: here, `3` is attached to the `process` call. Outside a `with Monitor(...)` block, `tap.batch_size(...)` does nothing, so taps can stay in your code.
91
+
92
+ Call taps from inside your functions, not directly in the `with` block.
93
+
94
+
95
+ ## License
96
+
97
+ Distributed under the Apache 2.0 License. See `LICENSE` for more information.
@@ -0,0 +1,11 @@
1
+ pilot_fish/__init__.py,sha256=GU05uvkY9aIHSqmtC_ijC1c7GJ6_WRUjGPR1_QWasPA,286
2
+ pilot_fish/monitor.py,sha256=IQMX-y8GFIFgpeVGEzsRfaWRqoTm0eSa4ixFANaFm_k,15362
3
+ pilot_fish/probe.py,sha256=X_QsSJuf08k33geR25k0w-LgZq9sKF50NWA3AphjYQM,1592
4
+ pilot_fish/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pilot_fish/registry.py,sha256=BsS1tODQAGPa6dYIYiuAu3hVoYDpNEM0s_r5mxGBKjw,844
6
+ pilot_fish/ring_buffer.py,sha256=0RclJC0EkKtvIgxv9GXKgiYjmBqgP6Dzb0v0LhwSYjk,1394
7
+ pilot_fish/sinks.py,sha256=iewX4ZHGzueNWa_3vjkE4327BPDGRWXicggqCA0iNt4,636
8
+ pilot_fish-0.0.1.dist-info/licenses/LICENSE,sha256=jO3bel7SU7bs3dblTN7Ake9nNQgMZUe4sJYXV3Kotbk,11352
9
+ pilot_fish-0.0.1.dist-info/WHEEL,sha256=f5fWSvWsg5Knq5GWa6t1nJIug0Tqo69GqAWD_9LbBKw,81
10
+ pilot_fish-0.0.1.dist-info/METADATA,sha256=xwd-QQmCTLzM7nV3qXTAjTSVyDRc8RS7X6cVQ7w1s4g,3164
11
+ pilot_fish-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.11.16
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Shawn-Patrick Barhorst
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.