Skip to content

Python API

Generated from the docstrings. Names without a module, such as install, are importable from polars_telemetry; the others show their module.

Instrumenting

install

install(
    config: Config | None = None,
    exporter: Exporter | Sequence[Exporter] | None = None,
) -> Installation | None

Instrument every polars query this process runs.

Parameters:

  • config (Config | None, default: None ) –

    What to record. Defaults to Config().

  • exporter (Exporter | Sequence[Exporter] | None, default: None ) –

    Where queries go: one exporter or several. Defaults to OTelExporter.

Returns:

  • Installation | None –

    What was installed, including what the probe found about this polars; None when this polars cannot be instrumented at all.

Enabling polars' monitoring sets its engine affinity to "streaming", so this changes how queries execute and never happens on import. Calling it again while installed logs a warning and changes nothing.

uninstall

uninstall() -> None

Stop instrumenting, and hand queries back to Polars Nanook if it was there.

The engine affinity goes back to what it was before install(), unless the application chose another engine in the meantime.

Config

Config(
    node_metrics: bool = True,
    include_plan: bool = False,
    call_site: bool = True,
    describe_fallbacks: bool = True,
    insights: bool = True,
    progress_interval: float = 1.0,
    redaction: Redaction | None = None,
)

What to record about each query. Every field has a working default.

node_metrics

node_metrics: bool = True

Read per-node counters once when the query ends.

polars exposes cumulative counters and no per-node timestamps, so these are exact totals with no timing. Disable to emit the query span alone.

include_plan

include_plan: bool = False

Attach the full plan and its counters to the span as JSON.

Off by default: it is kilobytes per span and identical for every run of a shape. Turn it on when you want the topology, which nothing else carries.

call_site

call_site: bool = True

Record the file, line and function that ran the query.

Costs well under a microsecond. Turn it off to keep source paths out of telemetry you do not control.

describe_fallbacks

describe_fallbacks: bool = True

Have polars describe what an in-memory fallback node runs.

polars leaves such a node unnamed unless asked: this sets POLARS_STREAM_ALWAYS_PREPARE_VISUALIZATION_DATA=1 at install() when it is unset. The variable is undocumented, costs a fraction of a millisecond per query, and polars keeps it on for the process once it has read it.

insights

insights: bool = True

Find what slows each query down, as polars-telemetry insights does.

Runs once the query has finished, after its wall time is measured: a few milliseconds even for a plan of a thousand nodes. Findings carry numbers and node kinds only.

progress_interval

progress_interval: float = 1.0

Seconds between samples of a running query, for exporters that record progress, such as FileEventExporter.

One background thread samples every running query and hands each sample to every such exporter. A query that ends before its first sample is never announced as running. A sample costs well under a millisecond for a small plan and about 15 ms for 500 nodes.

redaction

redaction: Redaction | None = None

What to mask before any exporter receives a query; None masks only URL query strings, which can hold credentials.

Redaction() masks literal values. One exporter can be given its own with redacted(). Metrics never carry literals, whatever this says.

polars_telemetry.activation.Installation

Installation(
    binding: Binding,
    config: Config,
    capabilities: Capabilities,
    exporters: tuple[Exporter, ...] = (),
    scoped: bool = False,
    receivers: tuple[Receiver, ...] = (),
    before: Before | None = None,
)

What install() put in place.

scoped

scoped: bool = False

Made by a profile() block, not by the application; the last block to close takes it back out.

polars_telemetry.compat.Capabilities

Capabilities(
    polars_version: str,
    has_monitoring_api: bool,
    observer_callbacks_ok: bool = False,
    plan_payload_ok: bool = False,
    ir_payload_ok: bool = False,
    metrics_snapshot_ok: bool = False,
    problems: tuple[str, ...] = (),
)

Result of probing the installed polars.

ir_payload_ok

ir_payload_ok: bool = False

The IR carries the user's own column names; without it, span attributes fall back to the physical plan's _POLARS_TMP_N names.

Masking

Redaction

Redaction(
    strings: bool = True,
    numbers: bool = True,
    temporal: bool = True,
    paths: bool = False,
    call_site: bool = False,
    labels: bool = False,
    custom: Callable[[str], str] | None = None,
    url_queries: bool = True,
)

What to mask before a query reaches an exporter.

The default masks literal values: text, numbers, and dates and times. Column names, operators and the plan's shape are always kept, so a masked query still shows which filter was slow.

Examples:

>>> Redaction()  # literal values
>>> Redaction(numbers=False)  # keep numbers, mask the rest
>>> Redaction(paths=True, call_site=True, labels=True)  # as little as possible

