Skip to main content

Metrana Client Library

Metrana is a metrics tracking client for ML/RL training runs. It provides a simple API to log metrics from training loops to the Metrana ingestion service, to record what an agent did as traces of spans (see Tracing agents), and — through the optional metrana.query subpackage — to read it all back as pandas DataFrames (see Querying your data). A Rust-backed engine batches points, streams them over gRPC, retries transient failures, and can spool to disk — all on a background thread, so logging stays cheap on the hot path while favoring delivery: by default Metrana keeps trying to deliver your data and fails loudly if it truly can't, rather than dropping it silently (see Guarantees and retries). The on-disk spool — on by default, under ~/.metrana/spools — is what lets a run survive a sustained backend outage, and what lets a run start with no backend at all (see Offline logging); without it, a long outage stalls and then fails your run (loudly, not silently).

Installation

pip install metrana

Requires Python 3.10+.

Supported platforms. metrana depends on the native metrana-logging-engine, which ships prebuilt wheels (there is no source distribution) for: Linux x86-64 and aarch64 (glibc manylinux_2_28 and musl musllinux_1_2), macOS x86-64 and Apple Silicon, and Windows x86-64. On any other platform (e.g. Windows on ARM, or an older-than-manylinux_2_28 Linux) pip install will fail to find a compatible wheel — open an issue if you need a target added.

Two optional extras, neither needed for plain logging:

pip install 'metrana[query]'      # read data back (metrana.query): grpcio, protobuf, pandas
pip install 'metrana[rendering]'  # log RL video with log_rendering(): PyAV, for H.264 encoding

Quick Start

ML training run

import metrana

metrana.init(
    api_key="your-api-key",
    workspace_name="my-workspace",
    project_name="my-project",
    run_name="run-001",
)

for step in range(num_steps):
    ...
    metrana.log("loss", loss)                      # one metric
    metrana.log({"accuracy": acc, "lr": lr})       # several at once

metrana.close()   # flush and shut down — always call this

RL training run

import metrana

metrana.init(api_key="...", workspace_name="ws", project_name="proj", run_name="rl-001")

for rl_step in range(num_updates):
    ...  # collect a rollout: M envs x T timesteps
    # one value per finished episode
    metrana.log_rl_episode("episode_return", ep_return, rl_step=rl_step, episode=episode)

    # the whole rollout in one call: `rewards` is an [M, T] block, one row per
    # env in `env_ids`. Always log vectors like this — a per-point loop over
    # envs/timesteps ships the same data orders of magnitude less efficiently.
    metrana.log_rl_environment_step(
        "reward", rewards, rl_step=rl_step, env_id=env_ids, episode=episodes
    )

metrana.close()

Logging standard metrics

metrana.log(metric_name, value, *, step=None, timestamp=None, scale=None, labels=None, evaluation=None, dtype=None) logs to the default ML-step scale.

Values may be a scalar or an array — a Python list or any NumPy / PyTorch / JAX / TensorFlow tensor (any float dtype, on any device); arrays are converted to contiguous NumPy once before crossing into the engine:

metrana.log("loss", 0.5)                       # one point
metrana.log("loss", [0.51, 0.49, 0.48])        # three points (bulk)
metrana.log("grad_norm", grad_norm_tensor)     # torch/np/jax/tf tensor

Storage precision is float32 by default for float values: metric signals don't carry more, and it halves the wire and storage footprint. Values arriving wider are rounded (IEEE round-to-nearest-even); "float16" rounds to half precision (traveling as float32). Integer-typed values — token counts, cumulative sample counts — are exempt and ship as float64 (exact to 253; float32 would silently round counters past ~16.7M, 224). Override per call with dtype="float64" / "float32" / "float16" (numpy spellings work too), or run-wide with metrana.init(..., default_dtype=...); an explicit dtype also overrides the integer exemption. dtype="int64" / "int32" declare a counter whose values arrive as floats (a division, a mean, a float metrics dict): values truncate toward zero and ship as exact-to-2**53 float64 (NaN/inf are rejected — accepted as usual under float dtypes).

Multiple metrics at once — pass a mapping (values may themselves be scalars or arrays):

metrana.log({"loss": loss, "accuracy": acc})

Steps

A series is identified by (metric_name, scale, labels), and each series has its own step axis. The step argument controls it:

step value meaning
None (default) auto-increment from the series' last step
a single int the step of the first point; further points in the call continue from it
a sequence/array an explicit step per point (length must match value)
metrana.log("loss", 0.5)                        # auto: next step
metrana.log("loss", [a, b, c], step=100)        # steps 100, 101, 102
metrana.log("loss", [a, b, c], step=[10, 20, 30])  # explicit steps

Timestamps work the same way via timestamp (Unix milliseconds): None lets the server stamp on arrival; a single int applies to every point; a sequence gives one per point.

Scale, labels, and evaluation

These three arguments shape the series identity:

  • scale — the step scale (a StandardMetricScale value: "ML_STEP", "EPISODE", "ENVIRONMENT_STEP"). None defaults to ML_STEP. Only log / log_distributed take it; the RL helpers fix their own scale.
  • labels — a dict[str, str] that, together with the name and scale, identifies the series. Two points with the same name but different labels go to different series. A metric holds one label key set (and one value kind) for its lifetime: every series of a metric uses the same label keys, and a call with different keys is rejected.
  • evaluation — a shorthand that adds the evaluation label: True adds {"evaluation": "true"}, False adds {"evaluation": "false"} (unless you already set the key in labels), None (default) adds nothing. Mark BOTH sides of an eval-split metric so its label key set stays uniform — a metric uses the flag never or always; mixing flagged and plain calls is rejected.
metrana.log("reward", train_reward, evaluation=False)      # training series
metrana.log("reward", eval_reward, evaluation=True)        # distinct eval series
metrana.log("reward_by_policy", r, labels={"policy": "greedy"})  # labeled series, own metric

Retrieving the last step

metrana.get_last_step(metric_name, scale=None, labels=None) returns the last step logged for a series, or None (pass the same scale / labels you logged it with). This is seeded from the server at init(), so after a restart or resume you can continue from where the run left off — useful when you want explicit steps but need to know the current position:

last = metrana.get_last_step("loss")
next_step = 0 if last is None else last + 1
metrana.log("loss", loss, step=next_step)

Closing

metrana.close() flushes queued points, marks the run closed, and shuts the background engine down, returning a CloseInfo (see Guarantees and retries). Always call it — the engine runs on a daemon thread, so if the interpreter exits without close(), queued-but-unsent points are lost (a warning is emitted at exit). Use it directly or rely on try/finally.

