Skip to main content

metrana-logging-engine

Rust-backed logging engine for Metrana — PyO3 bindings for the metrana-ingestion-logger crate (libs/ingestion_logger).

This package wraps the Rust logger's synchronous, gRPC-backed ingestion client and exposes it to Python. It is intended to be imported by client/metrana as a high-performance logging backend; it has no dependency on the rest of the metrana Python package.

Layout

client/metrana-logging-engine/
├── Cargo.toml              # standalone crate (not a root-workspace member)
├── pyproject.toml          # maturin build backend, abi3 wheel
├── src/
│   ├── lib.rs              # #[pymodule] _metrana_logging_engine
│   ├── config.rs           # Config
│   ├── enums.rs            # ResumeStrategy / Backpressure / ErrorStrategy / LogLevel
│   ├── points.rs           # column extraction (numpy/list) → SeriesFloatPoints
│   ├── logger.rs           # Logger
│   ├── tracing.rs          # Tracer / TracingConfig / TraceIdentity + wire enums
│   └── errors.rs           # exception hierarchy
└── python/metrana_logging_engine/   # pure-Python wrapper + type stubs

The compiled extension is logger_engine._metrana_logging_engine; __init__.py re-exports its public symbols.

Build

Requires a Rust toolchain and maturin.

make develop          # build + install into the active venv (editable-ish)
# or
maturin develop       # equivalent
maturin build --release   # produce an abi3 wheel under target/wheels/

The wheel is built abi3-py310, so a single wheel per platform covers Python 3.10, 3.11 and 3.12.

Tests

make test builds the extension and runs the pytest suite. It always runs the smoke tests; tests/test_e2e.py additionally drives the full local pipeline (logger -> ingestion -> kafka -> worker -> clickhouse -> query service) but is skipped unless the E2E stack is up:

./development/e2e_up.sh    # from the repo root; see development/README.md
make test

Benchmark

benches/rl_logging_bench.py measures the client-side burst cost of the canonical RL telemetry shape against a live stack (defaults: 1024 envs x 16 metrics, 100 minor points per series per one-minute cycle, ~1.6M points per burst from a single logger). It reports per-cycle enqueue wall time, drain lag until the server acked, CPU and RSS; --cycle-secs 0 runs bursts back-to-back as a max-throughput mode.

The target workspace must already exist (workspaces are provisioned with metrana-admin init-workspace, not through the ingestion API). The defaults match the e2e stack, which pre-creates e2e-tests and disables API-key auth; for any other endpoint pass --workspace and a real --api-key.

. .inephany-env/bin/activate && python benches/rl_logging_bench.py

Usage

from metrana_logging_engine import Config, Logger, ResumeStrategy

cfg = Config(
    api_key="...",
    workspace="my-workspace",
    project="my-project",
    run_name="run-001",
    endpoint="https://ingestion.metrana.ai",
    resume_strategy=ResumeStrategy.Allow,
)

import numpy as np

with Logger(cfg) as logger:
    # Ordered scalar series; steps/timestamps auto-assigned when omitted.
    logger.log_std_floats("loss", "ML_STEP", [1.0, 0.8, 0.6], labels={"split": "train"})

    # NumPy arrays are copied in one memcpy (no per-element unboxing) — the
    # preferred path for packing many points per call. `first_step` gives a
    # contiguous step range and `timestamp_millis` a single uniform timestamp,
    # so you don't build full step/timestamp arrays yourself. float64 and
    # float32 arrays are carried at their own precision end-to-end; `dtype=`
    # narrows wider input first ("float16" rounds to half, shipping as f32).
    # Logger(cfg, default_dtype="float32") sets a run-wide float default —
    # integer-typed values are exempt and ship as exact float64.
    logger.log_std_floats(
        "loss", "ML_STEP",
        values=np.asarray(losses, dtype=np.float32),
        first_step=1000,
        timestamp_millis=now_ms,
    )

    # RL series with a major step and optional episode.
    logger.log_rl_floats(
        "cartpole", "reward", "ENVIRONMENT_STEP",
        rl_step=42,
        values=[10.0], steps=[5],
        episode=3,
    )

    # Config / arbitrary attributes (nested dicts/lists are flattened).
    logger.log_config({"lr": 1e-3, "batch_size": 32})