strings

strings: bool = True

Quoted text such as "Brand#12" becomes "<str>". Column and alias names are kept.

numbers

numbers: bool = True

Numbers such as 60.0 or 1.0000e-9 become <num>.

temporal

temporal: bool = True

Dates, datetimes, times and durations become <date>, <datetime>, <time> and <duration>.

paths

paths: bool = False

File paths that are scanned or written become <path>, and so do a plugin's library path in an expression and any path or URL in an error message.

call_site

call_site: bool = False

Drop the file, line and function that ran the query.

labels

labels: bool = False

Drop labels set with label().

custom

custom: Callable[[str], str] | None = None

Your own rule, applied to every expression and error message after the masks above.

url_queries

url_queries: bool = True

A URL's query string becomes ?<query>: in a presigned or SAS URL it is a credential. On for every receiver, with or without a redaction, unless a redaction turns it off.

masks

masks: tuple[str, ...]

What this masks, by field name, for a reader to show.

redacted

redacted(
    exporter: Exporter, redaction: Redaction | None
) -> Redacted

Give one exporter its own redaction, in place of Config.redaction.

Examples:

>>> polars_telemetry.install(
...     Config(redaction=Redaction()),
...     exporter=[
...         redacted(OTelExporter(config), Redaction(paths=True, call_site=True)),
...         redacted(FileExporter("profiles/full.jsonl"), None),
...     ],
... )

Parameters:

  • exporter (Exporter) –

    Any exporter.

  • redaction (Redaction | None) –

    What to mask for this exporter; None sends it everything but URL query strings, whatever Config.redaction says.

Returns:

  • Redacted –

    The exporter, to pass to install().

Labelling and scoping

label

label(name: str) -> Iterator[None]

Label every query run inside the block.

Examples:

>>> with label("etl"), label("customers"):
...     frame.collect()  # labelled "etl/customers"

Parameters:

  • name (str) –

    Any non-empty text. Nested labels are joined with /.

Raises:

  • ValueError –

    If name is empty or not a string.

The label goes on the query's span as polars.query.label and into its profile, but never onto metrics: free-form values would make unbounded metric series. Each thread has its own labels. Queries run with collect_async() or collect_batches() carry none: polars reports those from its own threads.

profile

profile(config: Config | None = None) -> Iterator[Session]

Collect every query run inside the block.

Examples:

>>> with profile() as session:
...     frame.collect()
>>> session.slowest.call_site

Parameters:

  • config (Config | None, default: None ) –

    Used when nothing is installed yet; an existing installation keeps its own. The session masks what the installation masks and what config.redaction adds.

Queries still reach any exporters already installed, and blocks may nest. If nothing was installed, instrumentation is installed for the block and removed after it. A block collects every query that finishes while it is open, including ones other threads ran.

Session

Session()

The queries that ran inside a profile() block, in the order they finished.

Iterate it, index it or take its len() like a list of Query.

slowest

slowest: Query | None

The query with the longest wall time, or None if none ran.

wall_ms

wall_ms: float

Summed wall time. Not elapsed time: queries may overlap.

profiles

profiles() -> list[dict[str, Any]]

Each query as a profile document, the format the viewer reads.

Literals are already masked if the block's config asked for it.

write

write(path: str | Path) -> Path

Write the queries to a .jsonl file the viewer can open.

Parameters:

  • path (str | Path) –

    Where to write. An existing file is replaced.

Returns:

  • Path –

    The path written.

Exporters

polars_telemetry.export.otel.OTelExporter

OTelExporter(config: Config)

One span per query and per-node metrics, through OpenTelemetry.

Uses the global tracer and meter providers, so the application's OpenTelemetry SDK decides where they go. Without an SDK installed, both are no-ops and nothing is sent.

Parameters:

  • config (Config) –

    Only include_plan is read from it, and redaction when install()'s config has none; every other option comes from the config given to install().

config

config: Config

The configuration this exporter was made with.

polars_telemetry.export.dogstatsd.DogStatsdExporter

DogStatsdExporter(
    client: StatsdClient | None = None,
    *,
    metric_names: Mapping[str, str | None]
    | Callable[[str], str | None]
    | None = None,
    tag_names: Mapping[str, str | None] | None = None,
    tag_labels: bool = False,
    distributions: bool = True,
)

Per-query and per-node metrics as DogStatsD, with tags.

Totals are sent as counts; times and ratios as distributions, or as histograms with distributions=False.

