Open Source
Pyrockv0.1.0
The Python port of Bedrock: opinionated observability for CPython that unifies tracing, metrics, profiling, and structured logging around operations. Standard library only.
Overview
Pyrock brings Bedrock's model to CPython: every named unit of work is an operation that creates a span, records count, success, failure, and duration metrics, and correlates its logs. It uses only the standard library and has zero runtime dependencies.
A Go service and a Python service behind the same collector produce the same metric names, label sets, span attributes, log shape, and BEDROCK_* configuration, so dashboards and alerts carry over between languages.
import pyrock
with pyrock.init(service="users-api"):
with pyrock.operation("process_user", attrs={"user_id": "123"},
metric_labels=["status"]) as op:
op.register(status="active")
do_work() # an exception escaping here marks the operation as failed
Pythonic API
Context managers and decorators for functions, coroutines, generators, and async generators. Keyword attributes, no context argument.
Exceptions as Failures
An exception escaping an operation marks it failed, registers error attributes, and is re-raised. Pyrock never swallows exceptions.
WSGI and ASGI
Middleware for Flask, Django, FastAPI, Starlette, and more, built on protocol interfaces rather than frameworks.
asyncio and Threads
State lives in contextvars. Helpers carry context into threads and pools, and the free-threaded 3.14t build is supported.
OTLP Traces and Profiles
Traces over OTLP HTTP/JSON or gRPC, and CPU, wall, heap, and thread profiles encoded natively as OTLP Profiles.
Prometheus Metrics
Automatic operation metrics, custom counters, gauges, and histograms, and Python runtime and process metrics.
Testing Built In
pyrock.testing captures spans, metrics, and logs in memory, with a pytest fixture registered automatically.
Status
Alpha (0.1.0). Minor versions may change behavior until 1.0, and every change is recorded in the changelog with a migration note.
Installation
Install from PyPI. The distribution is pyrock-core; the package you import is pyrock.
pip install pyrock-core
- CPython 3.11 or newer, including the free-threaded build (3.14t). Every shared structure is lock-guarded; nothing relies on the GIL.
- Zero runtime dependencies. The wheel is pure Python.
- import pyrock is cheap: profiling, cloud wiring, gRPC, the server, the HTTP client, and the middleware load on first use.
Quick Start
A WSGI service (Flask, Django, Falcon, Pyramid)
import pyrock
from pyrock.wsgi import Middleware
pyrock.init(service="billing") # reads BEDROCK_* first; keywords override
app = Middleware(app) # Flask: app.wsgi_app = Middleware(app.wsgi_app)
An ASGI service (FastAPI, Starlette, Litestar)
import pyrock
from pyrock.asgi import Middleware
bedrock = pyrock.Bedrock(service="users-api") # live, not activated
app = Middleware(app, bedrock=bedrock) # FastAPI: app.add_middleware(Middleware, bedrock=bedrock)
# On shutdown: await bedrock.ashutdown(), or use the Bedrock as the lifespan context manager.
Each request becomes a server operation named http.request, with the metrics http_request_count, _successes, _failures, and _duration_ms labelled by http_method, http_route, and http_status_code. Incoming traceparent and tracestate headers continue the caller's trace.
Operations in your code
import pyrock
@pyrock.operation("get_user", metric_labels=["tier"])
def get_user(user_id: str) -> User:
user = db.load(user_id)
pyrock.register(tier=user.tier) # on the innermost operation or step
pyrock.info("user loaded", user_id=user_id) # carries trace_id/span_id
return user
Operations
An operation is the main unit of instrumentation. Each one creates a span, records four metrics, accepts attributes, and succeeds unless something marks it failed. Use it as a context manager or as a decorator.
{name}_count
Total number of operations
{name}_successes
Operations that completed successfully
{name}_failures
Operations that failed
{name}_duration_ms
Histogram of durations in milliseconds
Metric families use the base name with dots turned into underscores: http.request gives http_request_count.
with pyrock.operation("process_user", attrs={"user_id": uid}, metric_labels=["status"]) as op:
op.register(status="active") # keyword attributes
op.register({"user.tier": "gold"}) # a mapping for dotted keys
op.event("cache_miss", key="u:123") # a span event, recorded immediately
if not valid:
op.fail(ValueError("bad user")) # a handled failure; no raise needed
Operations also have succeed() (clear an earlier failure, for retry loops), end(error=..., success=...), and done(). For callbacks that can't use with, pyrock.start_operation(...) starts one without activating it.
Success by default, and exceptions
- No exception: success, unless fail() was called.
- An Exception escapes: failure. error, error.type, error.fingerprint, and error.chain are registered and the exception is re-raised.
- expected=(KeyError, ...): listed exceptions are recorded as a span event and leave the outcome a success.
- BaseException: asyncio.CancelledError and KeyboardInterrupt are failures; GeneratorExit and SystemExit(0) are not.
- ExceptionGroup: a failure, summarised in error.group.count and error.types.
Metric labels and no_trace
Only keys declared in metric_labels= become metric labels; a declared label with no value is _. Request IDs and user IDs are safe as attributes because they never turn into series. no_trace=True turns off spans for a scope and everything beneath it while still recording metrics.
Steps
Steps are lightweight spans for helper functions. Their attributes go to the parent operation, and they record no metrics of their own.
@pyrock.step("parse_payload")
def parse(raw: bytes) -> Payload:
pyrock.register(bytes=len(raw)) # on the step span and on the parent operation
...
An exception escaping a step marks the step span as an error. The operation fails only if the exception also escapes the operation. Repeated names under one parent are numbered in span names (fetch[1], fetch[2]); metric names never change.
Sources
Sources represent long-running processes. They prefix the names of operations opened beneath them, share their attributes and labels, and record aggregate metrics.
with pyrock.source("background.worker", attrs={"worker.type": "async"},
metric_labels=["worker.type"]) as src:
src.sum("jobs_processed", 1) # counter background_worker_jobs_processed
src.gauge("queue_depth", q.qsize()) # gauge background_worker_queue_depth
src.histogram("latency_ms", 52.3) # histogram background_worker_latency_ms
with pyrock.operation("process"): # named background.worker.process
...
Context, asyncio, and Threads
There is no process-wide default instance. The active instance, operation, step, source, and the no_trace flag live in contextvars.
- asyncio needs nothing: tasks copy the context when created, and asyncio.to_thread copies it too.
- Threads start with an empty context on most interpreters, so carry it explicitly.
- Python 3.14t threads inherit the creator's context when the interpreter enables it, and Pyrock follows that behavior.
- fork() resets queues and series in the child and restarts background threads. With gunicorn or uWSGI, call pyrock.init() in the post-fork hook.
pool.submit(pyrock.bind(process, item)) # wrap one callable
with pyrock.ContextThreadPoolExecutor(max_workers=8) as pool:
pool.map(process, items) # copies context on every submit
pyrock.Thread(target=consume).start() # a threading.Thread that copies context
Lifecycle and noop
pyrock.init(...) builds, starts, and activates an instance; it is a sync and async context manager that shuts down cleanly on exit. Without with, call bedrock.shutdown(timeout=30) or await bedrock.ashutdown(). When no instance is active, every helper returns a preallocated noop, so library code can instrument freely; the noop path costs one ContextVar lookup.
HTTP Instrumentation
Server middleware
The WSGI and ASGI middlewares take the same options:
Middleware(app,
operation_name="http.request",
additional_labels=["user_type"],
additional_attrs=lambda environ: {"user_type": environ.get("HTTP_X_USER_TYPE", "")},
success_codes=range(200, 400), # default: every status below 400
trace_propagation=True,
route=lambda environ: environ.get("pyrock.route"),
)
- Default attributes: http.method, http.route, http.scheme, http.host, http.status_code.
- http.route is always a template or _, never a raw path. FastAPI route templates are picked up automatically; recipes cover Flask and Django.
- Duration runs until the response body finishes, so streaming responses are timed correctly.
- ASGI passes lifespan through, and websocket=True covers each websocket connection as one operation.
- pyrock.http.instrument_http_server(MyHandler) traces a stdlib BaseHTTPRequestHandler.
Client
import pyrock.http
resp = pyrock.http.get("https://api.example.com/users") # a CLIENT span "HTTP GET"
resp = pyrock.http.post(url, json={"name": "a"}, timeout=10)
resp = pyrock.http.request("PUT", url, data=body, headers={"Authorization": f"Bearer {tok}"})
pyrock.inject_headers(headers) # traceparent/tracestate for httpx, requests, or anything else
Client spans record method, host, scheme, and status; 4xx and 5xx responses set error status. URLs never keep credentials, query strings, or fragments. Copy-in recipes for httpx, requests, and gRPC interceptors live in examples/recipes/.
Distributed Tracing
Pyrock implements W3C Trace Context. pyrock.trace.http.HTTPPropagator reads and writes header mappings and ASGI header lists, and pyrock.trace.w3c has the parsing and formatting helpers. Any object with extract(carrier) and inject(carrier, span_context=None) is a propagator:
from pyrock.trace import SpanKind, w3c
class KafkaPropagator:
def extract(self, headers):
for key, value in headers:
if key == "traceparent":
try:
return w3c.span_context_from_traceparent(value.decode())
except w3c.InvalidTraceparent:
return None
return None
def inject(self, headers, span_context=None):
sc = span_context or pyrock.current_span_context()
if sc is not None:
headers.append(("traceparent", w3c.format_traceparent(sc).encode()))
with pyrock.operation("consume", kind=SpanKind.CONSUMER,
remote_parent=KafkaPropagator().extract(msg.headers)):
...
Sampling
from pyrock.trace import sampler
pyrock.init(trace_sampler=sampler.ParentBased(sampler.Ratio(0.1)))
AlwaysOn, AlwaysOff, Ratio(r), and ParentBased(root). Ratio is deterministic on the trace ID, so every service makes the same decision for a trace. Sampling controls export, not span creation.
Logging
Pyrock builds on stdlib logging. By default init() installs a JSON handler on the root logger, so existing loggers in your code and your libraries become structured and trace-correlated.
log = logging.getLogger(__name__)
log.info("user loaded", extra={"user.id": uid}) # extra keys become fields
pyrock.info("processing request", user_id="123")
pyrock.warning("slow upstream", timeout=timedelta(seconds=5))
pyrock.error("job failed", exc) # a positional exception: error.* fields
{"time":"2026-11-05T12:00:00.123Z","level":"INFO","msg":"processing request",
"service":"users-api","user_id":"123",
"trace_id":"0af7651916cd43dd8448eb211c80319c","span_id":"b7ad6b7169203331"}
- log_install="pyrock" configures only the pyrock logger, for apps where Django LOGGING or dictConfig owns logging.
- log_canonical=True emits one operation.complete record per operation.
- log_format="text" gives a human-readable line instead of JSON.
Metrics
requests = pyrock.counter("api_requests_total", "Total API requests", labels=["endpoint", "method"])
requests.labels(endpoint="/users", method="GET").inc()
depth = pyrock.gauge("queue_depth", "Current depth", labels=["queue_name"])
depth.labels(queue_name="jobs").set(42)
latency = pyrock.histogram("query_latency_ms", "Query latency", labels=["db_type"])
with latency.labels(db_type="pg").time(): # milliseconds; also usable as a decorator
run_query()
Static labels are added automatically. An undeclared label key raises ValueError, and re-registering a name with a different schema raises MetricConflictError. Series and family limits default to 1,000 each.
With runtime metrics enabled (the default), each scrape also reports Python and process metrics:
python_gc_collections_total
GC collections by generation
python_threads
Active threads
python_asyncio_tasks
Tasks on tracked event loops
process_resident_memory_bytes
Resident memory
Testing
from pyrock.testing import capture
def test_process_user():
with capture(service="test") as t: # in memory: no server, no detection, no network
process_user("123")
op = t.spans.one(name="process_user")
assert op.attrs["user_id"] == "123"
assert not op.failed
assert t.metrics.value("process_user_count", status="active") == 1
assert t.logs.find(msg="processing request")["trace_id"] == op.trace_id
Under pytest, the pyrock_capture fixture is registered through an entry point; Pyrock never imports pytest itself.
Configuration
pyrock.init() builds its Config from BEDROCK_* environment variables, then applies keyword overrides and validates. Invalid values raise pyrock.ConfigError listing every problem without echoing values. Durations keep Go's syntax in the environment (10s, 500ms, 1m30s).
pyrock.init(service="users-api", log_level="debug",
static_attrs={"env": "production", "version": "1.2.3"})
cfg = pyrock.Config.from_env().replace(metric_prefix="myapp", log_canonical=True)
pyrock.init(cfg, static_attrs={"region": "us-west-2"})
| Variable | Config field | Default |
|---|---|---|
| BEDROCK_SERVICE | service |
unknown |
| BEDROCK_TRACE_URL | trace_url |
None (no export) |
| BEDROCK_TRACE_PROTOCOL | trace_protocol |
auto |
| BEDROCK_TRACE_SAMPLE_RATE | trace_sample_rate |
1.0 |
| BEDROCK_LOG_LEVEL | log_level |
INFO |
| BEDROCK_LOG_FORMAT | log_format |
json |
| BEDROCK_LOG_CANONICAL | log_canonical |
False |
| BEDROCK_LOG_INSTALL | log_install (Python only) |
root |
| BEDROCK_METRIC_PREFIX | metric_prefix |
"" |
| BEDROCK_METRIC_BUCKETS | metric_buckets |
0.5 … 1000 |
| BEDROCK_RUNTIME_METRICS | runtime_metrics |
True |
| BEDROCK_SERVER_ENABLED | server_enabled |
True |
| BEDROCK_SERVER_ADDR | server_addr |
127.0.0.1:9090 |
| BEDROCK_SERVER_PPROF | server_pprof |
False |
| BEDROCK_SERVER_MAX_CONNECTIONS | server_max_connections (Python only) |
64 |
| BEDROCK_DISABLE_ENVIRONMENT_DETECTION | disable_environment_detection |
False |
| BEDROCK_SHUTDOWN_TIMEOUT | shutdown_timeout |
30s |
The server timeouts and header limits match Bedrock. pyrock.env.parse(MyConfig) reads your own dataclasses the same way.
Privacy and Server
Telemetry defaults are conservative, as in Go. pyrock.privacy.Policy is enforced on span attributes, events, log records, metric labels, and profile labels: sensitive keys are redacted, error messages and stacks stay private, raw paths and user agents are emitted only when allowlisted, and host, process, and container identifiers are dropped unless allowed.
from pyrock import privacy
pyrock.init(data_policy=privacy.Policy(
resource_keys=["host.name"],
allow_error_details=False,
redact=lambda path, value: (value, True),
))
The observability server starts on 127.0.0.1:9090 with /metrics, /health, and /ready. It shares Bedrock's security defaults (Slowloris deadline, timeouts, header limit) and caps concurrent connections at 64. pprof requires both a flag and an explicitly passed handler.
Profiles
Python has no runtime pprof, so Pyrock builds each profile type from stdlib pieces and encodes it natively as OTLP Profiles (the same v0.2.0 schema as Bedrock) and as pprof profile.proto.
| Type | Implementation |
|---|---|
| CPU | 100 Hz sampler over thread frames, keeping threads whose CPU clock advanced |
| WALL | The same sampler without the CPU filter, for I/O-bound code (Python only) |
| HEAP | tracemalloc snapshot diffs |
| THREADS | Stacks of every thread plus pending asyncio tasks (alias GOROUTINE) |
| MUTEX / BLOCK | Waits on Pyrock's instrumented Lock, RLock, Condition, and Semaphore |
from pyrock.profile import ProfileExportConfig, ProfileType
pyrock.init(profiles=ProfileExportConfig(
endpoint="https://collector.example/v1/profiles",
headers={"Authorization": f"Bearer {token}"},
types=(ProfileType.CPU, ProfileType.HEAP),
interval=60.0,
cpu_sample_duration=10.0,
))
The debug handler pyrock.profile.debug.app() serves gzipped pprof that works with go tool pprof and Pyroscope.
Cloud backend
pyrock.init(cloud=pyrock.cloud("brk_live_abc123"))
The same wiring as Go's WithCloud: traces over OTLP/gRPC with retries and fan-out to a local collector, metrics pushed every 15 seconds, and profiles every 60 seconds.
Differences from Go Bedrock
Pyrock keeps Bedrock's concepts, wire formats, and names. It differs on purpose in a few places:
| Area | Go Bedrock | Pyrock |
|---|---|---|
| API shape | op, ctx := Operation(ctx, ...), attr.String(...) |
Context managers, decorators, plain values, keyword arguments |
| Failures | op.Register(ctx, attr.Error(err)) |
Escaping exceptions, or op.fail(exc) |
| Context | context.Context argument |
contextvars; no context argument |
| Ratio sampling | Random per span | Deterministic on the trace ID |
| Counters | Ignore negative and NaN increments | Raise ValueError |
| Profiles | CPU, heap, goroutine, mutex, block | Adds WALL; THREADS stands in for goroutine |
| WebSockets | Not covered | One operation per connection (ASGI, opt-in) |
Compatibility
| Python | Status |
|---|---|
| 3.11, 3.12, 3.13, 3.14 | Supported and tested in CI |
| 3.14t (free-threaded) | Supported and tested with PYTHON_GIL=0, including a stress job |
| 3.15 (pre-release) | Tested in CI |
Linux runs the full matrix; macOS and Windows run the suite on 3.14. CPython only.