# close() runs on __exit__: flushes pending events and joins the sender thread.

Agentic traces go through a separate Tracer, over their own stream. The engine only caps, packs and delivers: the span tree (ids, parents, restated opens) is the caller's to build, and every update names its trace through one reusable TraceIdentity. Unlike Config, TracingConfig compresses with zstd by default: trace bodies are text and shrink several-fold, where float payloads do not.

import os, time
from metrana_logging_engine import (
    PayloadKind, SpanKind, SpanStatus, Tracer, TraceIdentity, TracingConfig,
)

now_ms = lambda: int(time.time() * 1000)
# run_name=None anchors the traces to the project alone (inference traces).
cfg = TracingConfig("...", "my-workspace", "my-project", "run-001", endpoint="https://ingestion.metrana.ai")

with Tracer(cfg) as tracer:
    # 16 RANDOM bytes: a counter could restart within a run and alias two traces.
    trace = TraceIdentity(os.urandom(16), now_ms(), step=42)
    tracer.trace_open(trace, "agent.solve", SpanKind.SubAgent,
                      payloads=[(PayloadKind.TaskInput, "solve the maze"),
                                (PayloadKind.Attributes, {"model": "claude-y"})])
    started = now_ms()
    tracer.span_open(trace, 1, SpanKind.Thought, "plan", started)
    # A close restates the open as sent and carries the span's bodies.
    tracer.span_close(trace, 1, SpanKind.Thought, "plan", started,
                      end_millis=now_ms(), status=SpanStatus.Ok,
                      payloads=[(PayloadKind.Thought, "left, then right")], token_count=12)
    tracer.trace_close(trace, "agent.solve", SpanKind.SubAgent,
                       end_millis=now_ms(), status=SpanStatus.Ok, span_count=1,
                       payloads=[(PayloadKind.FinalOutput, "path found")])

API summary

Python Rust
Logger(config) Logger::new
log_std_floats(metric, scale, values, labels=None, *, steps=None, first_step=None, timestamps_millis=None, timestamp_millis=None) log_std_floats (ordered)
log_distributed_floats(...) log_distributed_floats (unordered)
log_rl_floats(env, metric, scale, rl_step, values, episode=None, labels=None, *, steps=…, first_step=…, timestamps_millis=…, timestamp_millis=…) log_rl_floats
log_config(value) / log_attributes(prefix, value) log_config / log_attributes
get_series_last_step(metric, scale, labels=None) get_series_last_step
get_env_last_rl_step_and_episode(env) get_env_last_rl_step_and_episode
flush(timeout_secs=None) flush
close(timeout_secs=None) → CloseInfo close_run
shutdown_logger(timeout_secs=None) → CloseInfo shutdown_logger
Tracer(tracing_config) Tracer::new
trace_open(identity, name, kind, payloads=None) log_update(TraceOpen)
span_open(identity, span_id, kind, name, start_millis, *, parent_span_id=0, ordinal=0, payloads=None) log_update(SpanOpen)
span_close(identity, span_id, kind, name, start_millis, *, end_millis, status, parent_span_id=0, ordinal=0, payloads=None, token_count=0) log_update(SpanClose)
trace_close(identity, name, kind, *, end_millis, status, span_count=0, iteration_count=0, token_count=0, payloads=None) log_update(TraceClose)
flush / failover_to_spool / close(timeout_secs) → TraceCloseInfo / metrics() → TraceMetrics same as the logger's

labels accepts a dict[str, str] or a sequence of (key, value) pairs. Durations are passed as seconds (float). Trace payloads is a sequence of (PayloadKind, value) pairs: text kinds take str or UTF-8 bytes, PayloadKind.Attributes a flat mapping of path to bool/int/float/str/ list of str. TaskInput/FinalOutput belong to the trace open/close, which also take the bodies of the root's own kind (an LlmCall root its prompt and completion); every other kind belongs to spans. With a disk spool, a tracer spools under <dir>/#traces/<workspace>/<project>/<run_name> (#project in place of the run for a project-anchored tracer) — a tree of its own, since a replay of a run's logging spool would decode trace records as run updates.