Parameters:

  • client (StatsdClient | None, default: None ) –

    A datadog.DogStatsd. Defaults to datadog.statsd, the client datadog.initialize() configures. Turn on its buffering and background sender, so sending happens off the query's thread.

  • metric_names (Mapping[str, str | None] | Callable[[str], str | None] | None, default: None ) –

    Renames metrics, from their names in Spans and metrics. A mapping or a function; a name mapped to None is not sent.

  • tag_names (Mapping[str, str | None] | None, default: None ) –

    Renames tag keys: engine, fingerprint, node_kind, direction, rule and level. A key mapped to None is not sent, such as {"fingerprint": None} to keep one series per query shape off a bill.

  • tag_labels (bool, default: False ) –

    Also tag every metric with the query's label. Labels are free-form, so only do this when yours come from a small, fixed set.

  • distributions (bool, default: True ) –

    Send times and ratios as distributions (|d), which Datadog aggregates across hosts. False sends histograms (|h), which Telegraf summarises per flush; Telegraf keeps only one sample of a distribution per flush.

close

close() -> None

Send what the client still holds. Called by uninstall() and at exit.

polars_telemetry.export.file.FileExporter

FileExporter(
    path: str | Path, *, max_bytes: int = DEFAULT_MAX_BYTES
)

Append one profile per query to a .jsonl file the viewer can open.

Parameters:

  • path (str | Path) –

    The session file. Its directory is created if missing.

  • max_bytes (int, default: DEFAULT_MAX_BYTES ) –

    64 MiB by default. When the file would grow past this, it moves to <name>.1, replacing the previous one, and a new file starts. At most about twice this is on disk. A profile is never split, so a file can run over by one record.

path

path: Path

The file being written.

polars_telemetry.export.events.FileEventExporter

FileEventExporter(
    path: str | Path,
    *,
    service: str | None = None,
    environment: str | None = None,
    max_bytes: int = DEFAULT_MAX_BYTES,
)

Append the life of every query to a .jsonl or .jsonl.gz file.

Parameters:

  • path (str | Path) –

    The events file. Its directory is created if missing. A name ending in .gz is written compressed.

  • service (str | None, default: None ) –

    What the process is, such as "orders-etl". Written on the process line so a dashboard can group by it.

  • environment (str | None, default: None ) –

    Where it runs, such as "prod". Also on the process line.

  • max_bytes (int, default: DEFAULT_MAX_BYTES ) –

    256 MiB by default. When the file would grow past this, it moves to <name>.1, replacing the previous one, and a new file starts.

path

path: Path

The file being written.

errors

errors: int

How many writes have failed.

close

close() -> None

Write what is buffered. uninstall() calls it, and so does exit.

polars_telemetry.export.http_events.HttpEventExporter

HttpEventExporter(
    url: str,
    *,
    token: str | None = None,
    service: str | None = None,
    environment: str | None = None,
    max_queue_bytes: int = DEFAULT_MAX_QUEUE_BYTES,
    timeout: float = 10.0,
)

Send the life of every query to a server that receives polars-telemetry/events@1.

Parameters:

  • url (str) –

    The server, such as "https://events.example.com". Events go to {url}/v1/events.

  • token (str | None, default: None ) –

    Sent as Authorization: Bearer <token>. Read from the POLARS_TELEMETRY_TOKEN environment variable when not given.

  • service (str | None, default: None ) –

    What the process is, such as "orders-etl".

  • environment (str | None, default: None ) –

    Where it runs, such as "prod".

  • max_queue_bytes (int, default: DEFAULT_MAX_QUEUE_BYTES ) –

    16 MiB by default. Events waiting to be sent beyond this are dropped, progress samples first.

  • timeout (float, default: 10.0 ) –

    Seconds to wait for the server on each request.

errors

errors = 0

How many requests have failed.

dropped

dropped = 0

How many events were dropped without being sent.

close

close() -> None

Send what is queued, for at most two seconds. Called by uninstall() and at exit.

polars_telemetry.export.console.ConsoleExporter

ConsoleExporter(stream: TextIO | None = None)

Print a short summary of each query: totals, call site, slowest nodes.

Parameters:

  • stream (TextIO | None, default: None ) –

    Where to write. Defaults to standard error.

polars_telemetry.export.base.Exporter

Anything with an export(query) method can receive queries.

An exporter that holds data, such as a buffer, may also have a close() method. uninstall() calls it, and so does the process on exit.

To follow queries while they run, an exporter may also have started(query), called with the plan at a query's first sample, and progress(progress), called at every sample from that one on. Both run on a background thread, and never after the query's export().