close() flushes for up to close_timeout seconds (default 900 — generous on purpose: when the ingestion backend lags, the server paces senders (adaptive backpressure, up to ~5s per in-flight message), so a healthy drain of a full send window can take minutes; a deadline that expires mid-drain abandons data that was on its way). To abandon a run immediately, dropping anything not yet sent, pass metrana.close(close_timeout=0) — pair it with init(skip_drain_render_on_close=True) if you also want queued rendering frames dropped rather than encoded. To stop without closing the run so it can be resumed later use metrana.shutdown_logger(), and to force a durability checkpoint mid-run use metrana.flush() — both are covered under Guarantees and retries.

On preemptible nodes note the provider grace period (~2 min on AWS spot, ~30 s elsewhere) is far below the 900 s default: pass a close_timeout sized to it and configure the disk spool. With a spool, a bounded close reserves its tail (close_spool_reserve_secs, default 5, capped at half the window) for an emergency flush: whatever is still undelivered when only the reserve remains is written straight to disk — no gRPC retries — and delivered by the next resume, so even a 30 s grace period ends with the data durable. init(max_pending_requests=3) additionally keeps a backpressure-paced drain down to seconds if you prefer delivery over spooling.

Logging histograms

metrana.log_histogram(metric_name, histogram, step, *, timestamp=None, scale=None, labels=None, evaluation=None) logs the distribution of a tensor at one step — weights, activations, gradients. A histogram is a metrana.Histogram: strictly increasing bin_edges (up to 512 bins) plus exactly one of counts or densities — which argument you pass declares the kind, and a metric holds one value kind (float vs histogram, counting vs density) for its lifetime.

import numpy as np

# np.histogram output wraps directly:
metrana.log_histogram("weights/l0", metrana.Histogram.from_numpy(np.histogram(w, bins=64)), step=100)

# construct explicitly for densities, and for float-typed counts (torch):
metrana.log_histogram("acts", metrana.Histogram(edges, densities=d), step=100)
metrana.log_histogram("weights/l0", metrana.Histogram(edges, counts=torch_hist), step=100)

Histogram.from_numpy accepts integer hist arrays only — a float array is ambiguous (np.histogram(..., density=True) returns floats, but so do torch's histogram counts), so those are constructed explicitly instead of guessed at. counts= accepts float arrays holding exact integral values (torch's native output); weighted histograms (fractional counts) are not supported.

Steps are explicit and absolute — there is no auto-increment. Histograms are typically logged sparsely (per epoch, every N steps) and their step axis must line up with your float series. Steps may arrive in any order, and re-logging a step overwrites its histogram (never merges).

Exact stats. Charts can reduce histograms to scalar series (mean, quantiles, …). Reductions computed from bins are approximate — the error is bounded by the bin width. If you still hold the raw values, pass their exact moments and moment-based reductions become exact:

h = metrana.Histogram(edges, counts=c, stats=(x.min(), x.max(), x.sum(), (x**2).sum()))

When omitted, the server stores a bin-approximation. With densities= the sample count is not recoverable, so stats must be the normalized reading: sum = mean, sum_of_squares = mean of squares; min/max stay the sample bounds.

Logging scatter plots

metrana.log_scatter(metric_name, xs, ys, step, *, x_title=None, y_title=None, timestamp=None, scale=None, labels=None, evaluation=None) logs a point cloud at one step — an embedding projection, a latent-space slice, a Pareto front — as a 2D scatter series; metrana.log_scatter3d(...) adds a zs axis and a z_title. The coordinates are parallel equal-length arrays (numpy, tensors, or plain sequences) of 0 to 32,768 finite points — empty arrays log the step with "no points here". One call carries the step's full point set, and re-logging a step overwrites it (never appends). 2D and 3D are two distinct value kinds — a scatter metric keeps one dimensionality for its lifetime, the same way every metric keeps one value kind.

emb = project_embeddings(model)  # [N, 2]
metrana.log_scatter("latents", emb[:, 0], emb[:, 1], step=100, x_title="pc1", y_title="pc2")
metrana.log_scatter3d("trajectory", pos[:, 0], pos[:, 1], pos[:, 2], step=100, z_title="height")

Axis titles are display metadata, not identity: the latest non-empty title set logged for a series wins, an omitted title renders as a plain axis, and titles follow the label naming rules. Steps are explicit and absolute, may arrive in any order, and never auto-increment — exactly as for histograms.

Logging RL metrics

RL metrics use a two-level step: a major rl_step (the training/update step, which must not decrease) plus a minor step. Two helpers cover the common scales; the scale is implied by the function, so you never pass it explicitly. Both helpers also accept labels and evaluation, which behave exactly as for standard metrics, and dtype, which selects the storage precision exactly as for metrana.log (float32 by default; see Logging standard metrics).

Per-episode metrics

metrana.log_rl_episode(metric_name, value, rl_step, episode=None, env_id=None, labels=None, evaluation=None, dtype=None) — the episode is the minor step. Omit it to auto-increment from the last logged episode:

metrana.log_rl_episode("episode_return", ep_return, rl_step=rl_step, episode=episode)

Per-environment-step metrics

metrana.log_rl_environment_step(metric_name, value, rl_step, *, episode, env_id=None, env_step=None, auto_start_from_one=False, labels=None, evaluation=None, dtype=None) logs env-step-scale points. The env-step axis counts across rl_steps, bounded by episode: each episode's steps keep increasing until the episode ends (without episodes, a single ever-increasing axis per environment).

episode is required (everything after rl_step is keyword-only): the first call for a metric pins it episodic or non-episodic for the run, and later calls on the other side are rejected — so a metric with no episode axis passes episode=None explicitly rather than leaving it out.

By default (env_step=None) env steps are numbered by the server, starting at 0 — pass auto_start_from_one=True to number episodic steps from 1 instead. Pass env_step to number the points yourself; explicit steps must increase within their episode, or they are deduplicated server-side even though the call succeeds. Auto and explicit env steps must not be mixed on one (environment, metric) — the first call pins the choice.

Re-collecting an episode from its start restarts it (its earlier env steps are discarded): explicit steps signal a restart by dropping back to 0/1; auto steps by replaying the episode's first rl_step batch, which is exactly the shape a from-scratch process restart produces.

It is vectorized over environments. Pass a list of env ids and a matching value block:

  • single env: env_id="env0", value a scalar or 1D [T] array;
  • many envs: env_id=["env0", "env1", ...] (length M), value a 1D [M] (one point each) or 2D [M, T] array. episode / env_step (and timestamp) broadcast: a scalar, 1D, or 2D matching the value. Environments usually share rl_steps but not episode counters, so per-env ([M]) or per-point ([M, T]) episodes are the typical forms; a scalar episode fits lockstep setups only.
# 8 envs, one reward each at this rl_step
metrana.log_rl_environment_step("reward", rewards_8, rl_step=rl_step,
                                env_id=env_ids, episode=episodes)

# 8 envs x 128 timesteps in one call
metrana.log_rl_environment_step("reward", rewards_8x128, rl_step=rl_step,
                                env_id=env_ids, episode=episodes_8x128)