Exceptions

MetranaLoggerError
├── LoggerInitError          # Logger() init/handshake failed
│   └── SpoolUnavailableError  # the disk spool could not be opened; Tracer() raises it too
├── TracerInitError          # Tracer() could not start (no handshake: the stream opens lazily)
├── EnqueueError             # log_* / trace updates failed
│   ├── LoggerClosedError
│   ├── QueueFullError       # Backpressure.Raise with a full queue
│   └── ValidationError      # invalid metric/scale/label/points/step/episode, or trace update
├── SenderError              # background sender-thread errors surfaced
└── ClosingError             # close() failed

Allocator

The extension uses jemalloc (tikv-jemallocator) as its global allocator, governing all Rust allocations in the linked crate graph (prost/tonic/rustls buffers, batching vectors, the Python→Rust point copy). This is the default jemalloc feature.

It is built with jemalloc's disable_initial_exec_tls setting, which puts jemalloc's thread-specific data in the global-dynamic TLS model (allocated lazily via __tls_get_addr) instead of initial-exec. That keeps it out of the static TLS image, so the .so dlopens cleanly with no GLIBC_TUNABLES env var — important for a library imported into arbitrary researcher processes. The trade-off is a small indirection on jemalloc's TSD access; negligible in practice.

To build without jemalloc (system allocator):

maturin develop --release --no-default-features

Maintainer caution: keep disable_initial_exec_tls on for any jemalloc build. Without it, jemalloc's ~2.6 KB TSD uses initial-exec TLS and exceeds glibc's static-TLS surplus for dlopened libraries, so import metrana_logging_engine fails with ImportError: cannot allocate memory in static TLS block. If that ever regresses, the launcher-side escape hatches are GLIBC_TUNABLES=glibc.rtld.optional_static_tls=2097152 (set before python starts) or LD_PRELOADing the .so.

Not yet exposed

  • aggregation_rules on Config — requires protobuf message bindings and is currently always empty.

Metadata

Release files for metrana-logging-engine 0.12.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for metrana-logging-engine 0.12.0
File Actions
metrana_logging_engine-0.12.0-cp310-abi3-win_amd64.whl CPython 3.10 abi3 Windows x86-64 Details for metrana_logging_engine-0.12.0-cp310-abi3-win_amd64.whl
metrana_logging_engine-0.12.0-cp310-abi3-musllinux_1_2_x86_64.whl CPython 3.10 abi3 Linux musl 1.2+ x86-64 Details for metrana_logging_engine-0.12.0-cp310-abi3-musllinux_1_2_x86_64.whl
metrana_logging_engine-0.12.0-cp310-abi3-musllinux_1_2_aarch64.whl CPython 3.10 abi3 Linux musl 1.2+ ARM64 Details for metrana_logging_engine-0.12.0-cp310-abi3-musllinux_1_2_aarch64.whl
metrana_logging_engine-0.12.0-cp310-abi3-manylinux_2_28_x86_64.whl CPython 3.10 abi3 Linux glibc 2.28+ x86-64 Details for metrana_logging_engine-0.12.0-cp310-abi3-manylinux_2_28_x86_64.whl
metrana_logging_engine-0.12.0-cp310-abi3-manylinux_2_28_aarch64.whl CPython 3.10 abi3 Linux glibc 2.28+ ARM64 Details for metrana_logging_engine-0.12.0-cp310-abi3-manylinux_2_28_aarch64.whl
metrana_logging_engine-0.12.0-cp310-abi3-macosx_11_0_arm64.whl CPython 3.10 abi3 macOS 11.0+ ARM64 Details for metrana_logging_engine-0.12.0-cp310-abi3-macosx_11_0_arm64.whl
metrana_logging_engine-0.12.0-cp310-abi3-macosx_10_12_x86_64.whl CPython 3.10 abi3 macOS 10.12+ x86-64 Details for metrana_logging_engine-0.12.0-cp310-abi3-macosx_10_12_x86_64.whl

Total release size: 41.6 MB

Release files / metrana_logging_engine-0.12.0-cp310-abi3-win_amd64.whl