export

export(query: Query) -> None

Handle one finished query.

Called on the thread that ran the query, once per query, after it has finished, so the time spent here is added to the caller's. An exception is logged and counted; after five, this exporter stops receiving queries and the others carry on.

What an exporter receives

polars_telemetry.model.types.Query

Query(
    query_id: UUID,
    wall_ms: float,
    plan: dict[int, PlanNode],
    logical: dict[int, PlanNode] = dict(),
    metrics: dict[int, NodeMetrics] = dict(),
    call_site: CallSite | None = None,
    label: str | None = None,
    engine: str | None = None,
    polars_version: str = "",
    fingerprint: str = "",
    diagnostics: Diagnostics | None = None,
    failed: str | None = None,
    redaction: Redaction | None = None,
    started_unix_ns: int = 0,
    insights: tuple[Finding, ...] | None = None,
    planning_ms: float | None = None,
    telemetry_ms: float | None = None,
    query_metrics: dict[str, int] | None = None,
    parent_query_id: UUID | None = None,
)

One finished query, as every exporter receives it.

query_id

query_id: UUID

polars' id for the query: a UUIDv7, so ids sort by start time.

wall_ms

wall_ms: float

Time from start to finish, in milliseconds.

plan

plan: dict[int, PlanNode]

Physical plan, by node id; empty when the query did not run on the streaming engine. Node ids here are what metrics key on.

logical

logical: dict[int, PlanNode] = field(default_factory=dict)

IR plan. Carries the user's own column names; the physical plan rewrites group-by keys and aggregations to _POLARS_TMP_N.

call_site

call_site: CallSite | None = None

Where in the caller's code the query ran.

label

label: str | None = None

What the application called it, via polars_telemetry.label().

engine

engine: str | None = None

The polars engine that ran it; None when it failed before planning.

polars_version

polars_version: str = ''

The polars that ran it. Carried here so nothing downstream imports polars.

fingerprint

fingerprint: str = ''

The plan shape, hashed once on arrival; empty on a Query built by hand.

diagnostics

diagnostics: Diagnostics | None = None

Derived once on arrival, so every exporter reports the same figures.

failed

failed: str | None = None

polars' error message when the query failed, else None.

redaction

redaction: Redaction | None = None

What was masked before this reached the exporter, else None.

started_unix_ns

started_unix_ns: int = 0

When the query started, in nanoseconds since the Unix epoch.

insights

insights: tuple[Finding, ...] | None = None

Findings about the plan, most important first; None when not computed.

planning_ms

planning_ms: float | None = None

From the start to polars handing over the plan to run: optimisation and lowering. None when the query failed before planning.

telemetry_ms

telemetry_ms: float | None = None

polars-telemetry's own work before execution, within wall time.

query_metrics

query_metrics: dict[str, int] | None = None

polars' query-level counters as sent, such as IO time in flight across all nodes; None when polars sends none.

parent_query_id

parent_query_id: UUID | None = None

The query this one ran inside, from a Python UDF of that query.

cpu_ms

cpu_ms: float

Summed node self time. Exceeds wall time on a parallel query.

result_rows

result_rows: int | None

Rows reaching the sink, when the sink reported any.

hottest

hottest: tuple[PlanNode, NodeMetrics] | None

The node with the most self time -- usually the whole answer.

polars_telemetry.model.insights.Finding

Finding(
    rule: str,
    kind: Kind,
    level: Level,
    node_id: int,
    node_kind: str,
    impact: Impact,
    title: str,
    fix: str,
    evidence: tuple[Measure, ...] = (),
    node_ids: tuple[int, ...] = (),
)

One observation about one node. Text carries numbers, node kinds and API names only.

node_ids

node_ids: tuple[int, ...] = ()

Every node the finding covers, when one finding stands for the same finding on several.

polars_telemetry.model.types.CustomMetric

CustomMetric(key: str, unit: str, value: int | None)

A figure a node reports about itself, named by polars, such as group_by.actual_groups. Unit "1" is a count, "By" bytes, "ns" a duration.

polars_telemetry.model.types.Progress

Progress(
    query_id: UUID,
    elapsed_ms: float,
    nodes: dict[int, NodeMetrics],
)

A sample of a running query's counters.

Counters are cumulative, so any sample may be dropped without losing what the next one says.

elapsed_ms

elapsed_ms: float

Since the query started.

nodes

nodes: dict[int, NodeMetrics]

Nodes whose counters changed since the previous sample of this query; every node in the first.