svkt 0.1.0__tar.gz
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.
- svkt-0.1.0/LICENSE +21 -0
- svkt-0.1.0/PKG-INFO +312 -0
- svkt-0.1.0/README.md +283 -0
- svkt-0.1.0/pyproject.toml +38 -0
- svkt-0.1.0/setup.cfg +4 -0
- svkt-0.1.0/svkt/__init__.py +226 -0
- svkt-0.1.0/svkt/_clock.py +237 -0
- svkt-0.1.0/svkt/_core.py +1916 -0
- svkt-0.1.0/svkt/_discovery.py +308 -0
- svkt-0.1.0/svkt/_encode.py +540 -0
- svkt-0.1.0/svkt/_lock.py +152 -0
- svkt-0.1.0/svkt/_logging.py +54 -0
- svkt-0.1.0/svkt/_proto.py +179 -0
- svkt-0.1.0/svkt/_save.py +456 -0
- svkt-0.1.0/svkt/_server.py +702 -0
- svkt-0.1.0/svkt/_sysinfo.py +310 -0
- svkt-0.1.0/svkt/_wsgi.py +118 -0
- svkt-0.1.0/svkt.egg-info/PKG-INFO +312 -0
- svkt-0.1.0/svkt.egg-info/SOURCES.txt +31 -0
- svkt-0.1.0/svkt.egg-info/dependency_links.txt +1 -0
- svkt-0.1.0/svkt.egg-info/top_level.txt +1 -0
- svkt-0.1.0/tests/test_asyncio.py +249 -0
- svkt-0.1.0/tests/test_chrome.py +209 -0
- svkt-0.1.0/tests/test_decoder.py +165 -0
- svkt-0.1.0/tests/test_discovery.py +326 -0
- svkt-0.1.0/tests/test_overhead.py +75 -0
- svkt-0.1.0/tests/test_protocol.py +537 -0
- svkt-0.1.0/tests/test_robustness.py +1743 -0
- svkt-0.1.0/tests/test_save.py +239 -0
- svkt-0.1.0/tests/test_stream.py +767 -0
- svkt-0.1.0/tests/test_tiers.py +275 -0
- svkt-0.1.0/tests/test_version.py +55 -0
- svkt-0.1.0/tests/test_wsgi.py +110 -0
svkt-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stefan van Kessel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
svkt-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: svkt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SVKT tracing: pure-Python producer client (live streaming, multi-tier history, Chrome JSON export)
|
|
5
|
+
Author: Stefan van Kessel
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/StefanVK/svk_tracing
|
|
8
|
+
Project-URL: Documentation, https://github.com/StefanVK/svk_tracing/blob/master/python/README.md
|
|
9
|
+
Project-URL: Repository, https://github.com/StefanVK/svk_tracing
|
|
10
|
+
Project-URL: Issues, https://github.com/StefanVK/svk_tracing/issues
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
22
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
23
|
+
Classifier: Topic :: Software Development :: Debuggers
|
|
24
|
+
Classifier: Topic :: System :: Monitoring
|
|
25
|
+
Requires-Python: >=3.8
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# svkt (Python producer client)
|
|
31
|
+
|
|
32
|
+
Pure-Python (>= 3.8, standard library only) producer for the SVKT tracing
|
|
33
|
+
framework. It records zones, instants, counters, messages, frames and
|
|
34
|
+
program-flow arrows into a shared multi-tier in-memory history, streams them
|
|
35
|
+
live to the SVKT viewer over TCP, and saves snapshots as native `.svkt` files
|
|
36
|
+
or Chrome Trace Event JSON (Perfetto UI / chrome://tracing). Project and
|
|
37
|
+
viewer: [github.com/StefanVK/svk_tracing](https://github.com/StefanVK/svk_tracing);
|
|
38
|
+
wire format: [docs/PROTOCOL.md](https://github.com/StefanVK/svk_tracing/blob/master/docs/PROTOCOL.md);
|
|
39
|
+
component design: [docs/DESIGN.md](https://github.com/StefanVK/svk_tracing/blob/master/docs/DESIGN.md)
|
|
40
|
+
section 5.
|
|
41
|
+
|
|
42
|
+
Version 0.1 (`svkt.__version__`, kept equal to the C++ library's version and
|
|
43
|
+
checked by a test): the API, the wire protocol and the file format may change
|
|
44
|
+
before 1.0. The flow functions (`flow_begin`, `flow_step`, `flow_end`) are
|
|
45
|
+
provisional, like their C++ and C counterparts: their names may change.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import svkt
|
|
49
|
+
|
|
50
|
+
svkt.init(process_name="inspection") # TCP 127.0.0.1:47474 (+15 probing), local registry
|
|
51
|
+
|
|
52
|
+
with svkt.zone("load_image", path=p) as z: # kwargs become args
|
|
53
|
+
img = load(p)
|
|
54
|
+
z.arg("bytes", len(img))
|
|
55
|
+
|
|
56
|
+
@svkt.traced # sync and async functions
|
|
57
|
+
def detect(img): ...
|
|
58
|
+
|
|
59
|
+
@svkt.traced("infer", level=svkt.IMPORTANT)
|
|
60
|
+
async def infer(img): ...
|
|
61
|
+
|
|
62
|
+
svkt.instant("trigger", level=svkt.IMPORTANT, line=3)
|
|
63
|
+
svkt.plot("queue_depth", q.qsize())
|
|
64
|
+
svkt.message("camera reconnected", level=svkt.CRITICAL)
|
|
65
|
+
svkt.warn("exposure clipped", gain=g) # severity WARNING, level CRITICAL
|
|
66
|
+
svkt.error_message("grab failed: timeout") # severity ERROR, level CRITICAL
|
|
67
|
+
svkt.frame("camera0")
|
|
68
|
+
|
|
69
|
+
fid = svkt.new_flow_id() # program flow across threads/processes
|
|
70
|
+
with svkt.zone("enqueue") as z:
|
|
71
|
+
z.flow_begin(fid)
|
|
72
|
+
queue.put((img, fid))
|
|
73
|
+
# ... elsewhere:
|
|
74
|
+
with svkt.zone("process") as z:
|
|
75
|
+
z.flow_end(fid)
|
|
76
|
+
|
|
77
|
+
svkt.save() # <save dir>/<process>_<pid>_<UTC>.svkt
|
|
78
|
+
svkt.export_chrome_json("trace.json")
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Recording calls are cheap no-ops before `init()` and after `shutdown()`
|
|
82
|
+
(`stats()` returns `{}`, `port()` 0). `save()` and `export_chrome_json()` raise
|
|
83
|
+
`RuntimeError` then; otherwise they return the path written. (The C++ library
|
|
84
|
+
can still save its retained data after `shutdown()`.)
|
|
85
|
+
|
|
86
|
+
## API
|
|
87
|
+
|
|
88
|
+
| Function | Notes |
|
|
89
|
+
|---|---|
|
|
90
|
+
| `init(process_name=None, port=47474, **options)` | Starts recording + the `svkt-server` thread. Options: `bind_address` ("127.0.0.1": this machine only; "0.0.0.0" or an interface address to listen on the network, see ["Remote access"](https://github.com/StefanVK/svk_tracing/blob/master/README.md#remote-access) in the main README; "" is refused like an address that cannot be bound: recording without a server, one stderr line), `port_range` (16), `port=0` (ephemeral), `enable_server`, `enable_discovery` (local registry file), `discovery_multicast` (True), `tiers`, `min_level`, `stream_interval_ms`, `max_live_records` (per consumer), `max_consumers` (4; 1..64), `allow_remote_save`, `allow_remote_save_from_network`, `save_directory`, `save_max_files`, `save_max_bytes`. Returns False if already active. |
|
|
91
|
+
| `shutdown()` | Sends remaining live data + Goodbye, stops the server, removes the registry file. Also registered with `atexit`. |
|
|
92
|
+
| `zone(name, level=NORMAL, color=0, severity=INFO, **args)` | Context manager (`with` / `async with`). Methods: `arg(k, v)`, `set_name(n)`, `severity(s)` (marks the zone `WARNING` / `ERROR` like the `severity` keyword, keeps its level; the last call wins), `flow_begin/step/end(fid)` (all chainable). Exceptions escaping the block are recorded as arg `exception` (`"ValueError: msg"`) and re-raised. |
|
|
93
|
+
| `traced` / `traced("name", level=..., color=...)` | Decorator for sync and `async def` functions (generator functions are returned unchanged). |
|
|
94
|
+
| `instant`, `plot`, `message`, `frame` | Point events, counters, log text (`LoggingHandler` forwards `logging`), frame boundaries. All default to level `NORMAL`; `frame(name="frame", level=NORMAL)` differs from C++ `SVKT_FRAME`, which always records at `Important` (pass `level=svkt.IMPORTANT` to keep frames where a C++ producer's are kept). |
|
|
95
|
+
| `warn(name, level=CRITICAL, color=0, **args)`, `error(...)`, `warn_message(text, level=CRITICAL, color=0)`, `error_message(...)` | Instants / messages with severity `WARNING` / `ERROR`. Level `CRITICAL` by default, so they survive tier demotion; an explicit `level` wins, and the level filters (`min_level`, tiers, stream level) apply as to any record. `instant(..., severity=...)` and `message(..., severity=...)` set a severity at any level (so `severity` is not an arg name there). `LoggingHandler` maps `WARNING` to severity `WARNING`, `ERROR` / `CRITICAL` to `ERROR`, all three at level `CRITICAL`. |
|
|
96
|
+
| `flow_begin(flow_id=None, name=None, level=NORMAL)`, `flow_step(flow_id, ...)`, `flow_end(flow_id, ...)` | Standalone flow points bound to the innermost open zone of the current context. `flow_begin()` without an id creates one and returns it (also before `init()`, like `new_flow_id()`); `flow_step` / `flow_end` with `None` record nothing and return `None`. |
|
|
97
|
+
| `new_flow_id()` | PROTOCOL 5.4 normative formula (`splitmix64(instance_id) + counter * 0x9E3779B97F4A7C15`). |
|
|
98
|
+
| `save(path=None)`, `export_chrome_json(path)` | Snapshots of all tiers + open zones + clock log; run on the calling thread. Return the path written; raise `RuntimeError` before `init()` and after `shutdown()`. |
|
|
99
|
+
| `wsgi_middleware(app)` | One zone per request (method, path, query, status, remote_addr). Flask: `app.wsgi_app = svkt.wsgi_middleware(app.wsgi_app)`. Header `X-SVKT-Flow: <id>` ends that flow in the request zone. |
|
|
100
|
+
| `set_system_info(key, value)` | Adds a line to the SystemInfo (PROTOCOL 4), e.g. `set_system_info("version", "2.3.1")` or the configuration in use: shown with the machine in the viewer and `svkt info`, kept in saves and Chrome exports. Works before `init()`, from any thread, and across `shutdown()` / `init()`. An existing key keeps its place and takes the new value; an empty value (or `None`) removes the key; a connected viewer gets the change at once. Returns False for an empty key, a machine key (`os`, `arch`, `cpu`, `logical_cpus`, `ram_bytes`, `page_size`) or a new key beyond 128 application keys. Non-`str` keys / values are converted with `str()`. |
|
|
101
|
+
| `set_thread_name`, `set_min_level`, `stats()`, `port()`, `is_active()` | |
|
|
102
|
+
|
|
103
|
+
Levels: `DETAIL` (0), `NORMAL` (1, default), `IMPORTANT` (2), `CRITICAL` (3).
|
|
104
|
+
Severities: `INFO` (0, default), `WARNING` (1), `ERROR` (2): what a record is,
|
|
105
|
+
independent of its level (how long it is kept); flag bits of the record
|
|
106
|
+
(PROTOCOL 5.1), `",warning"` / `",error"` appended to the `cat` in Chrome JSON.
|
|
107
|
+
|
|
108
|
+
Args: `bool`, `int` (i64, u64; larger integers become strings), `float`, `str`;
|
|
109
|
+
anything else is stored as `str(value)`. Names, strings and messages are
|
|
110
|
+
truncated to 4096 UTF-8 bytes on a code-point boundary and flagged `TRUNCATED`;
|
|
111
|
+
record bodies never exceed 65535 bytes (excess args are dropped, flagged).
|
|
112
|
+
|
|
113
|
+
## How it works
|
|
114
|
+
|
|
115
|
+
* **Shared tiers.** All threads write into one set of tiers with a
|
|
116
|
+
record budget each; default `[(100000, DETAIL), (50000, NORMAL), (25000, IMPORTANT)]`.
|
|
117
|
+
When tier *k* is full its oldest record is demoted to tier *k+1* if its level
|
|
118
|
+
qualifies, otherwise discarded (counted per thread, with the time range, for
|
|
119
|
+
`TierCoverage`, whose ranges are record end times like the C++ client's).
|
|
120
|
+
There is no chunk pool, so recording never drops an event for lack of trace
|
|
121
|
+
memory: the C++ client's `events_dropped_no_chunk` (which also counts events
|
|
122
|
+
it drops when its pool lock is not available within the chunk-switch time
|
|
123
|
+
budget) has no counterpart here.
|
|
124
|
+
Application threads only do an atomic `deque.append` into an intake queue;
|
|
125
|
+
the server thread moves records into the tiers (background demotion) every
|
|
126
|
+
`stream_interval_ms`, in batches with the lock released in between. If the
|
|
127
|
+
server falls behind (intake > 8192 records), an application thread moves at
|
|
128
|
+
most 64 records itself, and only if the lock is free at that moment: recording
|
|
129
|
+
never waits for the tracer lock. New threads / tasks / call sites register
|
|
130
|
+
without it as well. Snapshots / streaming drain the intake first under the
|
|
131
|
+
tiers lock, so they never miss a record.
|
|
132
|
+
* **Garbage collector.** Records hold only atomic values and flat tuples, and
|
|
133
|
+
the tiers store them in frozen chunks of 512, so CPython's cyclic GC untracks
|
|
134
|
+
them and full collections do not grow with the retained history.
|
|
135
|
+
* **Re-entrancy.** Events recorded from `__del__` methods, weakref callbacks or
|
|
136
|
+
signal handlers that run while the same thread is inside tracer code are
|
|
137
|
+
recorded (or, for a brand-new call site, recorded without a source location);
|
|
138
|
+
they never deadlock. A signal handler that raises inside tracer code (Ctrl+C,
|
|
139
|
+
a Jupyter interrupt, caught by the application) leaves no lock or state
|
|
140
|
+
behind, on every supported Python: every lock the client takes on
|
|
141
|
+
application threads (tracer, call sites, clock log, system info,
|
|
142
|
+
`init()` / `shutdown()`) is released inside its section's `try`, because up
|
|
143
|
+
to 3.9 a `with` block's `__exit__` can be skipped (bpo-29988), and a section
|
|
144
|
+
it interrupts half-way is repaired before the lock is released: at most the
|
|
145
|
+
records being moved are lost. (Two such exceptions within a few bytecodes
|
|
146
|
+
can still leave the lock held.) A signal handler that calls `save()` or
|
|
147
|
+
`set_system_info()` while its thread is inside one of these sections gets an
|
|
148
|
+
exception instead of a deadlock; one that calls `init()` or `shutdown()`
|
|
149
|
+
while its thread is already in `init()` / `shutdown()` returns at once
|
|
150
|
+
(`init()` returns False; the outer call finishes).
|
|
151
|
+
* **Thread churn.** Metadata of ended threads / tasks is kept while retained
|
|
152
|
+
records refer to it, plus the 65536 most recently ended; the rest is
|
|
153
|
+
forgotten (by the server thread, never on an application thread, with the
|
|
154
|
+
tracer lock held for well under a millisecond at a time), so
|
|
155
|
+
thread-per-request servers stay at flat memory.
|
|
156
|
+
* **Contexts and depth.** Threads get thread tracks. Each asyncio task gets its
|
|
157
|
+
own fiber track, created lazily on the task's first event and identified via
|
|
158
|
+
a `contextvars` variable holding `(weakref(task), fiber, tracer)`; a child
|
|
159
|
+
task sees its parent's value, notices the task mismatch and starts its own
|
|
160
|
+
fiber at depth 0 (parent recorded as `parent_track`). `@traced` coroutines
|
|
161
|
+
additionally record `FiberSlice`s (which OS thread ran the task, when).
|
|
162
|
+
A task's metadata (name, parent, creation and end time) stays in the tracer
|
|
163
|
+
while any retained record refers to it, so saves and connect histories name
|
|
164
|
+
every task track and end every ended one with its real end time (the C++
|
|
165
|
+
client needs `FiberEnd` records in trace memory for this; here nothing
|
|
166
|
+
changes).
|
|
167
|
+
Zone ends restore depth by assignment, so non-LIFO ends self-heal; a zone
|
|
168
|
+
ended in another thread or task (also a plain loop callback, or the
|
|
169
|
+
`aclose()` task asyncio runs for an async generator left with `break`) is
|
|
170
|
+
flagged `CROSS_CONTEXT`, disappears from the open zones at once, and the
|
|
171
|
+
owner pops it off its depth stack at its next zone.
|
|
172
|
+
Threads not started by `threading` (native SDK/camera threads calling Python
|
|
173
|
+
through ctypes/cffi/pybind11) keep one track per native thread id, although
|
|
174
|
+
CPython gives each such callback a fresh thread state.
|
|
175
|
+
* **Timestamps.** `time.perf_counter_ns()` (QPC on Windows, `CLOCK_MONOTONIC`
|
|
176
|
+
on Linux), `ns_per_tick = 1`. Ticks are the system-wide monotonic clock,
|
|
177
|
+
except on Windows with Python 3.8 / 3.9, where `perf_counter_ns()` counts
|
|
178
|
+
from interpreter start: there the client measures the constant offset to
|
|
179
|
+
the system-wide QPC clock once at import (to about 200 ns: it can only be
|
|
180
|
+
bracketed, not read) and reports `ticks + offset` as
|
|
181
|
+
`monotonic_ns` (ClockSync, Pong, the Chrome export's
|
|
182
|
+
`svkt_origin_monotonic_ns`, `clock_domain_id`); the recording path is
|
|
183
|
+
unchanged. Those ticks are not the monotonic clock, so a live consumer
|
|
184
|
+
holds events back until the next ClockSync: the client then samples every
|
|
185
|
+
100 ms instead of every second (PROTOCOL 2.2), which bounds that wait to
|
|
186
|
+
about 100 ms. Clock samples are retained independent of any consumer
|
|
187
|
+
(init + one per sample interval for 60 s + 1/min ring of 1024) and sent on connect and
|
|
188
|
+
in every saved file. `clock_domain_id`: Linux boot_id, Windows
|
|
189
|
+
`MachineGuid-<boot time s>`.
|
|
190
|
+
* **SystemInfo.** Right after Hello, on every connection and in every saved
|
|
191
|
+
file (PROTOCOL 4): `os`, `arch`, `cpu`, `logical_cpus`, `ram_bytes`,
|
|
192
|
+
`page_size`, in the C++ client's formats (Windows version from
|
|
193
|
+
`RtlGetVersion`, architecture from `GetNativeSystemInfo`; Linux
|
|
194
|
+
`/etc/os-release`, `/proc/cpuinfo`, `/proc/meminfo`). Gathered once per
|
|
195
|
+
process at the first connect or save; a key that cannot be determined is
|
|
196
|
+
left out. Then the application's entries (`set_system_info`) in insertion
|
|
197
|
+
order. When an entry changes while a consumer is connected, the server
|
|
198
|
+
thread sends the complete SystemInfo again at its next pass (every
|
|
199
|
+
`stream_interval_ms`; it compares a version counter, and like ClockSync it
|
|
200
|
+
waits while the consumer is backpressured). Chrome JSON: `process_labels`
|
|
201
|
+
args `"system": {...}` with the same entries in the same order.
|
|
202
|
+
* **Server.** Up to `max_consumers` consumers at a time (default 4), each with
|
|
203
|
+
its own history snapshot, live queue (`max_live_records`), backpressure and
|
|
204
|
+
`Dropped` accounting, so one that stops reading only loses its own records.
|
|
205
|
+
One more gets `Error{Busy}` right after accept unless a consumer has been
|
|
206
|
+
silent > 5 s (the one silent the longest is replaced). Heartbeat timeout 10 s, a connection whose sends
|
|
207
|
+
make no progress for 5 s *and* that sent nothing for 5 s is closed (a consumer
|
|
208
|
+
that still pings but stopped reading is kept and gets `Dropped` reports),
|
|
209
|
+
TCP keepalive, Windows `SO_EXCLUSIVEADDRUSE`. When a track's open zones are
|
|
210
|
+
all gone an empty OpenZone set is sent (PROTOCOL 5.1). On connect: Hello, SystemInfo, clock log,
|
|
211
|
+
history (oldest tier first, TierCoverage, open zones), then live data.
|
|
212
|
+
Slow consumers get `Dropped` reports instead of stalling the application;
|
|
213
|
+
while 8 MiB are unsent nothing else is queued for them either (no Pongs,
|
|
214
|
+
save Responses, ClockSync or OpenZone sets), so a peer that never reads
|
|
215
|
+
cannot grow memory.
|
|
216
|
+
`SaveRequest`: loopback peers need `allow_remote_save`, other peers
|
|
217
|
+
`allow_remote_save_from_network` (off by default), producer-chosen exclusive file
|
|
218
|
+
name `<process>_<pid>_<UTC yyyymmdd-hhmmss>[_<tag>].svkt/.json` in
|
|
219
|
+
the save directory (default Windows `%TEMP%\svkt`; POSIX `<TMPDIR or /tmp>/svkt-<euid>`,
|
|
220
|
+
created 0700 and refused unless it is a real directory owned by the user),
|
|
221
|
+
1 in flight, >= 5 s apart, quota (50 files / 2 GiB).
|
|
222
|
+
* **Discovery.** A registry file
|
|
223
|
+
`<temp>/svkt-registry/<instance_id>.ann` (deleted on exit; written through a
|
|
224
|
+
randomly named O_EXCL temp file; a directory the producer creates is mode
|
|
225
|
+
1777): how viewers on the same machine find the process. Consumers connect to
|
|
226
|
+
127.0.0.1:port for it, so it is written only when the server listens there
|
|
227
|
+
(`bind_address` 127.0.0.1, 0.0.0.0, or a dual-stack "::" except on Windows);
|
|
228
|
+
a producer bound to another address is found by multicast only (PROTOCOL
|
|
229
|
+
7.2). A failed write is repeated at the next announce. Unless
|
|
230
|
+
`discovery_multicast=False`, also a multicast announcement every second
|
|
231
|
+
(239.255.47.73:47473) on the interface(s) the server listens on (PROTOCOL
|
|
232
|
+
7.1, as the C++ client): every up IPv4 interface for
|
|
233
|
+
`bind_address="0.0.0.0"` (re-enumerated every 30 s; Linux via ioctls), only
|
|
234
|
+
127.0.0.1 for a loopback bind (not announced on the network), only that
|
|
235
|
+
interface for any other IPv4 address (nothing is sent if it cannot be
|
|
236
|
+
selected; never the default route) and none for a specific IPv6 address.
|
|
237
|
+
* **Network exposure.** As the C++ client: the server listens on 127.0.0.1
|
|
238
|
+
unless `bind_address` says otherwise, because the stream is neither
|
|
239
|
+
authenticated nor encrypted. For a viewer on another machine use an SSH
|
|
240
|
+
tunnel (["Remote access"](https://github.com/StefanVK/svk_tracing/blob/master/README.md#remote-access)
|
|
241
|
+
in the main README).
|
|
242
|
+
|
|
243
|
+
## Interop: viewing Python and C++ processes together
|
|
244
|
+
|
|
245
|
+
Python and C++ producers speak the same protocol, so the viewer treats them
|
|
246
|
+
alike:
|
|
247
|
+
|
|
248
|
+
1. Start the processes normally. Each producer listens on the first free port
|
|
249
|
+
of 47474..47489 and registers itself (local registry file), so the
|
|
250
|
+
viewer's Sources panel lists all of them; connect to each (or use
|
|
251
|
+
`svkt capture 127.0.0.1:47474 127.0.0.1:47475 -o session.svkt`).
|
|
252
|
+
2. All processes on one machine report the same `clock_domain_id` and use the
|
|
253
|
+
system monotonic clock (Python: `perf_counter_ns`, which is QPC /
|
|
254
|
+
`CLOCK_MONOTONIC`, corrected by a constant offset on Windows with Python
|
|
255
|
+
3.8 / 3.9; C++: TSC calibrated against the same clock), so the
|
|
256
|
+
viewer puts them on one timeline without offset estimation. Processes on
|
|
257
|
+
other machines are aligned with Ping/Pong.
|
|
258
|
+
3. Connect work across processes with flow ids: create one with
|
|
259
|
+
`svkt.new_flow_id()` (Python) / `svkt::new_flow_id()` (C++), call
|
|
260
|
+
`flow_begin(fid)` in the sending zone, transmit the id inside your own IPC
|
|
261
|
+
message (e.g. the `X-SVKT-Flow` HTTP header understood by
|
|
262
|
+
`svkt.wsgi_middleware`, a field in a ZeroMQ/gRPC message, ...), and call
|
|
263
|
+
`flow_end(fid)` in the receiving zone. The viewer draws the arrow across
|
|
264
|
+
process groups. Ids from the normative formula do not collide between
|
|
265
|
+
processes (instance ids are random).
|
|
266
|
+
4. A saved viewer session stores every process as its own stream in one `.svkt`
|
|
267
|
+
file; each process can also save its own snapshot (`svkt.save()` or the
|
|
268
|
+
viewer's "save on producer").
|
|
269
|
+
|
|
270
|
+
## Overhead and memory
|
|
271
|
+
|
|
272
|
+
Retained records are Python tuples: ~210 bytes per static-name zone, ~440
|
|
273
|
+
bytes with two args. The default tiers (175k records) therefore use roughly
|
|
274
|
+
35-80 MB when full; size `tiers` to your budget.
|
|
275
|
+
|
|
276
|
+
Measured by `tests/test_overhead.py` (static-name zone enter+exit, CPython,
|
|
277
|
+
desktop x86-64): about 2.7-3 µs per zone, ~5 µs with two kwargs args,
|
|
278
|
+
~0.5-0.7 µs per zone while tracing is not initialised. Use `level=svkt.DETAIL`
|
|
279
|
+
plus `set_min_level()` for very hot code, or `@svkt.traced` on coarser
|
|
280
|
+
functions.
|
|
281
|
+
|
|
282
|
+
## Examples and tests
|
|
283
|
+
|
|
284
|
+
The examples and tests are in the repository's
|
|
285
|
+
[python/](https://github.com/StefanVK/svk_tracing/tree/master/python) directory:
|
|
286
|
+
|
|
287
|
+
```
|
|
288
|
+
cd python # the commands below run from here
|
|
289
|
+
python examples/wsgi_server.py [--selftest]
|
|
290
|
+
python examples/asyncio_example.py --seconds 10
|
|
291
|
+
python -m unittest discover -s tests -v
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
The tests contain an independent pure-Python reference consumer/decoder
|
|
295
|
+
(`tests/svkt_decoder.py`) that connects over TCP (127.0.0.1, ephemeral ports;
|
|
296
|
+
discovery disabled except in the discovery test, which uses a temp registry and
|
|
297
|
+
loopback unicast), decodes and validates every message, and reads `.svkt` files.
|
|
298
|
+
|
|
299
|
+
## Limitations
|
|
300
|
+
|
|
301
|
+
* The GIL: the server thread's encoding work (~4 µs per record, e.g. ~0.4 s
|
|
302
|
+
for a 100k-record history sent on connect) competes with application
|
|
303
|
+
threads for the interpreter, so a busy application thread can wait up to the
|
|
304
|
+
interpreter switch interval (`sys.getswitchinterval()`, 5 ms) for it.
|
|
305
|
+
Application threads never block on the network or on the tracer lock.
|
|
306
|
+
* Forked children have tracing disabled until they call `init()` again. The
|
|
307
|
+
child closes its copies of the parent's listener, connection and announcer
|
|
308
|
+
sockets at fork (without sending anything), so it never keeps the parent's
|
|
309
|
+
port listening; the registry file stays the parent's.
|
|
310
|
+
* `FiberSlice` records are only produced by `@traced` coroutines (asyncio has
|
|
311
|
+
no portable hook for task resumption); zones inside any task still land on
|
|
312
|
+
that task's fiber track.
|
svkt-0.1.0/README.md
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
# svkt (Python producer client)
|
|
2
|
+
|
|
3
|
+
Pure-Python (>= 3.8, standard library only) producer for the SVKT tracing
|
|
4
|
+
framework. It records zones, instants, counters, messages, frames and
|
|
5
|
+
program-flow arrows into a shared multi-tier in-memory history, streams them
|
|
6
|
+
live to the SVKT viewer over TCP, and saves snapshots as native `.svkt` files
|
|
7
|
+
or Chrome Trace Event JSON (Perfetto UI / chrome://tracing). Project and
|
|
8
|
+
viewer: [github.com/StefanVK/svk_tracing](https://github.com/StefanVK/svk_tracing);
|
|
9
|
+
wire format: [docs/PROTOCOL.md](https://github.com/StefanVK/svk_tracing/blob/master/docs/PROTOCOL.md);
|
|
10
|
+
component design: [docs/DESIGN.md](https://github.com/StefanVK/svk_tracing/blob/master/docs/DESIGN.md)
|
|
11
|
+
section 5.
|
|
12
|
+
|
|
13
|
+
Version 0.1 (`svkt.__version__`, kept equal to the C++ library's version and
|
|
14
|
+
checked by a test): the API, the wire protocol and the file format may change
|
|
15
|
+
before 1.0. The flow functions (`flow_begin`, `flow_step`, `flow_end`) are
|
|
16
|
+
provisional, like their C++ and C counterparts: their names may change.
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import svkt
|
|
20
|
+
|
|
21
|
+
svkt.init(process_name="inspection") # TCP 127.0.0.1:47474 (+15 probing), local registry
|
|
22
|
+
|
|
23
|
+
with svkt.zone("load_image", path=p) as z: # kwargs become args
|
|
24
|
+
img = load(p)
|
|
25
|
+
z.arg("bytes", len(img))
|
|
26
|
+
|
|
27
|
+
@svkt.traced # sync and async functions
|
|
28
|
+
def detect(img): ...
|
|
29
|
+
|
|
30
|
+
@svkt.traced("infer", level=svkt.IMPORTANT)
|
|
31
|
+
async def infer(img): ...
|
|
32
|
+
|
|
33
|
+
svkt.instant("trigger", level=svkt.IMPORTANT, line=3)
|
|
34
|
+
svkt.plot("queue_depth", q.qsize())
|
|
35
|
+
svkt.message("camera reconnected", level=svkt.CRITICAL)
|
|
36
|
+
svkt.warn("exposure clipped", gain=g) # severity WARNING, level CRITICAL
|
|
37
|
+
svkt.error_message("grab failed: timeout") # severity ERROR, level CRITICAL
|
|
38
|
+
svkt.frame("camera0")
|
|
39
|
+
|
|
40
|
+
fid = svkt.new_flow_id() # program flow across threads/processes
|
|
41
|
+
with svkt.zone("enqueue") as z:
|
|
42
|
+
z.flow_begin(fid)
|
|
43
|
+
queue.put((img, fid))
|
|
44
|
+
# ... elsewhere:
|
|
45
|
+
with svkt.zone("process") as z:
|
|
46
|
+
z.flow_end(fid)
|
|
47
|
+
|
|
48
|
+
svkt.save() # <save dir>/<process>_<pid>_<UTC>.svkt
|
|
49
|
+
svkt.export_chrome_json("trace.json")
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Recording calls are cheap no-ops before `init()` and after `shutdown()`
|
|
53
|
+
(`stats()` returns `{}`, `port()` 0). `save()` and `export_chrome_json()` raise
|
|
54
|
+
`RuntimeError` then; otherwise they return the path written. (The C++ library
|
|
55
|
+
can still save its retained data after `shutdown()`.)
|
|
56
|
+
|
|
57
|
+
## API
|
|
58
|
+
|
|
59
|
+
| Function | Notes |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `init(process_name=None, port=47474, **options)` | Starts recording + the `svkt-server` thread. Options: `bind_address` ("127.0.0.1": this machine only; "0.0.0.0" or an interface address to listen on the network, see ["Remote access"](https://github.com/StefanVK/svk_tracing/blob/master/README.md#remote-access) in the main README; "" is refused like an address that cannot be bound: recording without a server, one stderr line), `port_range` (16), `port=0` (ephemeral), `enable_server`, `enable_discovery` (local registry file), `discovery_multicast` (True), `tiers`, `min_level`, `stream_interval_ms`, `max_live_records` (per consumer), `max_consumers` (4; 1..64), `allow_remote_save`, `allow_remote_save_from_network`, `save_directory`, `save_max_files`, `save_max_bytes`. Returns False if already active. |
|
|
62
|
+
| `shutdown()` | Sends remaining live data + Goodbye, stops the server, removes the registry file. Also registered with `atexit`. |
|
|
63
|
+
| `zone(name, level=NORMAL, color=0, severity=INFO, **args)` | Context manager (`with` / `async with`). Methods: `arg(k, v)`, `set_name(n)`, `severity(s)` (marks the zone `WARNING` / `ERROR` like the `severity` keyword, keeps its level; the last call wins), `flow_begin/step/end(fid)` (all chainable). Exceptions escaping the block are recorded as arg `exception` (`"ValueError: msg"`) and re-raised. |
|
|
64
|
+
| `traced` / `traced("name", level=..., color=...)` | Decorator for sync and `async def` functions (generator functions are returned unchanged). |
|
|
65
|
+
| `instant`, `plot`, `message`, `frame` | Point events, counters, log text (`LoggingHandler` forwards `logging`), frame boundaries. All default to level `NORMAL`; `frame(name="frame", level=NORMAL)` differs from C++ `SVKT_FRAME`, which always records at `Important` (pass `level=svkt.IMPORTANT` to keep frames where a C++ producer's are kept). |
|
|
66
|
+
| `warn(name, level=CRITICAL, color=0, **args)`, `error(...)`, `warn_message(text, level=CRITICAL, color=0)`, `error_message(...)` | Instants / messages with severity `WARNING` / `ERROR`. Level `CRITICAL` by default, so they survive tier demotion; an explicit `level` wins, and the level filters (`min_level`, tiers, stream level) apply as to any record. `instant(..., severity=...)` and `message(..., severity=...)` set a severity at any level (so `severity` is not an arg name there). `LoggingHandler` maps `WARNING` to severity `WARNING`, `ERROR` / `CRITICAL` to `ERROR`, all three at level `CRITICAL`. |
|
|
67
|
+
| `flow_begin(flow_id=None, name=None, level=NORMAL)`, `flow_step(flow_id, ...)`, `flow_end(flow_id, ...)` | Standalone flow points bound to the innermost open zone of the current context. `flow_begin()` without an id creates one and returns it (also before `init()`, like `new_flow_id()`); `flow_step` / `flow_end` with `None` record nothing and return `None`. |
|
|
68
|
+
| `new_flow_id()` | PROTOCOL 5.4 normative formula (`splitmix64(instance_id) + counter * 0x9E3779B97F4A7C15`). |
|
|
69
|
+
| `save(path=None)`, `export_chrome_json(path)` | Snapshots of all tiers + open zones + clock log; run on the calling thread. Return the path written; raise `RuntimeError` before `init()` and after `shutdown()`. |
|
|
70
|
+
| `wsgi_middleware(app)` | One zone per request (method, path, query, status, remote_addr). Flask: `app.wsgi_app = svkt.wsgi_middleware(app.wsgi_app)`. Header `X-SVKT-Flow: <id>` ends that flow in the request zone. |
|
|
71
|
+
| `set_system_info(key, value)` | Adds a line to the SystemInfo (PROTOCOL 4), e.g. `set_system_info("version", "2.3.1")` or the configuration in use: shown with the machine in the viewer and `svkt info`, kept in saves and Chrome exports. Works before `init()`, from any thread, and across `shutdown()` / `init()`. An existing key keeps its place and takes the new value; an empty value (or `None`) removes the key; a connected viewer gets the change at once. Returns False for an empty key, a machine key (`os`, `arch`, `cpu`, `logical_cpus`, `ram_bytes`, `page_size`) or a new key beyond 128 application keys. Non-`str` keys / values are converted with `str()`. |
|
|
72
|
+
| `set_thread_name`, `set_min_level`, `stats()`, `port()`, `is_active()` | |
|
|
73
|
+
|
|
74
|
+
Levels: `DETAIL` (0), `NORMAL` (1, default), `IMPORTANT` (2), `CRITICAL` (3).
|
|
75
|
+
Severities: `INFO` (0, default), `WARNING` (1), `ERROR` (2): what a record is,
|
|
76
|
+
independent of its level (how long it is kept); flag bits of the record
|
|
77
|
+
(PROTOCOL 5.1), `",warning"` / `",error"` appended to the `cat` in Chrome JSON.
|
|
78
|
+
|
|
79
|
+
Args: `bool`, `int` (i64, u64; larger integers become strings), `float`, `str`;
|
|
80
|
+
anything else is stored as `str(value)`. Names, strings and messages are
|
|
81
|
+
truncated to 4096 UTF-8 bytes on a code-point boundary and flagged `TRUNCATED`;
|
|
82
|
+
record bodies never exceed 65535 bytes (excess args are dropped, flagged).
|
|
83
|
+
|
|
84
|
+
## How it works
|
|
85
|
+
|
|
86
|
+
* **Shared tiers.** All threads write into one set of tiers with a
|
|
87
|
+
record budget each; default `[(100000, DETAIL), (50000, NORMAL), (25000, IMPORTANT)]`.
|
|
88
|
+
When tier *k* is full its oldest record is demoted to tier *k+1* if its level
|
|
89
|
+
qualifies, otherwise discarded (counted per thread, with the time range, for
|
|
90
|
+
`TierCoverage`, whose ranges are record end times like the C++ client's).
|
|
91
|
+
There is no chunk pool, so recording never drops an event for lack of trace
|
|
92
|
+
memory: the C++ client's `events_dropped_no_chunk` (which also counts events
|
|
93
|
+
it drops when its pool lock is not available within the chunk-switch time
|
|
94
|
+
budget) has no counterpart here.
|
|
95
|
+
Application threads only do an atomic `deque.append` into an intake queue;
|
|
96
|
+
the server thread moves records into the tiers (background demotion) every
|
|
97
|
+
`stream_interval_ms`, in batches with the lock released in between. If the
|
|
98
|
+
server falls behind (intake > 8192 records), an application thread moves at
|
|
99
|
+
most 64 records itself, and only if the lock is free at that moment: recording
|
|
100
|
+
never waits for the tracer lock. New threads / tasks / call sites register
|
|
101
|
+
without it as well. Snapshots / streaming drain the intake first under the
|
|
102
|
+
tiers lock, so they never miss a record.
|
|
103
|
+
* **Garbage collector.** Records hold only atomic values and flat tuples, and
|
|
104
|
+
the tiers store them in frozen chunks of 512, so CPython's cyclic GC untracks
|
|
105
|
+
them and full collections do not grow with the retained history.
|
|
106
|
+
* **Re-entrancy.** Events recorded from `__del__` methods, weakref callbacks or
|
|
107
|
+
signal handlers that run while the same thread is inside tracer code are
|
|
108
|
+
recorded (or, for a brand-new call site, recorded without a source location);
|
|
109
|
+
they never deadlock. A signal handler that raises inside tracer code (Ctrl+C,
|
|
110
|
+
a Jupyter interrupt, caught by the application) leaves no lock or state
|
|
111
|
+
behind, on every supported Python: every lock the client takes on
|
|
112
|
+
application threads (tracer, call sites, clock log, system info,
|
|
113
|
+
`init()` / `shutdown()`) is released inside its section's `try`, because up
|
|
114
|
+
to 3.9 a `with` block's `__exit__` can be skipped (bpo-29988), and a section
|
|
115
|
+
it interrupts half-way is repaired before the lock is released: at most the
|
|
116
|
+
records being moved are lost. (Two such exceptions within a few bytecodes
|
|
117
|
+
can still leave the lock held.) A signal handler that calls `save()` or
|
|
118
|
+
`set_system_info()` while its thread is inside one of these sections gets an
|
|
119
|
+
exception instead of a deadlock; one that calls `init()` or `shutdown()`
|
|
120
|
+
while its thread is already in `init()` / `shutdown()` returns at once
|
|
121
|
+
(`init()` returns False; the outer call finishes).
|
|
122
|
+
* **Thread churn.** Metadata of ended threads / tasks is kept while retained
|
|
123
|
+
records refer to it, plus the 65536 most recently ended; the rest is
|
|
124
|
+
forgotten (by the server thread, never on an application thread, with the
|
|
125
|
+
tracer lock held for well under a millisecond at a time), so
|
|
126
|
+
thread-per-request servers stay at flat memory.
|
|
127
|
+
* **Contexts and depth.** Threads get thread tracks. Each asyncio task gets its
|
|
128
|
+
own fiber track, created lazily on the task's first event and identified via
|
|
129
|
+
a `contextvars` variable holding `(weakref(task), fiber, tracer)`; a child
|
|
130
|
+
task sees its parent's value, notices the task mismatch and starts its own
|
|
131
|
+
fiber at depth 0 (parent recorded as `parent_track`). `@traced` coroutines
|
|
132
|
+
additionally record `FiberSlice`s (which OS thread ran the task, when).
|
|
133
|
+
A task's metadata (name, parent, creation and end time) stays in the tracer
|
|
134
|
+
while any retained record refers to it, so saves and connect histories name
|
|
135
|
+
every task track and end every ended one with its real end time (the C++
|
|
136
|
+
client needs `FiberEnd` records in trace memory for this; here nothing
|
|
137
|
+
changes).
|
|
138
|
+
Zone ends restore depth by assignment, so non-LIFO ends self-heal; a zone
|
|
139
|
+
ended in another thread or task (also a plain loop callback, or the
|
|
140
|
+
`aclose()` task asyncio runs for an async generator left with `break`) is
|
|
141
|
+
flagged `CROSS_CONTEXT`, disappears from the open zones at once, and the
|
|
142
|
+
owner pops it off its depth stack at its next zone.
|
|
143
|
+
Threads not started by `threading` (native SDK/camera threads calling Python
|
|
144
|
+
through ctypes/cffi/pybind11) keep one track per native thread id, although
|
|
145
|
+
CPython gives each such callback a fresh thread state.
|
|
146
|
+
* **Timestamps.** `time.perf_counter_ns()` (QPC on Windows, `CLOCK_MONOTONIC`
|
|
147
|
+
on Linux), `ns_per_tick = 1`. Ticks are the system-wide monotonic clock,
|
|
148
|
+
except on Windows with Python 3.8 / 3.9, where `perf_counter_ns()` counts
|
|
149
|
+
from interpreter start: there the client measures the constant offset to
|
|
150
|
+
the system-wide QPC clock once at import (to about 200 ns: it can only be
|
|
151
|
+
bracketed, not read) and reports `ticks + offset` as
|
|
152
|
+
`monotonic_ns` (ClockSync, Pong, the Chrome export's
|
|
153
|
+
`svkt_origin_monotonic_ns`, `clock_domain_id`); the recording path is
|
|
154
|
+
unchanged. Those ticks are not the monotonic clock, so a live consumer
|
|
155
|
+
holds events back until the next ClockSync: the client then samples every
|
|
156
|
+
100 ms instead of every second (PROTOCOL 2.2), which bounds that wait to
|
|
157
|
+
about 100 ms. Clock samples are retained independent of any consumer
|
|
158
|
+
(init + one per sample interval for 60 s + 1/min ring of 1024) and sent on connect and
|
|
159
|
+
in every saved file. `clock_domain_id`: Linux boot_id, Windows
|
|
160
|
+
`MachineGuid-<boot time s>`.
|
|
161
|
+
* **SystemInfo.** Right after Hello, on every connection and in every saved
|
|
162
|
+
file (PROTOCOL 4): `os`, `arch`, `cpu`, `logical_cpus`, `ram_bytes`,
|
|
163
|
+
`page_size`, in the C++ client's formats (Windows version from
|
|
164
|
+
`RtlGetVersion`, architecture from `GetNativeSystemInfo`; Linux
|
|
165
|
+
`/etc/os-release`, `/proc/cpuinfo`, `/proc/meminfo`). Gathered once per
|
|
166
|
+
process at the first connect or save; a key that cannot be determined is
|
|
167
|
+
left out. Then the application's entries (`set_system_info`) in insertion
|
|
168
|
+
order. When an entry changes while a consumer is connected, the server
|
|
169
|
+
thread sends the complete SystemInfo again at its next pass (every
|
|
170
|
+
`stream_interval_ms`; it compares a version counter, and like ClockSync it
|
|
171
|
+
waits while the consumer is backpressured). Chrome JSON: `process_labels`
|
|
172
|
+
args `"system": {...}` with the same entries in the same order.
|
|
173
|
+
* **Server.** Up to `max_consumers` consumers at a time (default 4), each with
|
|
174
|
+
its own history snapshot, live queue (`max_live_records`), backpressure and
|
|
175
|
+
`Dropped` accounting, so one that stops reading only loses its own records.
|
|
176
|
+
One more gets `Error{Busy}` right after accept unless a consumer has been
|
|
177
|
+
silent > 5 s (the one silent the longest is replaced). Heartbeat timeout 10 s, a connection whose sends
|
|
178
|
+
make no progress for 5 s *and* that sent nothing for 5 s is closed (a consumer
|
|
179
|
+
that still pings but stopped reading is kept and gets `Dropped` reports),
|
|
180
|
+
TCP keepalive, Windows `SO_EXCLUSIVEADDRUSE`. When a track's open zones are
|
|
181
|
+
all gone an empty OpenZone set is sent (PROTOCOL 5.1). On connect: Hello, SystemInfo, clock log,
|
|
182
|
+
history (oldest tier first, TierCoverage, open zones), then live data.
|
|
183
|
+
Slow consumers get `Dropped` reports instead of stalling the application;
|
|
184
|
+
while 8 MiB are unsent nothing else is queued for them either (no Pongs,
|
|
185
|
+
save Responses, ClockSync or OpenZone sets), so a peer that never reads
|
|
186
|
+
cannot grow memory.
|
|
187
|
+
`SaveRequest`: loopback peers need `allow_remote_save`, other peers
|
|
188
|
+
`allow_remote_save_from_network` (off by default), producer-chosen exclusive file
|
|
189
|
+
name `<process>_<pid>_<UTC yyyymmdd-hhmmss>[_<tag>].svkt/.json` in
|
|
190
|
+
the save directory (default Windows `%TEMP%\svkt`; POSIX `<TMPDIR or /tmp>/svkt-<euid>`,
|
|
191
|
+
created 0700 and refused unless it is a real directory owned by the user),
|
|
192
|
+
1 in flight, >= 5 s apart, quota (50 files / 2 GiB).
|
|
193
|
+
* **Discovery.** A registry file
|
|
194
|
+
`<temp>/svkt-registry/<instance_id>.ann` (deleted on exit; written through a
|
|
195
|
+
randomly named O_EXCL temp file; a directory the producer creates is mode
|
|
196
|
+
1777): how viewers on the same machine find the process. Consumers connect to
|
|
197
|
+
127.0.0.1:port for it, so it is written only when the server listens there
|
|
198
|
+
(`bind_address` 127.0.0.1, 0.0.0.0, or a dual-stack "::" except on Windows);
|
|
199
|
+
a producer bound to another address is found by multicast only (PROTOCOL
|
|
200
|
+
7.2). A failed write is repeated at the next announce. Unless
|
|
201
|
+
`discovery_multicast=False`, also a multicast announcement every second
|
|
202
|
+
(239.255.47.73:47473) on the interface(s) the server listens on (PROTOCOL
|
|
203
|
+
7.1, as the C++ client): every up IPv4 interface for
|
|
204
|
+
`bind_address="0.0.0.0"` (re-enumerated every 30 s; Linux via ioctls), only
|
|
205
|
+
127.0.0.1 for a loopback bind (not announced on the network), only that
|
|
206
|
+
interface for any other IPv4 address (nothing is sent if it cannot be
|
|
207
|
+
selected; never the default route) and none for a specific IPv6 address.
|
|
208
|
+
* **Network exposure.** As the C++ client: the server listens on 127.0.0.1
|
|
209
|
+
unless `bind_address` says otherwise, because the stream is neither
|
|
210
|
+
authenticated nor encrypted. For a viewer on another machine use an SSH
|
|
211
|
+
tunnel (["Remote access"](https://github.com/StefanVK/svk_tracing/blob/master/README.md#remote-access)
|
|
212
|
+
in the main README).
|
|
213
|
+
|
|
214
|
+
## Interop: viewing Python and C++ processes together
|
|
215
|
+
|
|
216
|
+
Python and C++ producers speak the same protocol, so the viewer treats them
|
|
217
|
+
alike:
|
|
218
|
+
|
|
219
|
+
1. Start the processes normally. Each producer listens on the first free port
|
|
220
|
+
of 47474..47489 and registers itself (local registry file), so the
|
|
221
|
+
viewer's Sources panel lists all of them; connect to each (or use
|
|
222
|
+
`svkt capture 127.0.0.1:47474 127.0.0.1:47475 -o session.svkt`).
|
|
223
|
+
2. All processes on one machine report the same `clock_domain_id` and use the
|
|
224
|
+
system monotonic clock (Python: `perf_counter_ns`, which is QPC /
|
|
225
|
+
`CLOCK_MONOTONIC`, corrected by a constant offset on Windows with Python
|
|
226
|
+
3.8 / 3.9; C++: TSC calibrated against the same clock), so the
|
|
227
|
+
viewer puts them on one timeline without offset estimation. Processes on
|
|
228
|
+
other machines are aligned with Ping/Pong.
|
|
229
|
+
3. Connect work across processes with flow ids: create one with
|
|
230
|
+
`svkt.new_flow_id()` (Python) / `svkt::new_flow_id()` (C++), call
|
|
231
|
+
`flow_begin(fid)` in the sending zone, transmit the id inside your own IPC
|
|
232
|
+
message (e.g. the `X-SVKT-Flow` HTTP header understood by
|
|
233
|
+
`svkt.wsgi_middleware`, a field in a ZeroMQ/gRPC message, ...), and call
|
|
234
|
+
`flow_end(fid)` in the receiving zone. The viewer draws the arrow across
|
|
235
|
+
process groups. Ids from the normative formula do not collide between
|
|
236
|
+
processes (instance ids are random).
|
|
237
|
+
4. A saved viewer session stores every process as its own stream in one `.svkt`
|
|
238
|
+
file; each process can also save its own snapshot (`svkt.save()` or the
|
|
239
|
+
viewer's "save on producer").
|
|
240
|
+
|
|
241
|
+
## Overhead and memory
|
|
242
|
+
|
|
243
|
+
Retained records are Python tuples: ~210 bytes per static-name zone, ~440
|
|
244
|
+
bytes with two args. The default tiers (175k records) therefore use roughly
|
|
245
|
+
35-80 MB when full; size `tiers` to your budget.
|
|
246
|
+
|
|
247
|
+
Measured by `tests/test_overhead.py` (static-name zone enter+exit, CPython,
|
|
248
|
+
desktop x86-64): about 2.7-3 µs per zone, ~5 µs with two kwargs args,
|
|
249
|
+
~0.5-0.7 µs per zone while tracing is not initialised. Use `level=svkt.DETAIL`
|
|
250
|
+
plus `set_min_level()` for very hot code, or `@svkt.traced` on coarser
|
|
251
|
+
functions.
|
|
252
|
+
|
|
253
|
+
## Examples and tests
|
|
254
|
+
|
|
255
|
+
The examples and tests are in the repository's
|
|
256
|
+
[python/](https://github.com/StefanVK/svk_tracing/tree/master/python) directory:
|
|
257
|
+
|
|
258
|
+
```
|
|
259
|
+
cd python # the commands below run from here
|
|
260
|
+
python examples/wsgi_server.py [--selftest]
|
|
261
|
+
python examples/asyncio_example.py --seconds 10
|
|
262
|
+
python -m unittest discover -s tests -v
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
The tests contain an independent pure-Python reference consumer/decoder
|
|
266
|
+
(`tests/svkt_decoder.py`) that connects over TCP (127.0.0.1, ephemeral ports;
|
|
267
|
+
discovery disabled except in the discovery test, which uses a temp registry and
|
|
268
|
+
loopback unicast), decodes and validates every message, and reads `.svkt` files.
|
|
269
|
+
|
|
270
|
+
## Limitations
|
|
271
|
+
|
|
272
|
+
* The GIL: the server thread's encoding work (~4 µs per record, e.g. ~0.4 s
|
|
273
|
+
for a 100k-record history sent on connect) competes with application
|
|
274
|
+
threads for the interpreter, so a busy application thread can wait up to the
|
|
275
|
+
interpreter switch interval (`sys.getswitchinterval()`, 5 ms) for it.
|
|
276
|
+
Application threads never block on the network or on the tracer lock.
|
|
277
|
+
* Forked children have tracing disabled until they call `init()` again. The
|
|
278
|
+
child closes its copies of the parent's listener, connection and announcer
|
|
279
|
+
sockets at fork (without sending anything), so it never keeps the parent's
|
|
280
|
+
port listening; the registry file stays the parent's.
|
|
281
|
+
* `FiberSlice` records are only produced by `@traced` coroutines (asyncio has
|
|
282
|
+
no portable hook for task resumption); zones inside any task still land on
|
|
283
|
+
that task's fiber track.
|