# explicit env steps (your own numbering) for episode 7
metrana.log_rl_environment_step("reward", [0.1, 0.3], rl_step=rl_step,
                                episode=7, env_step=[12, 13])

Log vectors, not loops. One [M, T] call and M × T single-point calls carry identical data, but the batched call is what the whole pipeline is built around: point-by-point logging pays per-call overhead in the client, per-batch framing on the wire, and per-batch tracking on the backend — easily orders of magnitude more expensive for the same rollout. If your rollout buffer already holds a block, log the block.

metrana.get_env_last_rl_step_and_episode(env_id) returns (last_rl_step, last_episode) for an environment (either may be None) — handy for computing explicit steps after a resume.

Run configuration and attributes

metrana.log_config({"optimizer": {"name": "adam", "lr": 3e-4}, "batch_size": 256})
metrana.set_tags(["baseline", "v2"])      # replace the tag set
metrana.add_tags(["ablation"])            # add without removing
metrana.remove_tags(["baseline"])         # remove
metrana.set_description("LR sweep, seed 0")

config passed to init() is logged the same way (nested dicts/lists flatten under config/). These run-level attributes — along with the git commit SHA and any tags/description given to init() — are applied only by the process that creates the run, so distributed siblings that resume it never clobber them.

For arbitrary run attributes use metrana.log_attributes(prefix_path, value). For per-environment RL attributes (a distinct, env-scoped kind) use metrana.log_env_attributes(env_id, value, episode=None).

Environment renderings

metrana.log_rendering(frame, rl_step, episode, env_id=None) appends a frame to a per-(env_id, episode) H.264 .mp4, encoded on a dedicated background thread (never blocks the training loop).

  • frame: a uint8 NumPy array, (H, W, 3) RGB or (H, W) / (H, W, 1) grayscale. Width and height must be even (libx264 yuv420p).
  • When the (env_id, episode) pair changes, the open encoder for that env is closed and a new one opened for the next episode.

Configure via init(): rendering_output_dir, rendering_fps, rendering_max_concurrent_encoders, rendering_queue_max_size, skip_drain_render_on_close, rendering_close_timeout. Requires the rendering extra.

Tracing agents

metrana.tracing records what an agent did: each invocation — in post-training, each rollout — becomes a trace, a tree of spans for its model calls, tool calls, thoughts, loop iterations and sub-agents, with the prompts, completions, inputs and outputs those steps carried. Traces sit next to the run's metrics, so a reward curve can be opened into the rollouts that produced it. The tracer is the logger's pair: tracing.init() after metrana.init, tracing.close() before metrana.close().

import metrana
import metrana.tracing as tracing

metrana.init(workspace_name="my-team", project_name="agents", run_name="grpo-7b-v2")
tracing.init()                                  # traces of that run, with its credentials and settings

with tracing.step(100):                         # the policy step every trace in the block belongs to
    with tracing.agent_trace("rollout", task_input=task) as trace:
        with tracing.llm_call("policy", prompt=messages) as llm:
            llm.completion(reply.content)
            llm.token_count = reply.usage.total_tokens
        with tracing.tool_call("search", input={"q": query}) as tool:
            tool.output(results)
        trace.final_output(answer)
        trace.set_attributes({"reward": reward})

tracing.close()
metrana.close()

Spans nest by their with blocks (and per asyncio task); each is enqueued the moment its block is entered, so a running rollout is already visible. An input known at the start — a prompt, a tool's input, the task — rides the open; what the span produced rides the close, as do attributes and the token count. An exception escaping a block closes the span ERROR with an exception attribute and propagates. Kinds and their bodies: llm_call (prompt / completion), tool_call (input / output), thought (.text()), sub_agent, iteration (counted on the trace), artifact, function; trace(name, kind=...) roots at any of them.

Functions can be traced without blocks — arguments in, return value out, nesting by the call stack, and a top-level call rooting its own trace at the enclosing tracing.step:

@tracing.op(kind=tracing.SpanKind.TOOL_CALL)
def search(query: str) -> dict: ...

@tracing.op
def rollout(task: str) -> dict:                 # a FUNCTION-rooted trace when called at top level
    hits = search(task)
    tracing.current_span().set_attributes({"reward": 0.9})
    return {"hits": hits["hits"]}

At inference there is no run and no step: initialize the tracer against the project and root each request at the model call.

tracing.init(workspace_name="my-team", project_name="agents", run_name=None)   # project only

with tracing.model_trace("chat", prompt=messages, attributes={"model": "claude-y"}) as trace:
    trace.completion(reply.content)

tracing.close()

@tracing.op also takes postprocess_inputs= / postprocess_output= to shape what is recorded (redact a key, drop a tensor), leaves a method's self out, and traces generators as one node — opened at the first pull, closed when the iteration ends, its yields joined into the output. What a whole batch shares goes on every node opened in a tracing.attributes({"sample_index": i}) block. The root counts the spans that failed beneath it in an error_count attribute, so AttrFilter("error_count") > 0 finds the rollouts where something went wrong even when the rollout itself recovered.

Instrumented code runs wherever it is called: with METRANA_TRACING_DISABLED=1, with nothing initialized (warned once), or for the roots a sample_rate (tracing.init(sample_rate=0.01), METRANA_TRACING_SAMPLE_RATE) leaves out — decided once per root, kept or dropped whole — the constructors hand out inert NoopSpan nodes that record nothing.