Download URL metrana_logging_engine-0.12.0-cp310-abi3-win_amd64.whl
Size 4.9 MB
Tags CPython 3.10 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
1e5228306591cd4c0c36ebd72ea573e47917300f057331464c2baa1a16ed83b1
BLAKE2b-256 checksum
How to use checksums
59480050b3b2e1b1f34df3befc84d5d37436e4bb3a234d8b5db2bf851d8e6f08
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.15.0

Release files / metrana_logging_engine-0.12.0-cp310-abi3-musllinux_1_2_x86_64.whl

Download URL metrana_logging_engine-0.12.0-cp310-abi3-musllinux_1_2_x86_64.whl
Size 6.6 MB
Tags CPython 3.10 Linux musl 1.2+ x86-64 abi3
SHA-256 checksum
How to use checksums
b911c886cbf667fd6fdc39a772e75205283323e7f6cf852ff1cd73e203d54a35
BLAKE2b-256 checksum
How to use checksums
0b3cceb2eed4836eaacd4beca313b24cc1c9589d152d735230ffef14fe0e0c64
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.15.0

Release files / metrana_logging_engine-0.12.0-cp310-abi3-musllinux_1_2_aarch64.whl

Download URL metrana_logging_engine-0.12.0-cp310-abi3-musllinux_1_2_aarch64.whl
Size 6.4 MB
Tags CPython 3.10 Linux musl 1.2+ ARM64 abi3
SHA-256 checksum
How to use checksums
6b8613b1afaf666fcfbe618746f4d9f40adccd172884178fde6f0fc708e7d59f
BLAKE2b-256 checksum
How to use checksums
38a6d373f8af6fb4d86c44e23659a77d9dd375c73cb07027ccf95d53905824fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.15.0

Release files / metrana_logging_engine-0.12.0-cp310-abi3-manylinux_2_28_x86_64.whl

Download URL metrana_logging_engine-0.12.0-cp310-abi3-manylinux_2_28_x86_64.whl
Size 6.3 MB
Tags CPython 3.10 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
f093d9dbe4f9506e437c937e533b711e979f68d8c84f1a11de273fa94a51c083
BLAKE2b-256 checksum
How to use checksums
02a9e8ce6e8511379a4ac991f6f5afbb05c3ee9b12c0cc9f28e2e1fff56a2fe7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.15.0

Release files / metrana_logging_engine-0.12.0-cp310-abi3-manylinux_2_28_aarch64.whl

Download URL metrana_logging_engine-0.12.0-cp310-abi3-manylinux_2_28_aarch64.whl
Size 6.2 MB
Tags CPython 3.10 Linux glibc 2.28+ ARM64 abi3
SHA-256 checksum
How to use checksums
929a8b0538f47e902d0e41fe3f277b43cdd77b0dea2b2c21184885865f8c672d
BLAKE2b-256 checksum
How to use checksums
29a7d2a59008eca9f094b70752fc3eac80b5a245b7c13493aeae554e5217637d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.15.0

Release files / metrana_logging_engine-0.12.0-cp310-abi3-macosx_11_0_arm64.whl

Download URL metrana_logging_engine-0.12.0-cp310-abi3-macosx_11_0_arm64.whl
Size 5.5 MB
Tags CPython 3.10 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
ccab08c2a257a3d720a8bd98375643d87da79aa77e21281abbdfbcb8e1394045
BLAKE2b-256 checksum
How to use checksums
c61334a31fe13994211a59c2120d2d15c087b4489845d85233c3c563dcf4f199
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.15.0

Release files / metrana_logging_engine-0.12.0-cp310-abi3-macosx_10_12_x86_64.whl

Download URL metrana_logging_engine-0.12.0-cp310-abi3-macosx_10_12_x86_64.whl
Size 5.8 MB
Tags CPython 3.10 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
ff7a51cc3afb40a628f447a22b8a1c71a26459d410adef7dddab2b67604f909d
BLAKE2b-256 checksum
How to use checksums
f98765b822d982f6049de3b65a25e1fddf012731de9f4614e0e98de7e54fe372
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.15.0

Security for metrana-logging-engine 0.12.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page