Tracing uses the same engine, stream, queue, backpressure, retries and disk spool as logging (traces spool under a #traces subtree of the same directory), compresses with zstd by default, and delivers a stream's updates strictly in the order sent, so a span's close can never overtake its open. Read traces back with the query client's trace methods.

Naming rules

  • Metric names identify a series together with the scale and labels. Use /-delimited prefixes to group related series (e.g. train/loss, eval/loss are distinct series); labels and the evaluation shorthand are an alternative way to split a name into distinct series.
  • Environment ids appear in URLs, so they must be URL-safe segments.
  • Config / attribute paths are /-delimited; keys must be non-empty and contain only [a-zA-Z0-9._-:/].

Distributed logging

When several processes (e.g. distributed-training ranks) log into one run, two pieces matter:

1. They must agree on the run. Every process that should share a run needs the same orchestration_id. If you don't pass one, it is resolved automatically from METRANA_ORCHESTRATION_ID, then the framework job ids TORCHELASTIC_RUN_ID / SLURM_JOB_ID / RAY_JOB_ID, then a random token (which only descendants that inherit the environment will match). The resolved value is published back to METRANA_ORCHESTRATION_ID so forked/spawned children inherit it. With resume_strategy="never" (the default), the first process creates the run and the rest resume it by matching this identifier; a genuinely different job hitting the same run name errors instead of corrupting it.

# torchrun / Slurm / Ray: nothing to do — the framework job id is picked up automatically.
metrana.init(api_key="...", workspace_name="ws", project_name="proj", run_name="run")

# Custom launcher: pass a token shared by all workers of the job.
metrana.init(..., orchestration_id="job-2025-06-23-abc")

2. Choose the right log function for shared series. Use metrana.log_distributed(...) (instead of metrana.log(...)) when multiple processes write to the same series — for example all ranks logging a global loss. It uses unordered, merge semantics so concurrent writers don't conflict. Provide an explicit step (the global training step) so points from different ranks align on the same axis:

metrana.log_distributed("loss", loss, step=global_step)

Use plain metrana.log(...) for series owned by a single writer (it is ordered and can auto-increment). Pin logger_id (e.g. one per rank) if you want the backend to distinguish a restarted writer from a genuinely new concurrent one.

3. RL metrics need an exclusive owner per (environment, episode). The RL functions (metrana.log_rl_episode(...) and metrana.log_rl_environment_step(...)) are ordered, and the unit of ownership is the (environment, episode) pair: each episode of each environment must be logged by exactly one process. Sharding whole environments across ranks (e.g. a vectorized env split over workers) satisfies this automatically. Sharding episodes of one environment across parallel rollout workers — each worker running its own episodes of cartpole — works too; each point just has to carry an explicit episode. In log_rl_episode an explicit episode switches the series to unordered (merge) semantics: you own the episode numbering, and parallel workers' points merge cleanly instead of contending for one auto-increment cursor. In log_rl_environment_step nothing special is needed — log normally with episode=... set; env steps are numbered within each episode, so writers that own different episodes never contend.

Episode restarts are the main risk with parallel loggers. An episode that logs its first env-step again is treated as an episode restart: the server discards the episode's earlier points and starts it over (this is how a crashed-and-restarted worker recovers). Two processes writing the same episode of one environment therefore don't just interleave — the second writer looks like a restart and silently wipes what the first one logged. Keep episode ownership disjoint.

Plain metrana.log(...) / metrana.log_distributed(...) float series have no per-env restriction (log_distributed is explicitly built for many writers on one series).

Guarantees and retries

Metrana favors delivering your data over shaving microseconds off the hot path — while never blocking it forever. The defaults are chosen so a healthy run pays almost nothing and an unhealthy one fails loudly instead of silently dropping metrics:

  • Backpressure (backpressure_strategy, default "block"): when the in-process queue is full an enqueue waits for room rather than dropping. This is not an unbounded stall — the queue only stays full while delivery is stuck, which is itself bounded by the retry policy below (and, with a disk spool, drained quickly to disk). Alternatives: "drop_new" (drop the new points — protects the loop, can lose data under sustained pressure) and "raise" (raise MetranaEventQueueFullError). With a disk spool, "spool_then_raise" gives bounded-latency logging with no data loss and no hand-written wiring: a timed-out enqueue (or flush) triggers the spool failover itself and waits disk_spool_retry_timeout_secs (default 5) more before raising. "raise" paired with metrana.failover_to_spool() in the exception handler remains for precise control.
  • Retries (max_send_retries, default 15): a failed gRPC send is retried with exponential backoff (send_retry_initial_backoff_secs → send_retry_max_backoff_secs, ≈1.7 min total at the defaults). When the budget is spent the logger fails over to the disk spool if one is configured (below); otherwise the delivery policy applies. max_send_retries=None retries gRPC forever.
  • Delivery policy (delivery_policy, default "all_or_crash"): what happens once every channel has given up. "all_or_crash" stops the logger so the next log / flush / close raises MetranaSenderError — for an experiment tracker a loud failure beats a silent hole. "tolerate_loss" drops the data and keeps the process running, for callers who would rather lose metrics than the job.
  • Rendering errors (rendering_error_strategy, default "warn"): governs only the Python rendering pipeline's frame-encoding errors ("silent", "warn", "raise_on_log", "raise_on_close"). Engine delivery is governed by delivery_policy, not this.

With block + all_or_crash and the spool disabled (disk=None), data survives transient outages (they're retried), and the only silent-loss path is a hard process kill (kill -9, or exiting without close()). But a sustained outage — longer than the ~2-min retry budget — still loses the buffered window, loudly: the loop blocks, then all_or_crash stops the logger and the next call raises. So without a spool, "favoring delivery" means fail loud, not survive. A disk spool is what closes that gap, turning a sustained outage into a transparent failover. (Or opt into tolerate_loss / drop_new to drop-and-continue instead of block-then-crash.)

Two recommended spool-backed profiles. With a spool (sized via max_size_bytes!) the knobs compose into two coherent setups:

  • Durability-first — jobs with no clock against them: backpressure_strategy="block" (default), long or None timeouts for flush/close/shutdown_logger, disk=metrana.DiskConfig(path, max_size_bytes=...). Delivery favors the wire; backend pressure slows the loop instead of diverting data; the spool catches genuine outages.
  • Bounded-latency — spot/preemptible nodes, tight step budgets: backpressure_strategy="spool_then_raise" with short flush/close timeouts, plus eager knobs — ack_stall_timeout_secs=10, max_send_retries=3, max_pending_requests=3, disk_spool_retry_timeout_secs=5 and close_spool_reserve_secs=5 (defaults) — so every wait is bounded and timed-out waits land on the spool instead of raising. More data takes the disk → replay path; nothing is lost.

Lifecycle: flush, close, shutdown

All three accept a timeout (timeout_secs for flush, close_timeout for close / shutdown_logger) bounding how long they wait; pass None to wait without bound. The defaults are finite so an unreachable backend can never hang interpreter shutdown forever.

  • metrana.flush(timeout_secs=900) — a durability barrier: it returns only once everything logged before it is durable (acknowledged by the backend, or — with a disk spool — fsync'd to it). It rides out a transient outage (a reconnect does not fail it) and raises only if that data is actually dropped (MetranaSenderError) or the timeout elapses (MetranaTimeoutError — not loss; the data is still in flight or on the spool). The logger stays usable afterwards. Call it at checkpoints: a flush() next to your checkpoint write makes the metrics leading up to the checkpoint durable together, so a resumed run lines up with its metrics.
  • metrana.close(close_timeout=900) — closes the run: flush, mark it closed, stop the engine. Returns a CloseInfo. Always call it (see Closing).
  • metrana.shutdown_logger(close_timeout=900) — like close, but leaves the run open so a later process can resume it. Use it for a graceful, resumable stop — e.g. on a spot-instance preemption signal, call it to flush in-flight data and stop cleanly instead of being killed mid-send, then init() the same run when the job restarts. Returns a CloseInfo.

close() and shutdown_logger() (and replay_spool, below) return a CloseInfo:

info = metrana.close()
print(info.metrics)                  # final self-metrics snapshot (see "Tuning and observability")
if info.has_undelivered_spool:       # data still on the disk spool, not yet seen by the backend
    print(f"{info.leftover_segments} spool segments ({info.leftover_bytes} bytes) left to replay")

has_undelivered_spool is True when the disk spool still holds data the recovery channel could not deliver within the close window — a future resume or replay_spool will deliver it. It is always False when no disk spool is configured.

Sizing timeouts for strong guarantees. During a backend outage data is not spooled instantly — it first exhausts the gRPC retry budget (up to ~2 minutes at the defaults), then fails over to the disk spool. A stalled-but-alive backend is slower still: each stall burns one retry only after the ack-stall watchdog fires (ack_stall_timeout_secs, default 60), so the worst case to reach the spool is ack_stall_timeout_secs × max_send_retries — ~15 minutes at the defaults, plus retry backoffs on top. Latency-sensitive callers should lower those knobs, or skip the wait with failover_to_spool() / backpressure_strategy="spool_then_raise". So a flush / close / shutdown_logger timeout shorter than that window can elapse before the data ever reaches disk. The two surface differently: flush raises MetranaTimeoutError (benign — the data is still in flight; just re-flush or close), while close / shutdown_logger raise MetranaClosingError only if their deadline elapses with data still not durable — neither acknowledged by the backend nor written to the disk spool — which means likely loss. If the data reached the spool before the deadline they do not raise: they return a CloseInfo and log that the data is safe on disk, awaiting delivery. For strong guarantees, configure a disk spool and give these calls a timeout at least as long as the failover window (≥ ~2–3 minutes): an outage at close-time then lands the data on disk — recoverable on the next resume / via replay_spool — instead of cutting the failover short.

Disk spool (on by default)

The disk spool is an extra delivery layer that turns "deliver or fail" into "deliver, eventually, through almost anything". It is on by default under ~/.metrana/spools/<hostname> (override the base with METRANA_DISK_SPOOL_DIR; see Where the spool lives below for the hostname, and read it before running on Slurm), 8 GiB per run. The default is best-effort: init() creates the directory, writes a probe file and takes an exclusive lock on this process's writer directory, and if any of that fails (read-only home, no space) it warns and continues without a spool rather than failing your job. An explicit path is a requirement — init() raises MetranaSpoolUnavailableError if it cannot be used — and disk=None opts out:

metrana.init(..., disk=metrana.DiskConfig("/var/spool/metrana", max_size_bytes=16 << 30))
# a bare path also works, but takes the 8 GiB default cap — prefer an explicit size:
metrana.init(..., disk="/var/spool/metrana")
# opt out entirely (no failover, no warning):
metrana.init(..., disk=None)

Each run gets its own sub-directory under that path — the spool actually lives at <dir>/<workspace>/<project>/<run_name> — so many runs can safely share one base disk= directory without ever mixing segments.

Multiple processes logging to one run? Nothing to configure. Every logger process gets its own writer directory under the run's spool directory (<run dir>/w-<created ms>-<logger_id>-<token>/, so names sort by creation time), so distributed ranks on one host, a forked child, or a restarted process all spool the same run with the same disk= setting and never share a file. Each live process holds an exclusive lock on its writer directory from before its first byte until it exits; the kernel drops the lock with the process, so a directory that holds data with a free lock belongs to a process that is gone. That is the whole protocol — no PIDs, no heartbeats — and it drives two things:

  • Leftovers are delivered first. A process that starts online and finds earlier processes' spools under the run (its own previous incarnation, a crashed sibling) delivers them before anything of its own: it starts on its spool, its recovery channel replays the leftovers oldest first under their own writer identities, then drains its own spool and returns to gRPC. The server never sees a series' steps out of order across a restart chain. If the backend is unreachable at that start, the leftovers still identify the run, and the process continues on its spool as during any outage.
  • Cursors carry over. Every leftover's metadata is folded into the new process's, so auto-assigned steps and episodes continue where the earlier process stopped — no logger_id pinning required.
  • Offline loggers cannot deliver anything: they report leftovers at close (CloseInfo.foreign_spools), and one replay_spool of the run delivers every writer, oldest first, honoring only the newest spool's close marker.

os.fork() needs nothing special: the child's first log call rebuilds its logger with its own writer directory, offline runs included. Forked DataLoader/multiprocessing workers still shouldn't be logging metrics; the main process is the logger.

Python 3.12+ prints a DeprecationWarning here ("use of fork() may lead to deadlocks in the child"), and gRPC logs that it skipped its fork handlers. Both are generic warnings about forking a multi-threaded process, not signs of a problem: Metrana holds no lock across the fork, and the child builds its own connection rather than using the inherited one.

Where the spool lives — and why the hostname is in it. The writer lock is a flock, and a flock only means something within one machine. Over a network filesystem it may be emulated, downgraded to local-only by a mount option (-o nolock, local_lock=, Lustre's localflock), or quietly hand two hosts the same lock — and nothing in userspace can tell you which you got. The hostname in the default path is what stops that mattering: everything beneath it belongs to one kernel, so "data on disk plus a free lock = a dead writer" stays true, and no node can sweep, replay, consume or delete a spool another node is still writing.

The cost is that a restart under a new hostname — a rescheduled Deployment pod, a Slurm job requeued onto other nodes — cannot see what its predecessor left. What happens then depends on whether that spool still owes anything:

  • Nothing owed → its step cursors carry over. A spool whose data all reached the backend still records where its steps got to, and a logger on another node reads that, so auto-assigned steps and episodes continue instead of restarting at zero. This matters most for init_mode="offline" runs, which have no handshake to seed them.

  • Data still owed → init() refuses. Continuing would set this process's next step above data that has not arrived yet, and the ingestion service rejects a step below the last one it accepted — so replaying that spool afterwards would drop it, not merely deliver it late. Rather than lose it quietly, init fails and names the directory. Which fix applies depends on whose spool it is:

    • Your own run, restarting under a new hostname. Point disk= at that directory — the one carrying the old hostname. Its spool becomes this process's own leftover, so the ordinary recovery path delivers it before any new data, in order, with no manual step. The two must share an orchestration id for that: framework job ids (SLURM_JOB_ID, TORCHELASTIC_RUN_ID) survive a requeue, otherwise set METRANA_ORCHESTRATION_ID or pass resume_strategy="allow".
    • A different process that is still running. Give this one a disk= path of its own and leave that spool to its owner.

    Replaying by hand with replay_spool also works, and is the right move when you only want the data delivered and are not continuing the run.

On Slurm, key the path by node id rather than hostname. If the spool base is reachable from several machines and the hostname changes across restarts — an NFS home plus requeues is exactly that — the default will stop your restarts: each interrupted run leaves a spool the successor can neither deliver nor order itself behind, so init() raises MetranaUndeliverableSpoolError until you replay it by hand. Treat an explicit path as the required setup there, not a tuning option. $SLURM_NODEID is the node's index within the allocation, so it survives a requeue even when the physical machine does not:

import os
metrana.init(..., disk=f"/scratch/{os.environ['USER']}/metrana/{os.environ['SLURM_NODEID']}")

An explicit disk= path is used verbatim — no hostname is appended — so a requeued rank finds its own predecessor directly and gets the whole recovery path back: leftovers delivered before new data, cursors continued, directories cleaned up, no manual replay. It swaps one assumption for the lock: that the scheduler really did kill the previous allocation before starting the replacement. Schedulers do; a partitioned straggler would not. (init_mode="offline" users tend to arrive here already, since offline cannot run without a spool and raises rather than degrading; an online run takes the default silently and only meets the constraint when a restart refuses.)

If you would rather not rely on that, point disk= at node-local scratch ($TMPDIR, $SLURM_TMPDIR) — nothing is shared, so the lock is authoritative again, but the spool dies with the node, which is the persistence it exists to give you. On Kubernetes the choice is usually made for you: a StatefulSet has stable pod names (worker-0) and the default is fine, while a Deployment or Job with a PVC is the one combination where the name churns under a volume that outlives it.

How it works. While gRPC is healthy, data goes straight over the wire — the spool directory holds no points, only the run's step cursors: a small snapshot refreshed about once a minute plus an append-only journal of what changed since. That is what lets a hard kill resume where it stopped, and what a later process reads to continue your steps. When delivery gives up (the gRPC retry budget is spent), the logger fails over to the spool — every subsequent point is fsync'd to disk instead of dropped — and a background recovery channel keeps trying to re-establish gRPC. Once the wire returns it drains the spool to the backend, in order, switches delivery back to gRPC, and reclaims the disk as it goes.

Because the spool sits behind the delivery decision, it protects against every backend-side failure, not just network blips — including ones retries alone can never fix: an expired token, an accidentally revoked authorization, an unauthenticated rejection, a backend refusing requests, a regional outage. The data waits on disk and the recovery channel retries reconnecting indefinitely, so the moment the problem is fixed (token rotated, permissions restored) the backlog ships automatically. Nothing is dropped while there is room on disk (bounded by max_size_bytes).

If the outage outlasts the run — you close() (or the process ends) while data is still stranded — Metrana warns, and the CloseInfo reports has_undelivered_spool. The data is safe on disk; deliver it later by replaying the spool:

import metrana

# Re-deliver a leftover spool to its run. No prior init() needed; the identity args must
# match the run that produced the spool. Omit the path for a run that used the default spool.
info = metrana.replay_spool(
    "/var/spool/metrana",
    workspace_name="my-team",
    project_name="my-project",
    run_name="run-2026-06-28",
    api_key="...",            # or via METRANA_API_KEY
)
print(info.metrics.float_points_sent, "points re-delivered")

The spool is durable across process restarts: if a process dies while data is spooled and the next process starts with the same disk= directory, it resumes from the leftover spool and keeps delivering — no manual replay needed for the crash-and-restart case.

Offline logging

An offline run never talks to the backend while it runs: everything lands on the spool, and the run is created on the backend later, when you replay the spool from a machine that can reach it. It is how you use Metrana from an air-gapped cluster. init_mode (also METRANA_INIT_MODE) picks the start mode:

  • "online_only" (default): the handshake must succeed within init_timeout_secs, any failure raises MetranaLoggerInitError. There is deliberately no automatic fallback to offline: a mistyped endpoint or a revoked key fails loudly instead of silently producing an offline run. If the service is slow to come up when your job starts, raise init_timeout_secs.
  • "offline": never contact the backend. Requires a spool.
metrana.init(..., init_mode="offline", disk="/scratch/metrana-spool")
metrana.log("loss", 0.42)        # lands on the spool
print(metrana.is_offline())      # True
metrana.close()                  # logs where the spool is, no warning

Size the spool for the whole run. The 8 GiB default assumes the recovery channel is reclaiming space as it delivers — offline it never runs, so nothing is freed until you replay and the cap is the total budget for everything the run will ever log. Reaching it stops the run under the delivery policy. Spooled points cost roughly 3 bytes each (~9 on the wire, ~3x from zstd), so 8 GiB is a few billion points: years of ordinary ML logging, but only about 30 hours of high-fanout RL (1024 envs x 16 metrics x 100 minor points a minute is ~27K points/s). Starting offline on the default cap logs a warning for this reason. Set max_size_bytes accordingly before starting an air-gapped run:

metrana.init(..., init_mode="offline",
             disk=metrana.DiskConfig("/scratch/metrana-spool", max_size_bytes=64 << 30))

Offline, the run has no id yet, rendering upload is disabled (videos stay on local disk), and forks are refused — a forked run starts from its parent's cursors, which only the backend knows. A restart on the same spool continues the offline run whatever init_mode it configures. Deliver it with metrana.replay_spool(...) exactly as above: the replay performs the handshake the run skipped, with the parameters persisted next to the spool — it creates the run, delivers every record under the id the backend allocated, and closes the run if the offline process did. A backend rejection surfaces from replay_spool as the matching init error and leaves the spool intact; a fully delivered spool is consumed (its files are removed), so replay is the last step for a finished run — a later init() on the same disk path starts fresh and online rather than resuming the delivered run. Several processes may start the same run offline (own writer spool each, shared orchestration_id): one replay_spool of the run delivers every writer in turn — the first creates the run and later ones attach to it by that id; a same-named run owned by another job is refused, never overwritten.

Logging at scale

When you log a lot — many series, high step rates, many environments — a few habits keep the overhead negligible:

  • Log in bulk, not point-by-point. Every log call crosses from Python into the engine; one call with an array amortizes that far better than a loop of scalar calls. Pass a 1-D array of values (with a matching step range or array) instead of calling log once per step, and for RL prefer the vectorized log_rl_environment_step(..., env_id=[...], value=grid) over a per-env loop — it takes a [num_envs, T] block in a single call (see Logging RL metrics). Contiguous arrays already in the target dtype (float32 by default) are handed to the engine without a copy, so wide batches are cheap.
  • Don't flush on the hot path. flush() is a synchronous barrier — it waits for delivery / durability, so calling it every step serializes your loop against the network. Flush at checkpoints (or every few minutes), not every step; let the background engine batch and stream everything in between.
  • Give the engine room. Under sustained high rates raise queue_capacity (more buffer before backpressure) and max_pending_requests (more in-flight streams); batch_max_age_secs controls how long points coalesce before a send. Watch get_metrics() (added vs sent, and *_dropped) to confirm you are keeping up — see Tuning and observability.

Tuning and observability

  • max_pending_requests (default 30): in-flight streaming requests — raise it to push more throughput when the backend is the bottleneck.
  • queue_capacity (default 10_000): in-process point buffer depth.
  • batch_max_age_secs (default 1.0): how long points wait to coalesce into a batch before sending.
  • max_msg_size: max serialized request size in bytes.

metrana.get_metrics() returns a point-in-time snapshot of the engine's self-metrics. For each data kind (float_points, rl_float_points, attribute_updates, env_attribute_updates) it reports how much was added (attempted), enqueued, sent (server-acked over gRPC), and dropped (shed under backpressure or after a channel gave up). With a disk spool configured it also reports disk_persisted (made durable on the spool, not yet seen by the backend) and the recovery counters recovered_spool_segments / recovered_spool_messages (drained from the spool back to the backend), alongside transport/health counters (connection_attempts, requests_sent, send_errors).

Comparing added vs sent tells you whether anything was lost:

m = metrana.get_metrics()
print(m.float_points_added, m.float_points_sent, m.float_points_dropped)

The counters are monotonic, so diff two snapshots over a window to get rates (e.g. for a periodic health log):

import time

prev = metrana.get_metrics()
time.sleep(10)
now = metrana.get_metrics()
sent_per_sec = (now.float_points_sent - prev.float_points_sent) / 10
backlog = now.float_points_added - now.float_points_sent      # added but not yet acked
if now.float_points_dropped > prev.float_points_dropped:
    print("data loss in the last window — enable a disk spool, or raise queue_capacity / retries")

Querying your data

Everything above writes. The metrana.query subpackage reads — projects, runs, RL environments and series come back as pandas DataFrames, ready for analysis. It is pure Python (gRPC + protobuf + numpy/pandas) and ships as an optional extra, so training images that only log never carry the analysis stack:

pip install 'metrana[query]'
from metrana.query import QueryClient

client = QueryClient(workspace_name="my-team", project_name="my-project")   # api_key from METRANA_API_KEY

runs = client.fetch_runs(max_runs=20)                          # a table of runs
loss = client.fetch_float_series(runs["name"].tolist(), "loss")  # their loss curves

The client is bound to one workspace for its lifetime — an API key is workspace-scoped, so reading another workspace means another key and another client. The project is only a default: every method takes a project_name= override. workspace_name, project_name, api_key and query_url all fall back to environment variables (see Environment Variables).

Ingestion is asynchronous, so data logged moments ago may not be queryable yet. This API is for analysis, not for reading back what a live training process just wrote.

Method families

The name tells you the shape of the answer:

prefix returns examples
fetch_ a 2-D DataFrame fetch_runs, fetch_float_series
list_ a 1-D list or dict list_experiments, list_run_attributes
get_ a single record get_rl_info

Tables: projects, runs, environments

client.fetch_projects()                       # one row per project
client.list_experiments()                     # experiment names in the project
client.fetch_runs(
    filter=AttrFilter("config/lr") < 0.01,
    order_by=SeriesOrderBy("loss", "last").asc(),
    attributes=["sys/status", "config/lr"],    # attribute columns
    series_summaries=[SeriesSummary("loss", "last")],  # summary columns
    max_runs=50,
)

attributes= and series_summaries= also accept an AttributeFilter / MetricFilter, which is resolved against the project's definitions before fetching — "every config/* attribute", "every metric matching this regex" — so you don't have to enumerate columns you don't know yet.

Filters and ordering

filter= and order_by= take typed builders. They cover the query grammar, validate client-side, and escape values correctly — there is no raw-string form:

from metrana.query import AttrFilter, AttrOrderBy, SeriesFilter, SeriesOrderBy

AttrFilter("config/lr") < 0.01                       # comparisons: < <= > >= == !=
AttrFilter("sys/tags").contains_all(["baseline"])     # string sets
AttrFilter("sys/name").matches("^ablation-")          # RE2 regex, server-side
AttrFilter("config/seed").is_in([0, 1, 2])
AttrFilter("config/dropout").exists()

# Combine with & and | — NOT `and`/`or`, which cannot be overloaded and would
# silently evaluate the wrong thing (so a Condition refuses to be truthy).
(AttrFilter("sys/status") == "CLOSED") & (SeriesFilter("loss").last() < 0.1)

AttrOrderBy("sys/creation_time").desc()
SeriesOrderBy("accuracy", "max").desc()

Series conditions (SeriesFilter, SeriesOrderBy) are valid for runs and RL environments; the listings that accept attributes only reject them client-side rather than at the server.

Series

Five ways to read series, differing in what they give you per step:

# Raw points — index (run, step), one column per matched series.
client.fetch_float_series("run-001", ["loss", "accuracy"])

# Chart-shaped: compressed into a fixed number of buckets, with min/max/count per bucket.
client.fetch_float_series_buckets("run-001", "loss", buckets_count=500)

# One number per series per run — the runs-table columns, in bulk.
client.fetch_series_summaries(["run-001", "run-002"], "loss", functions=["last", "min", "max"])

# Whole histograms — bins and edges per step, as metrana.Histogram objects.
client.fetch_histogram_series("run-001", "weights/l0")

# Whole scatter point sets — parallel coordinate arrays per step, axis titles in frame.attrs.
client.fetch_scatter_series("run-001", "latents")

fetch_float_series_buckets also picks the x axis — x_mode=XAxisMode.STEP (default), ABSOLUTE_TIME (wall clock), or RELATIVE_TIME (elapsed time from the series' first point):

from metrana.query import XAxisMode, LastSteps

client.fetch_float_series_buckets(["run-001", "run-002"], "loss",
                                  x_mode=XAxisMode.RELATIVE_TIME, buckets_count=300)
client.fetch_float_series("run-001", "loss", steps=LastSteps(1000))     # tail of the run

A SeriesQuery picks series more precisely than a bare name — scale, labels (any operator, and partial), and histogram reduction:

from metrana.query import SeriesQuery, HistogramReducer

SeriesQuery("reward").with_scale("EPISODE").with_label("policy", "greedy")
SeriesQuery("reward").with_label_matches("policy", "^greedy")
SeriesQuery("weights/l0").reduce_histogram(HistogramReducer.quantile(0.95))  # histogram -> floats

Series fetches read at most 1000 runs. That is the query service's own limit, and it is a hard error rather than a silent truncation — a chart quietly missing runs is worse than one that refuses to draw. Narrow the filter, or pass max_runs= to take the first N in order_by order:

from metrana.query import RunsSelection

client.fetch_float_series(
    RunsSelection(filter=AttrFilter("sys/status") == "CLOSED",
                  order_by=SeriesOrderBy("accuracy", "max").desc()),
    "accuracy", max_runs=100,      # best 100 by accuracy
)

RL environments

RL selectors must pin a scale. log_rl_environment_step writes at ENVIRONMENT_STEP and log_rl_episode at EPISODE, while a selector naming no scale means ML_STEP — which no RL series has, so it would match nothing. The client cannot know which a metric used, so it rejects the call rather than returning an empty frame. This covers every RL selector: series, summary columns, SeriesFilter, SeriesOrderBy and group_by conditions. A MetricFilter is exempt — it takes the scale from the definitions it resolves against.

reward = SeriesQuery("reward").with_scale("ENVIRONMENT_STEP")

info = client.get_rl_info("rl-001")                 # env count, latest episode / rl_step
client.fetch_rl_envs("rl-001", at=Episode(12))      # the environments table at an episode

# Per-environment series (the env-level counterpart of fetch_float_series_buckets)
client.fetch_rl_env_float_series_buckets("rl-001", ["envA", "envB"], reward, at=RLStep(40))

# One series reduced ACROSS environments into chart lines
client.aggregate_rl_env_series("rl-001",
                               SeriesSummary("reward", "avg").with_scale("ENVIRONMENT_STEP"),
                               EpisodeRange(0, 100),
                               aggregations=["avg", "std"], group_by=["cfg/policy"])

at= selects the slice: Episode(n) or RLStep(n), defaulting to the latest.

Discovery

Before you can filter on an attribute or fetch a series, you need to know what exists. The list_* family answers that, and each takes the same narrowing arguments (prefix, regex, kinds):

client.list_run_attribute_definitions()            # paths + kinds runs carry
client.list_project_attribute_definitions()
client.list_rl_env_attribute_definitions("rl-001")
client.list_metric_definitions(prefixes=["train/"]) # metrics + their label keys
client.list_rl_env_metric_definitions("rl-001")
client.list_series_definitions(run="run-001")       # metrics with label values pinned
client.list_series_label_values("run-001", "policy")
client.list_run_attributes("run-001")               # values for ONE run
client.list_rl_env_attributes("rl-001", "envA")

Traces

Agent traces come back in three steps: the trace list, one trace's tree, its bodies.

from metrana.query import AttrFilter, SpanFilter, SpanOrderBy, TracePayloadKind

traces = client.fetch_spans(                        # one row per trace (root span)
    runs="grpo-7b-v2",                              # up to 10 runs; empty for the project's inference traces
    filter=(SpanFilter.step >= 1000) & (AttrFilter("reward") >= 0.5),
    order_by=SpanOrderBy.step.asc(),
    attributes=["reward"],
)
tree = client.fetch_trace_spans(traces.iloc[0]["trace_id"], run="grpo-7b-v2")   # every span, root first
bodies = client.fetch_span_payloads(tree.iloc[0]["trace_id"], tree["span_id"].tolist(), run="grpo-7b-v2")
bodies[(1, TracePayloadKind.LLM_PROMPT)].body       # {(span_id, kind): SpanPayload}

SpanFilter covers the span's own fields (op_name, step, status, kind, duration, token_count, span_count, iteration_count); AttrFilter the attributes you logged on spans. include_children=True searches spans rather than traces, and then the filter must name the ops (SpanFilter.op_name == ... as a top-level & term). list_tracing_op_names and list_tracing_attribute_definitions list the names those filters take; run=None on any of these names the project's own traces.

Errors

Every failure is a MetranaQueryError subclass, so one except catches the API:

Exception Raised when
ConfigError Missing workspace/project, or a malformed endpoint URL.
TransportError The connection fails and retries are exhausted.
RpcError The server answers with a non-OK status after retries.
QueryValueError An argument's value is unusable (unknown enum spelling, out-of-range bound, a selector this endpoint cannot express).
QueryTypeError An argument is of the wrong type, or a builder is used in a context that does not accept it.

QueryValueError and QueryTypeError also subclass the built-in ValueError / TypeError, so ordinary handlers still catch them.

TLS

HTTPS endpoints trust the system store, the roots bundled with gRPC, and — on macOS — certificates installed in the admin keychain, which Python's ssl module does not see. Behind a TLS-inspecting proxy or a private CA, point the client at a PEM bundle with ca_bundle=, SSL_CERT_FILE, REQUESTS_CA_BUNDLE, or GRPC_DEFAULT_SSL_ROOTS_FILE_PATH.

Environment Variables

Variable Equivalent init() argument
METRANA_API_KEY api_key
METRANA_ORCHESTRATION_ID orchestration_id
METRANA_INGESTION_URL ingestion_url
METRANA_ARTIFACT_API_URL artifact_api_url
METRANA_QUERY_API_URL query_api_url
METRANA_BACKPRESSURE_STRATEGY backpressure_strategy
METRANA_DELIVERY_POLICY delivery_policy
METRANA_RENDERING_ERROR_STRATEGY rendering_error_strategy
METRANA_RESUME_STRATEGY resume_strategy
METRANA_LOG_LEVEL log_level
METRANA_EVENT_QUEUE_MAX_SIZE queue_capacity
METRANA_SKIP_DRAIN_RENDER_ON_CLOSE skip_drain_render_on_close
METRANA_RENDERING_CLOSE_TIMEOUT rendering_close_timeout

The tracer reads the delivery ones (METRANA_API_KEY, METRANA_INGESTION_URL, METRANA_BACKPRESSURE_STRATEGY, METRANA_DELIVERY_POLICY, METRANA_LOG_LEVEL) through tracing.init(), plus two of its own:

Variable Meaning
METRANA_TRACING_DISABLED 1 / true: no tracer is built, every trace and span is inert
METRANA_TRACING_SAMPLE_RATE tracing.init(sample_rate=...) when not given; 1.0 by default

The query client reads its own:

Variable Equivalent QueryClient() argument
METRANA_API_KEY api_key
METRANA_WORKSPACE workspace_name
METRANA_PROJECT project_name
METRANA_QUERY_API_URL query_url
SSL_CERT_FILE / REQUESTS_CA_BUNDLE / GRPC_DEFAULT_SSL_ROOTS_FILE_PATH ca_bundle

The artifact, video and query helpers fall back to the endpoint given to init() before their own environment variable, so base_url / query_url need only be passed to override it.

Metadata

Release files for metrana 1.9.1

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

Source distribution (sdist)

Source distribution for metrana 1.9.1
File Size Uploaded Provenance Actions
metrana-1.9.1.tar.gz 363.3 kB Without provenance Details for metrana-1.9.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for metrana 1.9.1
File Interpreter ABI Platform Actions
metrana-1.9.1-py3-none-any.whl Python 3 none any Details for metrana-1.9.1-py3-none-any.whl

Total release size: 694.5 kB

Release files / metrana-1.9.1.tar.gz

Download URL metrana-1.9.1.tar.gz
Size 363.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b582ccc88747c02b86a8d672d9775d7fd23116bf1b2c8f30e43bde4e9e7608ab
BLAKE2b-256 checksum
How to use checksums
12054b7527d0a871bea631fcbf59ed01bbb53fc30af6a0e80c0abf7db2ee041d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Release files / metrana-1.9.1-py3-none-any.whl

Download URL metrana-1.9.1-py3-none-any.whl
Size 331.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eb3e44e52d13c76fa60ceef6b2ac5dfd9984a19ab53a6b30989c01f32f353801
BLAKE2b-256 checksum
How to use checksums
81b9c8f136bd0451eb1bbfc2ee02f1dd0454c62dd55ebe31d5324076599f0ed1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Security for metrana 1.9.1

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.

Release history Release notifications | RSS feed

This release

1.9.1 This release

2 release files No provenance

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