Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

feature/Analytics-groups-field · L-260922-88ea2c (#1230)

Louis Choquel77d34b12a541
diff --git a/.drift/acks/pipelex-kernel-docs.toml b/.drift/acks/pipelex-kernel-docs.toml
index c4ec93e12..f1b31220b 100644
--- a/.drift/acks/pipelex-kernel-docs.toml
+++ b/.drift/acks/pipelex-kernel-docs.toml
@@ -1,8 +1,8 @@
contract = "pipelex-kernel-docs"
-digest = "sha256:b71924eeeafa924135c4e1658e999cb8591249a729083996bb01291f6f315096"
-reviewed_by = "Claude (Opus 5)"
-reviewed_at = "2026-09-18T19:26:43Z"
-rationale = "ConceptProviderAbstract gained list_concept_keys_for_ref, so the boot-contract test's NativeOnlyConceptProvider implements it, returning an empty list — a provider that builds native concepts on demand stores none under a key. docs/under-the-hood/pipelex-kernel.md describes that smallest provider under shape_inputs and now names the enumeration beside the three capabilities it already listed; nothing else in the doc touches the provider surface."
+digest = "sha256:38318fc12f2f5c8bc54359c7b41dddf7c81e3cbddc177a9c8c9f3bf087b525c5"
+reviewed_by = "Louis Choquel"
+reviewed_at = "2026-09-22T11:22:02Z"
+rationale = "PipelexKernel.make gained an optional analytics_groups parameter, the opaque host-supplied group mapping, carried onto RunMetadata beside user_id and storage_scope. The kernel doc's run-scoped-state bullet already listed analytics_groups among what run_metadata holds and now also says the host supplies it at make time, which is the seam a multi-tenant embedder needs. The parameter is optional and defaults to an empty mapping, so the doc's two make examples stay correct unchanged."
[trigger_files]
"pipelex/kernel/__init__.py" = "blob:c4f1b0fe2ccc17db9110733f71b612f4ac1ba4ce"
@@ -20,7 +20,7 @@ rationale = "ConceptProviderAbstract gained list_concept_keys_for_ref, so the bo
"pipelex/kernel/llm_prompt_content.py" = "blob:82c34283dacd2bfd9a2c263915e744736d399875"
"pipelex/kernel/llm_results.py" = "blob:6e3b8a2878b5bb284ece5fac10262fb59ac2029d"
"pipelex/kernel/memory_ops.py" = "blob:f6a5745e804ac08f19c70f1beb1f78baf50d51cd"
-"pipelex/kernel/pipelex_kernel.py" = "blob:93b02410886a1f81d4a32c135bcbc35896417af3"
+"pipelex/kernel/pipelex_kernel.py" = "blob:622c379bd9d1bf0041b192275b5aa3b37a7a5ea5"
"pipelex/kernel/prompt_references.py" = "blob:03ec9ef67ae84f141d072ca2d2c3ef888549ccc0"
"pipelex/kernel/search_ops.py" = "blob:ed0a8c7953aca1e38de852d0ddef11731b819539"
"pipelex/kernel/search_results.py" = "blob:101b70dc96cc5ee1721c9f6b1cb725a5ca78ff70"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 67846dee1..25f4de1c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## [Unreleased]
+
+### Added
+
+- **A run carries opaque analytics groups the runtime never parses**: `RunMetadata` and the runtime-bridge payload gain `analytics_groups`, a host-supplied mapping of group type to group key — `{"organization": "org_acme"}` on a multi-tenant host, nothing at all on a single-user one — threaded through `pipeline_run_setup`, `prepare_pipe_job` and `PipelexKernel.make` beside `user_id` and `storage_scope`. No key is privileged and the runtime never reads one by name, the same boundary that keeps `storage_scope` opaque. It is validated where it enters, on the type and at the wire: a lowercase snake_case group type, a group key from `A-Za-z0-9_-`, and a small fixed number of group types per run, so a malformed mapping is a construction error naming the field rather than a failure inside a telemetry capture.
+
+### Fixed
+
+- **A malformed `storage_scope` is refused before the run registers itself**: it was validated only inside `prepare_pipe_job`, which runs below the pipeline registration, the library acquire, the tracer open and the trace-start emission, so a scope carrying `..` announced a trace that cannot be unsent before anything looked at it. `pipeline_run_setup` now gates the caller's scope at its top, and gates the rebound value again when the local sentinel turns it into the caller's `pipeline_run_id`. The existing gate in `prepare_pipe_job` stays: it is the first one for a caller reaching that seam directly.
+
## [v0.62.0] - 2026-09-21
### Added
diff --git a/docs/setup/telemetry.md b/docs/setup/telemetry.md
index 6a7f6d853..6a6bfcbf3 100644
--- a/docs/setup/telemetry.md
+++ b/docs/setup/telemetry.md
@@ -102,6 +102,28 @@ When set, this disables:
!!! warning "Gateway Requires Telemetry"
If you set `DO_NOT_TRACK=1` while using Pipelex Gateway, the Gateway will not function. Use direct provider backends instead if you need to disable all telemetry.
+## Attaching your own groups to a run
+
+A host that runs Pipelex for more than one customer usually wants a run's telemetry to belong to the entities *it* cares about — an organization, a workspace, a tenant. Pipelex carries those labels for you without ever learning what they mean.
+
+The run-level metadata every run carries (`RunMetadata`) has an `analytics_groups` field: an opaque mapping of **group type** to **group key** that you supply when you start the run, beside `user_id` and `storage_scope`.
+
+```python
+analytics_groups = {"organization": "org_acme"}
+```
+
+!!! note "What this field does today"
+ The runtime validates the mapping, carries it through every nested pipe, and keeps it on the run's metadata across a process boundary. It does **not** yet attach it to the events and spans the built-in PostHog and OpenTelemetry integrations emit — so setting it today will not group anything in your backend. Supply it if you want your runs to carry the labels from now on; wait if you want to see them in PostHog.
+
+The rules it follows:
+
+- **Nothing is privileged.** `organization` is a word a host chose, not one Pipelex knows. A deployment that sends `{"tenant": "t-1", "plan_tier": "enterprise"}` is served identically, because the runtime never reads a key by name — the same boundary that keeps `storage_scope` opaque.
+- **It is validated where it enters.** A group type is lowercase snake_case starting with a letter (up to 32 characters); a group key is 1 to 128 characters from `A-Za-z0-9_-`; a run carries at most five group types. A mapping outside those bounds is refused before the run registers itself or emits anything, and again when a bridge payload is decoded — not later, inside a telemetry capture. The group key is quoted into log lines and capture payloads, so whitespace and control characters are refused outright.
+- **It is optional.** Omitting it leaves the group facet empty, which misattributes nothing. Unlike `user_id` and `storage_scope`, which have no default because a missing one used to be invented, a missing group invents nothing.
+- **It travels with the run.** The mapping rides the job through every nested pipe, and the bridge payload that crosses a process boundary carries it, so a distributed worker is handed the same groups the entry point was given.
+
+These are labels for grouping, not content: they belong in the reserved identity fields of whichever backend understands groups, never in an event property or a span name.
+
## Privacy
We take your privacy seriously:
diff --git a/docs/under-the-hood/pipelex-kernel.md b/docs/under-the-hood/pipelex-kernel.md
index 2fe66251e..acfeee4fa 100644
--- a/docs/under-the-hood/pipelex-kernel.md
+++ b/docs/under-the-hood/pipelex-kernel.md
@@ -127,7 +127,7 @@ summaries = extract_main_content_as_list(memory=result.memory, item_type=Summary
`PipelexKernel` holds run-scoped identity, plus the one seam that identity needs:
-- **`job_metadata`** — the run-level metadata. **The two halves are now separate types, and a caller reading a field off this object must know which half it is in.** `JobMetadata.run_metadata` holds what is constant for the whole run — `user_id`, `pipeline_run_id`, `storage_scope`, `request_id` — and the rest of `JobMetadata` holds what changes per step (`pipe_code`, `pipe_run_id`, `otel_context`). So it is `kernel.job_metadata.run_metadata.pipeline_run_id`, not `kernel.job_metadata.pipeline_run_id`; there is deliberately no read-through accessor, so one fact has one spelling. The distinction this bullet already drew informally — run-level metadata, per-step copy — is what the split makes explicit, and it is why the per-step copy can carry the run half through untouched. It is not what a step runs under: every call mints a per-step copy through `make_step_metadata()`, carrying a fresh `pipe_run_id` and inheriting the trace context, so trace and usage attribution stay per-step. This mirrors the interpreter's pass-down-a-modified-copy pattern. `make_step_metadata(pipe_code=…)` names the pipe the step is running — mirroring what the interpreter stamps on its live and dry paths — so log correlation, usage accounting, and the per-step labelling a distributed backend derives see a named step. When no `pipe_code` is supplied the key is omitted from the update rather than passed as `None`, so a run-level `pipe_code` is never silently erased; the direct-call façade (`llm_text`/`llm_object`) stays deliberately anonymous, because the caller ran no pipe.
+- **`job_metadata`** — the run-level metadata. **The two halves are now separate types, and a caller reading a field off this object must know which half it is in.** `JobMetadata.run_metadata` holds what is constant for the whole run — `user_id`, `pipeline_run_id`, `storage_scope`, `request_id`, `analytics_groups` — and the rest of `JobMetadata` holds what changes per step (`pipe_code`, `pipe_run_id`, `otel_context`). So it is `kernel.job_metadata.run_metadata.pipeline_run_id`, not `kernel.job_metadata.pipeline_run_id`; there is deliberately no read-through accessor, so one fact has one spelling. `user_id`, `storage_scope` and `analytics_groups` are supplied by the host at `PipelexKernel.make(...)` — the last of them opaque, so a multi-tenant host can attribute a kernel-driven run to its own entities without the runtime learning what they are. The distinction this bullet already drew informally — run-level metadata, per-step copy — is what the split makes explicit, and it is why the per-step copy can carry the run half through untouched. It is not what a step runs under: every call mints a per-step copy through `make_step_metadata()`, carrying a fresh `pipe_run_id` and inheriting the trace context, so trace and usage attribution stay per-step. This mirrors the interpreter's pass-down-a-modified-copy pattern. `make_step_metadata(pipe_code=…)` names the pipe the step is running — mirroring what the interpreter stamps on its live and dry paths — so log correlation, usage accounting, and the per-step labelling a distributed backend derives see a named step. When no `pipe_code` is supplied the key is omitted from the update rather than passed as `None`, so a run-level `pipe_code` is never silently erased; the direct-call façade (`llm_text`/`llm_object`) stays deliberately anonymous, because the caller ran no pipe.
- **`cogt_run_params`** — the execution-mode contract (`run_mode`, and the DRY-only `is_mock_usage` sub-flag) that every cogt leaf reads off the assignment it is handed.
- **`step_id_source`** — where each step's `pipe_run_id` comes from, defaulting to a fresh `uuid4`, which is what every in-process run wants. It exists for a kernel hosted inside a replay-based executor, where ids minted from a non-replay-safe source take different values each re-execution; such a host injects its own replay-safe source via `PipelexKernel.make(step_id_source=…)`. It is a seam, not state — the kernel never inspects what it returns.
diff --git a/pipelex/kernel/pipelex_kernel.py b/pipelex/kernel/pipelex_kernel.py
index 93b024108..622c379bd 100644
--- a/pipelex/kernel/pipelex_kernel.py
+++ b/pipelex/kernel/pipelex_kernel.py
@@ -86,6 +86,7 @@ class PipelexKernel:
run_mode: PipeRunMode = PipeRunMode.LIVE,
user_id: str,
storage_scope: str,
+ analytics_groups: dict[str, str] | None = None,
is_mock_usage: bool = False,
trace_context: TraceContext | None = None,
step_id_source: Callable[[], str] | None = None,
@@ -108,6 +109,13 @@ class PipelexKernel:
across two ids (the registered-context emit path stamps the event log's id, the runner
fallback stamps the metadata's), so the read-back would silently miss half of them.
+ ``analytics_groups`` is the opaque, host-supplied mapping this run's telemetry belongs to,
+ carried beside ``user_id`` and ``storage_scope``. This tier is the direct programmatic entry
+ point, so a multi-tenant host embedding the kernel needs the same seam the pipeline entry
+ points have — without it a kernel-minted run is permanently group-less and its host has no
+ supported way to say otherwise. Omitting it leaves the group facet empty, which misattributes
+ nothing. See :mod:`pipelex.system.analytics_groups`.
+
``step_id_source`` overrides where each step's ``pipe_run_id`` comes from; it defaults to a
fresh ``uuid4``, which is what every in-process run wants. It exists for a kernel hosted
inside a **replay-based** executor, where identifiers minted from a non-replay-safe source
@@ -122,6 +130,7 @@ class PipelexKernel:
user_id=user_id,
storage_scope=storage_scope,
pipeline_run_id=trace_context.graph_id if trace_context is not None else str(uuid4()),
+ analytics_groups=analytics_groups or {},
),
trace_context=trace_context,
),
diff --git a/pipelex/pipeline/execution_seams.py b/pipelex/pipeline/execution_seams.py
index 3fa3ba0e3..49ada584c 100644
--- a/pipelex/pipeline/execution_seams.py
+++ b/pipelex/pipeline/execution_seams.py
@@ -45,6 +45,7 @@ from pipelex.pipe_run.pipe_run_params import VariableMultiplicity
from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory
from pipelex.pipeline.blueprint_selection import select_primary_blueprint
from pipelex.pipeline.input_normalizer import normalize_data_urls_to_storage
+from pipelex.system.analytics_groups import validate_analytics_groups
from pipelex.system.configuration.configs import PipelineExecutionConfig
from pipelex.system.job_metadata import JobMetadata, OtelContext, RunMetadata
from pipelex.system.pipe_run_mode import PipeRunMode
@@ -164,6 +165,7 @@ async def prepare_pipe_job(
pipeline_run_id: str,
user_id: str,
storage_scope: str,
+ analytics_groups: dict[str, str] | None = None,
inputs: PipelineInputs | WorkingMemory | None = None,
search_scope: str | None = None,
trace_context: "TraceContext | None" = None,
@@ -205,6 +207,14 @@ async def prepare_pipe_job(
# This is deliberately not a "second gate": it is the FIRST one on this path.
storage_scope = validate_storage_scope(value=storage_scope)
+ # And the groups beside it, for the same reason: `RunMetadata` is built at
+ # the bottom of this function, below the data-url normalization that writes
+ # to real storage, so validating only there refuses a malformed mapping
+ # after the run has already put bytes in a bucket. `pipeline_run_setup`
+ # validates earlier still — this is the first gate for the callers that
+ # reach this seam directly (`bundle_validator`, `dry_run_in_process`).
+ analytics_groups = validate_analytics_groups(value=analytics_groups or {})
+
working_memory: WorkingMemory | None = None
# First, process user-provided inputs. Empty PipelineInputs is falsy and behaves like no inputs.
@@ -278,7 +288,16 @@ async def prepare_pipe_job(
working_memory = await normalize_data_urls_to_storage(working_memory, storage_scope=storage_scope)
job_metadata = JobMetadata(
- run_metadata=RunMetadata(user_id=user_id, storage_scope=storage_scope, pipeline_run_id=pipeline_run_id, request_id=request_id),
+ run_metadata=RunMetadata(
+ user_id=user_id,
+ storage_scope=storage_scope,
+ pipeline_run_id=pipeline_run_id,
+ request_id=request_id,
+ # Already normalized to a mapping and validated at the top of this
+ # function; the parameter stays nullable only so every existing call
+ # site can keep omitting it.
+ analytics_groups=analytics_groups,
+ ),
otel_context=otel_context,
trace_context=trace_context,
)
diff --git a/pipelex/pipeline/pipeline_run_setup.py b/pipelex/pipeline/pipeline_run_setup.py
index 65fe0dc33..afc57903c 100644
--- a/pipelex/pipeline/pipeline_run_setup.py
+++ b/pipelex/pipeline/pipeline_run_setup.py
@@ -25,11 +25,12 @@ from pipelex.pipe_run.pipe_run_params import (
from pipelex.pipeline.exceptions import PipeExecutionError
from pipelex.pipeline.execution_seams import acquire_library, prepare_pipe_job
from pipelex.runtime_hub import get_event_log_override, get_otel_tracer, get_report_delegate, get_telemetry_manager
+from pipelex.system.analytics_groups import validate_analytics_groups
from pipelex.system.configuration.configs import PipelineExecutionConfig
from pipelex.system.environment import get_optional_env
from pipelex.system.job_metadata import OtelContext
from pipelex.system.pipe_run_mode import PipeRunMode
-from pipelex.system.storage_scope import LOCAL_STORAGE_SCOPE
+from pipelex.system.storage_scope import LOCAL_STORAGE_SCOPE, validate_storage_scope
from pipelex.system.telemetry.events import EventName, EventProperty
from pipelex.system.telemetry.otel_constants import OTelConstants
from pipelex.system.telemetry.otel_factory import OtelFactory
@@ -57,6 +58,7 @@ async def pipeline_run_setup(
is_mock_usage: bool = False,
user_id: str,
storage_scope: str,
+ analytics_groups: dict[str, str] | None = None,
pipeline_run_id: str | None = None,
request_id: str | None = None,
inputs_base_dir: Path | None = None,
@@ -123,6 +125,14 @@ async def pipeline_run_setup(
Opaque prefix under which every byte this run writes must land. REQUIRED,
validated at ``JobMetadata`` construction. See
:mod:`pipelex.system.storage_scope`.
+ analytics_groups:
+ Opaque, host-supplied mapping of group type to group key that this run's
+ telemetry belongs to — the hosted platform sends its organization, a
+ single-user deployment sends nothing. Never read by name here. Validated
+ at the TOP of this function, above the pipeline registration and above
+ the trace-start event, so a malformed mapping registers nothing and
+ emits nothing. Optional, and omitting it leaves the group facet empty.
+ See :mod:`pipelex.system.analytics_groups`.
pipeline_run_id:
Pre-generated pipeline run ID. If provided, this ID is used instead of
generating a new one. Use this when the run record has already been created
@@ -163,6 +173,33 @@ async def pipeline_run_setup(
msg = "Either pipe_code or mthds_contents must be provided to the pipeline API."
raise ValueError(msg)
+ # Validate the groups HERE, before this function causes anything observable.
+ #
+ # `RunMetadata` validates them too, and `prepare_pipe_job` validates them at
+ # its own top — but BOTH run below `add_new_pipeline`, the open tracer and
+ # `handle_trace_start`, which emits a telemetry event that cannot be unsent.
+ # So a malformed mapping used to abort a run that had already registered
+ # itself and announced its own trace to the backend. The teardown below
+ # releases the local state; the emitted event it cannot take back.
+ #
+ # This is the same lesson `storage_scope` learned one seam lower, and the
+ # same cure: ordering, not absence, was the defect.
+ analytics_groups = validate_analytics_groups(value=analytics_groups or {})
+
+ # And the scope, for the same reason and with more at stake.
+ #
+ # `prepare_pipe_job` gates it too, and that gate stays — but it runs below
+ # everything listed above, so until now the OPAQUE mapping was refused
+ # earlier than the field that decides where a tenant's bytes land. A scope
+ # carrying `..` registered a pipeline, opened a library and a tracer and
+ # announced its trace before anything looked at it.
+ #
+ # ADDITIVE, never a move: the value validated here is the caller's raw one,
+ # and the sentinel below rebinds it to something else that only the lower
+ # gate sees. `LOCAL_STORAGE_SCOPE` passes this gate unharmed — it is itself
+ # a valid one-segment scope — so the sentinel is not disturbed.
+ storage_scope = validate_storage_scope(value=storage_scope)
+
# TODO: rethink this, it's not forcing
if pipe_run_mode is None:
if run_mode_from_env := get_optional_env(key=FORCE_DRY_RUN_MODE_ENV_KEY):
@@ -189,7 +226,13 @@ async def pipeline_run_setup(
# Keyed on the sentinel EXACTLY, never a prefix test: a host that serves more
# than one tenant passes its own scope and is untouched here.
if storage_scope == LOCAL_STORAGE_SCOPE:
- storage_scope = pipeline_run_id
+ # The rebound value is caller data too: `pipeline_run_id` is a parameter
+ # of this function, so a caller passing the sentinel alongside its own id
+ # chooses the storage scope through the back door. The gate above saw
+ # only the sentinel, so this is the first look at what the scope has
+ # actually become — and it still sits above the library, the tracer and
+ # the trace-start.
+ storage_scope = validate_storage_scope(value=pipeline_run_id)
if not library_id:
library_id = pipeline_run_id
@@ -323,6 +366,7 @@ async def pipeline_run_setup(
pipeline_run_id=pipeline_run_id,
user_id=user_id,
storage_scope=storage_scope,
+ analytics_groups=analytics_groups,
inputs=inputs,
search_scope=search_scope,
trace_context=trace_context,
diff --git a/pipelex/pipeline/runner.py b/pipelex/pipeline/runner.py
index 906dc81d7..5b9ee3fe1 100644
--- a/pipelex/pipeline/runner.py
+++ b/pipelex/pipeline/runner.py
@@ -119,6 +119,10 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):
# by omission, because `pipeline_run_setup` requires both explicitly.
user_id: str = LOCAL_USER_ID,
storage_scope: str = LOCAL_STORAGE_SCOPE,
+ # Opaque groups the host attaches to every run this protocol starts.
+ # No local default: a laptop belongs to no organization, and inventing
+ # a group here would put every such run into one shared entity.
+ analytics_groups: dict[str, str] | None = None,
execution_config: PipelineExecutionConfig | None = None,
pipe_run: PipeRunProtocol | None = None,
inputs_base_dir: Path | None = None,
@@ -130,6 +134,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):
self.is_mock_usage = is_mock_usage
self.user_id = user_id
self.storage_scope = storage_scope
+ self.analytics_groups = analytics_groups
self.execution_config = execution_config
self._pipe_run = pipe_run
# Directory that bare relative local file paths in `inputs` resolve against (Smart Inputs
@@ -230,6 +235,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):
is_mock_usage=self.is_mock_usage,
user_id=self.user_id,
storage_scope=self.storage_scope,
+ analytics_groups=self.analytics_groups,
inputs_base_dir=self.inputs_base_dir,
)
effective_pipe_run = self._pipe_run or get_pipe_run()
diff --git a/pipelex/runtime_bridge/payloads.py b/pipelex/runtime_bridge/payloads.py
index 6d14e514a..72c4415c3 100644
--- a/pipelex/runtime_bridge/payloads.py
+++ b/pipelex/runtime_bridge/payloads.py
@@ -15,8 +15,10 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator
from pipelex.runtime_bridge.delivery_mode import DeliveryMode
from pipelex.runtime_bridge.orchestration_mode import DIRECT_ORCHESTRATION_MODE
-# Import-light by design (see module docstring): `storage_scope` pulls in `re`
-# and nothing else, so validating here costs the boundary nothing.
+# Import-light by design (see module docstring): `storage_scope` and
+# `analytics_groups` each pull in `re` and nothing else, so validating here
+# costs the boundary nothing.
+from pipelex.system.analytics_groups import validate_analytics_groups
from pipelex.system.storage_scope import validate_storage_scope
@@ -50,6 +52,26 @@ class PipelexPipeRunInput(BaseModel):
"""
return validate_storage_scope(value=value)
+ # The opaque groups this run's telemetry belongs to. Unlike the two fields
+ # above it DEFAULTS: a host with no groups to send invents nothing by
+ # staying silent, whereas a missing identity or scope used to be invented
+ # for it. See `pipelex.system.analytics_groups`.
+ analytics_groups: dict[str, str] = Field(default_factory=dict)
+
+ @field_validator("analytics_groups")
+ @classmethod
+ def _validate_analytics_groups(cls, value: dict[str, str]) -> dict[str, str]:
+ """Refuse a malformed mapping at the WIRE, not inside a telemetry capture.
+
+ Declaring the field `dict[str, str]` says nothing about its contents,
+ and the contents are whatever the other side of the boundary put there.
+ A key with a newline in it, or a mapping with a thousand entries, would
+ decode happily here and surface much later, far from the payload that
+ carried it. Validating at construction makes it a decoding error naming
+ the field.
+ """
+ return validate_analytics_groups(value=value)
+
library_crate_dump: dict[str, Any] | None = None
# Two orthogonal axes: which orchestrator runs the pipe (open token, defaults to the
# core in-process orchestrator) and whether the caller waits (endpoint-set; defaults
diff --git a/pipelex/system/analytics_groups.py b/pipelex/system/analytics_groups.py
new file mode 100644
index 000000000..f3fabfcd5
--- /dev/null
+++ b/pipelex/system/analytics_groups.py
@@ -0,0 +1,126 @@
+"""`analytics_groups` — the opaque group labels a host attaches to a run.
+
+**The runtime does not know what an organization is, and must not learn.** That
+is the same rule `pipelex.system.storage_scope` states for where a run's bytes
+go, and this module is its telemetry counterpart: a host that runs Pipelex for
+many tenants needs a run's spans and events to belong to the entities that
+tenant cares about, and Pipelex needs somewhere to put labels it will forward
+without reading. `analytics_groups` is that somewhere — an opaque, host-supplied
+mapping of group *type* to group *key* that the runtime carries on
+`RunMetadata`, unread, for a telemetry consumer that understands groups to
+forward. Carrying it is all this module does: no exporter reads the mapping
+yet, so do not take the field's presence as evidence that a span or an event is
+already grouped by it.
+
+The hosted Pipelex platform fills it with `{"organization": "<org_id>"}`, but
+nothing here knows or checks that: no key is privileged, and a deployment that
+sends `{"tenant": …, "plan_tier": …}` is served identically. A single-user
+deployment sends nothing at all.
+
+**Why it carries groups and not free properties.** A telemetry backend gives an
+event two different destinations. A *group* is an entity the event belongs to,
+and it is what makes entity-level counts, funnels and retention possible after
+the fact; a *property* is a free scalar on the event and can do none of that. A
+generic extras bag would force the runtime to sort entries between the two, and
+since it may not read a key by name it would have to send everything one way —
+spending a backend's scarce group-type budget on values like a plan tier, or
+losing entity analytics entirely. So the facet is named in the field. If a host
+ever needs free properties on a run, that is a sibling field routed by facet,
+and this one keeps its name and its meaning.
+
+**Why the value is validated on the type.** The mapping is caller data that
+arrives over a wire, so its contents are whatever the other side put there. It
+is then quoted into log lines and forwarded to a telemetry backend, where a
+newline is a log-forging primitive and an unbounded mapping is an unbounded
+capture payload. Validating at construction — on `RunMetadata` and on the bridge
+payload, through this one helper — means a malformed mapping is a decoding error
+naming the field, at the edge, rather than a failure inside whichever capture
+first tried to use it.
+
+**Why an empty default is right here and was wrong for `storage_scope`.** An
+absent group creates no shared namespace and misattributes nothing; it only
+leaves the group facet empty. The doctrine that made `user_id` and
+`storage_scope` non-defaulting is about identity and about storage keys, and
+both of those still refuse to default.
+"""
+
+from __future__ import annotations
+
+import re
+
+# A group TYPE: the facet name, lowercase snake_case, starting with a letter.
+#
+# Deliberately narrower than the value charset. A group type is a schema-level
+# name that a telemetry backend registers once and then shows in a picker, so it
+# is written by whoever integrates the host, not derived from tenant data — the
+# tight shape costs an integrator nothing and keeps a stray id out of the facet
+# list. Applied with `fullmatch` (see below).
+ANALYTICS_GROUP_TYPE_PATTERN = re.compile(r"^[a-z][a-z0-9_]{0,31}$")
+
+# A group KEY: the identifier of one entity inside a type.
+#
+# This one IS tenant data — an org id, a workspace slug — so it admits both
+# cases, digits, `_` and `-`, which covers every id shape the platform mints,
+# and nothing else. No `/`, no `.`, no whitespace and no control character: the
+# value is quoted into log lines and into capture payloads, and a newline in it
+# is a log-forging primitive exactly as it is in a storage scope.
+ANALYTICS_GROUP_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
+
+# How many group types one run may carry.
+#
+# A bound is needed because the mapping is unbounded caller input crossing a
+# wire and is attached to every span of a run. It lands at five because that is
+# where the most constrained consumer of the group facet sits — a telemetry
+# backend typically registers a small fixed number of group types per project —
+# so a sixth could not be honoured downstream anyway, and refusing it at the
+# edge is more honest than forwarding a value that will be dropped in silence.
+ANALYTICS_GROUPS_MAX_ENTRIES = 5
+
+
+def validate_analytics_groups(*, value: dict[str, str]) -> dict[str, str]:
+ """Return `value` if it is a usable analytics-groups mapping, else raise `ValueError`.
+
+ Args:
+ value: The host-supplied mapping of group type to group key. An empty
+ mapping is valid and means "this run belongs to no group".
+
+ Returns:
+ The mapping, unchanged — this validator never normalizes, because the
+ runtime does not own the vocabulary and lowercasing a tenant's id would
+ silently address a different entity.
+
+ Raises:
+ ValueError: the mapping holds more than `ANALYTICS_GROUPS_MAX_ENTRIES`
+ entries, or a key or a value falls outside its charset — which
+ covers the empty string, whitespace, control characters, and
+ anything that could forge a line in a log or a capture payload.
+ """
+ if len(value) > ANALYTICS_GROUPS_MAX_ENTRIES:
+ msg = (
+ f"Invalid analytics_groups: {len(value)} entries, at most {ANALYTICS_GROUPS_MAX_ENTRIES} are accepted. "
+ "Each entry is one group type a telemetry backend registers for the project, and that budget is "
+ "small and fixed — an entry beyond it could not be honoured downstream."
+ )
+ raise ValueError(msg)
+
+ # `fullmatch`, NOT `match`. A trailing `$` in a `match` still admits one
+ # final newline, which is how `storage_scope` once let a newline travel into
+ # every storage key and log line built from it. The anchors below are
+ # therefore redundant but kept: the patterns are also read on their own.
+ for group_type, group_key in value.items():
+ if not ANALYTICS_GROUP_TYPE_PATTERN.fullmatch(group_type):
+ msg = (
+ f"Invalid analytics_groups group type {group_type!r} (a key of the mapping): expected lowercase "
+ "snake_case starting with a letter, at most 32 characters (e.g. 'organization'). A group type is a "
+ "facet name registered with the telemetry backend, not tenant data."
+ )
+ raise ValueError(msg)
+ if not ANALYTICS_GROUP_KEY_PATTERN.fullmatch(group_key):
+ msg = (
+ f"Invalid analytics_groups group key {group_key!r} for group type {group_type!r} (a value of the "
+ "mapping): expected 1 to 128 characters from [A-Za-z0-9_-] (e.g. 'org_acme'). The group key is "
+ "quoted into log lines and capture payloads, so whitespace, control characters and separators "
+ "are refused."
+ )
+ raise ValueError(msg)
+ return value
diff --git a/pipelex/system/job_metadata.py b/pipelex/system/job_metadata.py
index 910d41df0..fe8c181b6 100644
--- a/pipelex/system/job_metadata.py
+++ b/pipelex/system/job_metadata.py
@@ -4,6 +4,7 @@ from typing import Any
from pydantic import BaseModel, Field, field_validator
+from pipelex.system.analytics_groups import validate_analytics_groups
from pipelex.system.storage_scope import validate_storage_scope
from pipelex.system.telemetry.otel_context import OtelContext
from pipelex.system.trace_context import TraceContext
@@ -51,9 +52,9 @@ class UnitJobId(StrEnum):
class RunMetadata(BaseModel):
- """Who is running, which run it is, and where its bytes go.
+ """Who is running, which run it is, where its bytes go, and what it belongs to.
- **The four facts that are constant for a whole run**, split out from
+ **The facts that are constant for a whole run**, split out from
:class:`JobMetadata` — which mixes them with per-job facts that change at
every step (``pipe_code``, ``pipe_run_id``, ``otel_context``,
``content_generation_job_id``). Grouping them says which is which: a copy
@@ -95,6 +96,19 @@ class RunMetadata(BaseModel):
# characters into the log lines or ``ErrorReport`` envelopes that quote it.
request_id: str | None = Field(default=None, max_length=128, pattern=r"^[\x20-\x7E]+$")
+ # The opaque groups this run's telemetry belongs to, supplied by the host.
+ # Forwarded to whichever consumer understands groups and never read by name
+ # — see `pipelex.system.analytics_groups` for why the host's own concepts
+ # (organization, tenant, plan tier) deliberately do not cross this boundary,
+ # and for the charset and the size bound.
+ #
+ # It DEFAULTS, unlike `user_id` and `storage_scope` above, and the asymmetry
+ # is the point: those two refuse to default because a missing identity once
+ # became a present-looking one and a shared storage prefix. An absent group
+ # creates no namespace and misattributes nothing — it only leaves the group
+ # facet empty — so a caller with no groups to send says nothing.
+ analytics_groups: dict[str, str] = Field(default_factory=dict)
+
@field_validator("storage_scope")
@classmethod
def _validate_storage_scope(cls, value: str) -> str:
@@ -110,6 +124,29 @@ class RunMetadata(BaseModel):
"""
return validate_storage_scope(value=value)
+ @field_validator("analytics_groups")
+ @classmethod
+ def _validate_analytics_groups(cls, value: dict[str, str]) -> dict[str, str]:
+ """Refuse a mapping the runtime could not safely forward, at construction.
+
+ On the TYPE for the same reason as `storage_scope`: the value is caller
+ data that ends up quoted into log lines and handed to a telemetry
+ backend, so a newline in it forges a log line and an unbounded mapping
+ is an unbounded capture payload. Validating here means a mapping that
+ ARRIVED through construction is safe, which is the case that matters:
+ every mapping crossing the wire or a call site is built here.
+
+ The guarantee stops at construction, and deliberately so. This model is
+ neither frozen nor `validate_assignment`, so mutating the mapping in
+ place — `run_metadata.analytics_groups[k] = v` — bypasses this
+ validator, exactly as reassigning `storage_scope` bypasses its own.
+ `model_copy` does not re-run validators either, which is fine:
+ `copy_with_update` only ever carries an already-validated mapping
+ forward. Nothing in the runtime mutates the mapping after construction;
+ a future consumer that forwards it must not start.
+ """
+ return validate_analytics_groups(value=value)
+
class JobMetadata(BaseModel):
# The run-constant half: who, which run, where its bytes go, which request
diff --git a/tests/integration/pipelex/pipeline/test_pipeline_run_setup_analytics_groups.py b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_analytics_groups.py
new file mode 100644
index 000000000..68841455e
--- /dev/null
+++ b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_analytics_groups.py
@@ -0,0 +1,117 @@
+"""Integration tests for :func:`pipeline_run_setup` threading ``analytics_groups``
+onto :class:`JobMetadata`.
+
+The groups ride the ``PipeJob``
+(``arg.pipe_job.job_metadata.run_metadata.analytics_groups``) — the same payload-first
+route ``request_id`` takes, and for the same reason: there is no ContextVar layer
+and the worker on the far side of a Temporal hop rehydrates the whole job. No
+exporter reads them yet; this test pins the dispatcher-side contract, which is
+what the hosted runner will call once it accepts the field on the wire.
+
+It also pins WHERE the refusal happens. Validation sits above
+``add_new_pipeline`` and above ``handle_trace_start`` deliberately: a malformed
+mapping must not register a run or emit a trace-start event that cannot be
+unsent. Asserting only that a ``ValueError`` escapes would pass with the
+validation at the bottom of ``prepare_pipe_job``, which is where it used to be.
+"""
+
+import pytest
+from pytest_mock import MockerFixture
+
+from pipelex.config import get_config
+from pipelex.pipeline import pipeline_run_setup as pipeline_run_setup_module
+from pipelex.pipeline.pipeline_run_setup import pipeline_run_setup
+
+_MINIMAL_MTHDS = """
+domain = "analytics_groups_test"
+description = "Minimal bundle for analytics_groups propagation test"
+
+[concept.Topic]
+description = "A topic"
+
+[concept.Topic.structure]
+name = { type = "text", description = "Topic name" }
+
+[pipe.echo_topic]
+type = "PipeLLM"
+description = "Pipe used only to set up a PipeJob"
+inputs = { subject = "Text" }
+output = "Topic"
+prompt = "Echo the $subject as a topic"
+"""
+
+
[email protected](loop_scope="class")
+class TestPipelineRunSetupAnalyticsGroups:
+ async def test_analytics_groups_thread_onto_job_metadata(self) -> None:
+ """``pipeline_run_setup(..., analytics_groups=...)`` puts them on ``job_metadata.run_metadata``."""
+ execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(
+ generate_graph=False,
+ )
+ pipe_job, _, _ = await pipeline_run_setup(
+ storage_scope="test/scope",
+ user_id="test-user",
+ execution_config=execution_config,
+ mthds_contents=[_MINIMAL_MTHDS],
+ pipe_code="echo_topic",
+ analytics_groups={"organization": "org_acme"},
+ )
+ assert pipe_job.job_metadata.run_metadata.analytics_groups == {"organization": "org_acme"}
+
+ async def test_omitting_them_leaves_an_empty_mapping(self) -> None:
+ """Every existing caller omits the field, and an omission is an empty group facet, not an error."""
+ execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(
+ generate_graph=False,
+ )
+ pipe_job, _, _ = await pipeline_run_setup(
+ storage_scope="test/scope",
+ user_id="test-user",
+ execution_config=execution_config,
+ mthds_contents=[_MINIMAL_MTHDS],
+ pipe_code="echo_topic",
+ )
+ assert pipe_job.job_metadata.run_metadata.analytics_groups == {}
+
+ async def test_malformed_groups_are_refused_before_the_run_starts(self) -> None:
+ """The validator on the field is what makes a bad mapping fail at setup rather than at capture."""
+ execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(
+ generate_graph=False,
+ )
+ with pytest.raises(ValueError, match="analytics_groups"):
+ await pipeline_run_setup(
+ storage_scope="test/scope",
+ user_id="test-user",
+ execution_config=execution_config,
+ mthds_contents=[_MINIMAL_MTHDS],
+ pipe_code="echo_topic",
+ analytics_groups={"Organization": "org_acme"},
+ )
+
+ async def test_the_refusal_registers_no_run_and_emits_no_trace_start(self, mocker: MockerFixture) -> None:
+ """A rejected mapping must leave NOTHING behind — not a pipeline entry, not a telemetry event.
+
+ The teardown can release a registered pipeline and an opened tracer; it cannot
+ unsend a ``handle_trace_start`` that already reached the backend. So the gate has
+ to sit above both, and this test fails if it is moved back down into
+ ``prepare_pipe_job`` where the mapping was first validated.
+ """
+ execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(
+ generate_graph=False,
+ )
+ # SPIES, not stubs: they call through, so this test fails on the assertion
+ # below rather than on some mock artifact tripping a constructor first.
+ pipeline_manager = mocker.spy(pipeline_run_setup_module, "get_pipeline_manager")
+ telemetry_manager = mocker.spy(pipeline_run_setup_module, "get_telemetry_manager")
+
+ with pytest.raises(ValueError, match="analytics_groups"):
+ await pipeline_run_setup(
+ storage_scope="test/scope",
+ user_id="test-user",
+ execution_config=execution_config,
+ mthds_contents=[_MINIMAL_MTHDS],
+ pipe_code="echo_topic",
+ analytics_groups={"Organization": "org_acme"},
+ )
+
+ pipeline_manager.assert_not_called()
+ telemetry_manager.assert_not_called()
diff --git a/tests/integration/pipelex/pipeline/test_pipeline_run_setup_storage_scope_gate.py b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_storage_scope_gate.py
new file mode 100644
index 000000000..ba8515067
--- /dev/null
+++ b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_storage_scope_gate.py
@@ -0,0 +1,109 @@
+"""Where `pipeline_run_setup` refuses a malformed `storage_scope`.
+
+The scope decides where a tenant's bytes land, so a traversal in it is the
+highest-stakes value this function takes. It was validated only inside
+`prepare_pipe_job`, which runs below the pipeline registration, the library
+acquire, the tracer open and `handle_trace_start` — so a scope carrying `..`
+registered a run and emitted a trace event that cannot be unsent before
+anything looked at it. These pin the two gates that close that window, and both
+fail if either gate is removed.
+
+The lower gate in `prepare_pipe_job` is NOT replaced by these and must stay: the
+sentinel path rebinds the scope to the caller's `pipeline_run_id`, and only the
+lower gate sees what a direct caller of that seam passes.
+"""
+
+import pytest
+from pytest_mock import MockerFixture
+
+from pipelex.config import get_config
+from pipelex.pipeline import pipeline_run_setup as pipeline_run_setup_module
+from pipelex.pipeline.pipeline_run_setup import pipeline_run_setup
+from pipelex.system.storage_scope import LOCAL_STORAGE_SCOPE
+
+_MINIMAL_MTHDS = """
+domain = "storage_scope_gate_test"
+description = "Minimal bundle for the storage_scope gate test"
+
+[concept.Topic]
+description = "A topic"
+
+[concept.Topic.structure]
+name = { type = "text", description = "Topic name" }
+
+[pipe.echo_topic]
+type = "PipeLLM"
+description = "Pipe used only to set up a PipeJob"
+inputs = { subject = "Text" }
+output = "Topic"
+prompt = "Echo the $subject as a topic"
+"""
+
+
[email protected](loop_scope="class")
+class TestPipelineRunSetupStorageScopeGate:
+ async def test_a_traversal_scope_registers_no_run_and_emits_no_trace_start(self, mocker: MockerFixture) -> None:
+ """The caller's raw scope is refused above every observable effect.
+
+ Spies, not stubs: they call through, so a failure here is the assertion
+ and not a mock artifact tripping a constructor first.
+ """
+ execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(generate_graph=False)
+ pipeline_manager = mocker.spy(pipeline_run_setup_module, "get_pipeline_manager")
+ telemetry_manager = mocker.spy(pipeline_run_setup_module, "get_telemetry_manager")
+ acquire_library = mocker.spy(pipeline_run_setup_module, "acquire_library")
+
+ with pytest.raises(ValueError, match="storage_scope"):
+ await pipeline_run_setup(
+ storage_scope="../evil",
+ user_id="test-user",
+ execution_config=execution_config,
+ mthds_contents=[_MINIMAL_MTHDS],
+ pipe_code="echo_topic",
+ )
+
+ pipeline_manager.assert_not_called()
+ acquire_library.assert_not_called()
+ telemetry_manager.assert_not_called()
+
+ async def test_the_sentinel_rebinds_to_a_validated_run_id(self, mocker: MockerFixture) -> None:
+ """A caller passing the sentinel plus its own malformed run id picks the scope through the back door.
+
+ The first gate sees only `LOCAL_STORAGE_SCOPE`, which is a valid scope, so
+ this is the first look at what the scope actually became — and it still
+ has to happen before the library, the tracer and the trace-start.
+ """
+ execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(generate_graph=False)
+ telemetry_manager = mocker.spy(pipeline_run_setup_module, "get_telemetry_manager")
+ acquire_library = mocker.spy(pipeline_run_setup_module, "acquire_library")
+
+ with pytest.raises(ValueError, match="storage_scope"):
+ await pipeline_run_setup(
+ storage_scope=LOCAL_STORAGE_SCOPE,
+ pipeline_run_id="../escape",
+ user_id="test-user",
+ execution_config=execution_config,
+ mthds_contents=[_MINIMAL_MTHDS],
+ pipe_code="echo_topic",
+ )
+
+ acquire_library.assert_not_called()
+ telemetry_manager.assert_not_called()
+
+ async def test_the_sentinel_itself_still_passes_and_becomes_the_run_id(self) -> None:
+ """The gate must not reject the sentinel: `local` is a valid one-segment scope.
+
+ This is what makes the new gate additive rather than a behaviour change —
+ a local run still gets its own run id as its scope.
+ """
+ execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(generate_graph=False)
+
+ pipe_job, pipeline_run_id, _ = await pipeline_run_setup(
+ storage_scope=LOCAL_STORAGE_SCOPE,
+ user_id="test-user",
+ execution_config=execution_config,
+ mthds_contents=[_MINIMAL_MTHDS],
+ pipe_code="echo_topic",
+ )
+
+ assert pipe_job.job_metadata.run_metadata.storage_scope == pipeline_run_id
diff --git a/tests/unit/pipelex/kernel/test_pipelex_kernel_analytics_groups.py b/tests/unit/pipelex/kernel/test_pipelex_kernel_analytics_groups.py
new file mode 100644
index 000000000..61acdc82b
--- /dev/null
+++ b/tests/unit/pipelex/kernel/test_pipelex_kernel_analytics_groups.py
@@ -0,0 +1,51 @@
+"""`PipelexKernel.make` carrying the host's opaque analytics groups.
+
+The kernel tier is the direct programmatic entry point — the one a host embeds
+without going through `pipeline_run_setup` — so it needs the same seam the
+pipeline entry points have. Without it a kernel-minted run is permanently
+group-less and its host has no supported way to say otherwise, while
+`docs/under-the-hood/pipelex-kernel.md` lists the field among what
+`job_metadata.run_metadata` holds.
+"""
+
+import pytest
+
+from pipelex.kernel.pipelex_kernel import PipelexKernel
+from pipelex.system.pipe_run_mode import PipeRunMode
+
+
+class TestPipelexKernelAnalyticsGroups:
+ def test_supplied_groups_land_on_the_runs_metadata(self) -> None:
+ kernel = PipelexKernel.make(
+ storage_scope="test/scope",
+ run_mode=PipeRunMode.DRY,
+ user_id="test-user",
+ analytics_groups={"organization": "org_acme"},
+ )
+
+ assert kernel.job_metadata.run_metadata.analytics_groups == {"organization": "org_acme"}
+
+ def test_omitting_them_leaves_an_empty_mapping(self) -> None:
+ """Every existing caller omits the field; an omission is an empty facet, not an error."""
+ kernel = PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user")
+
+ assert kernel.job_metadata.run_metadata.analytics_groups == {}
+
+ def test_two_kernels_do_not_share_one_default_mapping(self) -> None:
+ """A mutable default shared between runs would leak one host's groups into another's."""
+ first = PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user")
+ second = PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user")
+
+ first.job_metadata.run_metadata.analytics_groups["organization"] = "org_acme"
+
+ assert second.job_metadata.run_metadata.analytics_groups == {}
+
+ def test_a_malformed_mapping_is_refused_when_the_kernel_is_minted(self) -> None:
+ """The field's validator is what makes this fail here rather than inside a later capture."""
+ with pytest.raises(ValueError, match="analytics_groups"):
+ PipelexKernel.make(
+ storage_scope="test/scope",
+ run_mode=PipeRunMode.DRY,
+ user_id="test-user",
+ analytics_groups={"Organization": "org_acme"},
+ )
diff --git a/tests/unit/pipelex/runtime_bridge/test_input_analytics_groups.py b/tests/unit/pipelex/runtime_bridge/test_input_analytics_groups.py
new file mode 100644
index 000000000..a71752d8b
--- /dev/null
+++ b/tests/unit/pipelex/runtime_bridge/test_input_analytics_groups.py
@@ -0,0 +1,73 @@
+"""The bridge payload refuses malformed analytics groups at the WIRE.
+
+A `PipelexPipeRunInput` crosses a process boundary, so its groups are whatever
+the other side put there. Declaring the field `dict[str, str]` says nothing
+about its contents: a key with a newline in it, or a mapping with a thousand
+entries, would decode happily and only surface much later, inside whichever
+telemetry capture first tried to use it. Validating at construction makes that a
+payload-decoding error naming the field — the same bargain `storage_scope`
+already struck one field over.
+"""
+
+from __future__ import annotations
+
+import pytest
+from pydantic import ValidationError
+
+from pipelex.runtime_bridge.payloads import PipelexPipeRunInput
+from pipelex.system.analytics_groups import ANALYTICS_GROUPS_MAX_ENTRIES
+
+
+def _payload(analytics_groups: dict[str, str]) -> PipelexPipeRunInput:
+ return PipelexPipeRunInput(
+ storage_scope="org_a/mt_b/run_c",
+ user_id="test-user",
+ pipe_code="some_pipe",
+ analytics_groups=analytics_groups,
+ )
+
+
+class TestTheWireRefusesMalformedAnalyticsGroups:
+ def test_the_field_defaults_to_an_empty_mapping(self) -> None:
+ """A host with no groups to send sends none, and that is not an error.
+
+ `user_id` and `storage_scope` are required here because a missing one
+ used to be invented; a missing group invents nothing, so it defaults.
+ """
+ payload = PipelexPipeRunInput(storage_scope="org_a/mt_b/run_c", user_id="test-user", pipe_code="some_pipe")
+ assert payload.analytics_groups == {}
+
+ @pytest.mark.parametrize(
+ "groups",
+ [
+ pytest.param({}, id="empty-mapping"),
+ pytest.param({"organization": "org_acme"}, id="the-hosted-plane-shape"),
+ pytest.param({"organization": "org_acme", "workspace": "ws-1"}, id="two-group-types"),
+ ],
+ )
+ def test_well_formed_groups_cross_the_wire(self, groups: dict[str, str]) -> None:
+ assert _payload(groups).analytics_groups == groups
+
+ @pytest.mark.parametrize(
+ "bad_groups",
+ [
+ pytest.param({"Organization": "org_acme"}, id="uppercase-key"),
+ pytest.param({"org-id": "org_acme"}, id="hyphen-in-key"),
+ pytest.param({"": "org_acme"}, id="empty-key"),
+ pytest.param({"organization": ""}, id="empty-value"),
+ pytest.param({"organization": "org acme"}, id="space-in-value"),
+ pytest.param({"organization": "org_acme\n"}, id="trailing-newline-in-value"),
+ pytest.param({"organization": "v" * 129}, id="value-one-over-the-length-cap"),
+ pytest.param({f"g{index}": "v" for index in range(ANALYTICS_GROUPS_MAX_ENTRIES + 1)}, id="one-over-the-entry-cap"),
+ ],
+ )
+ def test_malformed_groups_are_refused_at_construction(self, bad_groups: dict[str, str]) -> None:
+ with pytest.raises(ValidationError):
+ _payload(bad_groups)
+
+ def test_the_groups_survive_a_json_round_trip(self) -> None:
+ """The payload is decoded from JSON on the far side, so the field must round-trip."""
+ original = _payload({"organization": "org_acme"})
+ round_tripped = PipelexPipeRunInput.model_validate(original.model_dump(mode="json"))
+ assert round_tripped == original
+ assert round_tripped.analytics_groups == {"organization": "org_acme"}
diff --git a/tests/unit/pipelex/system/test_analytics_groups.py b/tests/unit/pipelex/system/test_analytics_groups.py
new file mode 100644
index 000000000..dafc8da12
--- /dev/null
+++ b/tests/unit/pipelex/system/test_analytics_groups.py
@@ -0,0 +1,155 @@
+"""`analytics_groups` — the construction-time guard on the host's opaque group labels.
+
+The mapping is host-supplied and arrives over a wire, so it is exactly the kind
+of value that must be refused at the type rather than three frames into a run.
+It is also *never read by name* here: the runtime forwards it to whichever
+telemetry consumer understands groups and learns nothing about what an
+`organization` is. That makes the charset and the size bound the only thing
+standing between a caller's mistake and a telemetry backend, which is what these
+tests pin.
+"""
+
+from __future__ import annotations
+
+import pytest
+from pydantic import ValidationError
+
+from pipelex.system.analytics_groups import (
+ ANALYTICS_GROUP_KEY_PATTERN,
+ ANALYTICS_GROUP_TYPE_PATTERN,
+ ANALYTICS_GROUPS_MAX_ENTRIES,
+ validate_analytics_groups,
+)
+from pipelex.system.job_metadata import JobMetadata, RunMetadata
+
+
+def _metadata(analytics_groups: dict[str, str]) -> JobMetadata:
+ return JobMetadata(
+ run_metadata=RunMetadata(
+ user_id="u1",
+ pipeline_run_id="run_1",
+ storage_scope="tenant/run_1",
+ analytics_groups=analytics_groups,
+ )
+ )
+
+
+class TestAnalyticsGroups:
+ @pytest.mark.parametrize(
+ "groups",
+ [
+ pytest.param({}, id="empty-mapping"),
+ pytest.param({"organization": "org_acme"}, id="the-hosted-plane-shape"),
+ pytest.param({"organization": "org_acme", "workspace": "ws-1"}, id="two-group-types"),
+ pytest.param({"a": "x"}, id="shortest-key-and-value"),
+ pytest.param({"a_b_c9": "A-Z_az-09"}, id="full-charset"),
+ pytest.param({"a" * 32: "v" * 128}, id="longest-key-and-value"),
+ pytest.param({f"g{index}": "v" for index in range(ANALYTICS_GROUPS_MAX_ENTRIES)}, id="at-the-entry-cap"),
+ ],
+ )
+ def test_well_formed_groups_are_accepted(self, groups: dict[str, str]) -> None:
+ assert _metadata(groups).run_metadata.analytics_groups == groups
+
+ def test_an_empty_mapping_is_the_default(self) -> None:
+ """Unlike `user_id` and `storage_scope`, this field defaults.
+
+ An absent group creates no shared namespace and misattributes nothing —
+ it only leaves the group facet empty. The doctrine that made the other
+ two required is about IDENTITY, and identity is still non-defaulting.
+ """
+ run_metadata = RunMetadata(user_id="u1", pipeline_run_id="run_1", storage_scope="tenant/run_1")
+ assert run_metadata.analytics_groups == {}
+
+ def test_two_run_metadatas_do_not_share_one_default_mapping(self) -> None:
+ """A mutable default shared between instances would let one run's groups leak into another."""
+ first = RunMetadata(user_id="u1", pipeline_run_id="run_1", storage_scope="tenant/run_1")
+ second = RunMetadata(user_id="u2", pipeline_run_id="run_2", storage_scope="tenant/run_2")
+ first.analytics_groups["organization"] = "org_acme"
+ assert second.analytics_groups == {}
+
+ @pytest.mark.parametrize(
+ "groups",
+ [
+ pytest.param({"Organization": "org_acme"}, id="uppercase-key"),
+ pytest.param({"9org": "org_acme"}, id="key-starting-with-a-digit"),
+ pytest.param({"_org": "org_acme"}, id="key-starting-with-an-underscore"),
+ pytest.param({"": "org_acme"}, id="empty-key"),
+ pytest.param({"org-id": "org_acme"}, id="hyphen-in-key"),
+ pytest.param({"org id": "org_acme"}, id="space-in-key"),
+ pytest.param({"org.id": "org_acme"}, id="dot-in-key"),
+ pytest.param({"a" * 33: "org_acme"}, id="key-one-over-the-length-cap"),
+ pytest.param({"organization": ""}, id="empty-value"),
+ pytest.param({"organization": "org acme"}, id="space-in-value"),
+ pytest.param({"organization": "org/acme"}, id="slash-in-value"),
+ pytest.param({"organization": "org.acme"}, id="dot-in-value"),
+ # A `$`-anchored `re.match` admits one trailing newline, which is a log
+ # forging primitive once the value is quoted into a log line. The
+ # validator uses `fullmatch`; these pin it shut, as they do for
+ # `storage_scope`.
+ pytest.param({"organization": "org_acme\n"}, id="trailing-newline-in-value"),
+ pytest.param({"organization": "org\nacme"}, id="interior-newline-in-value"),
+ pytest.param({"organization": "org_acme\r"}, id="trailing-carriage-return-in-value"),
+ pytest.param({"organization\n": "org_acme"}, id="trailing-newline-in-key"),
+ pytest.param({"organization": "v" * 129}, id="value-one-over-the-length-cap"),
+ pytest.param({f"g{index}": "v" for index in range(ANALYTICS_GROUPS_MAX_ENTRIES + 1)}, id="one-over-the-entry-cap"),
+ ],
+ )
+ def test_malformed_groups_raise_at_construction(self, groups: dict[str, str]) -> None:
+ """Refused when the object is BUILT, not when a telemetry consumer chokes on it.
+
+ Same reasoning as `storage_scope`: a `RunMetadata` that exists is one
+ whose groups are safe to forward, so no downstream exporter has to
+ re-check them.
+ """
+ with pytest.raises(ValidationError):
+ _metadata(groups)
+
+ def test_the_error_names_the_offending_entry(self) -> None:
+ """The caller supplied the mapping, so the message must say which entry it got wrong."""
+ with pytest.raises(ValidationError, match="Organization"):
+ _metadata({"Organization": "org_acme"})
+
+ def test_an_unknown_group_type_is_carried_through(self) -> None:
+ """No key is privileged: `organization` is the hosted plane's word, not the runtime's.
+
+ The runtime is forbidden to learn what an organization is — the same rule
+ that keeps `storage_scope` opaque — so a group type it has never heard of
+ must travel exactly as well as the one the platform happens to send.
+ """
+ groups = {"tenant": "t-1", "plan_tier": "enterprise"}
+ assert _metadata(groups).run_metadata.analytics_groups == groups
+
+ def test_copy_with_update_carries_the_groups_through(self) -> None:
+ """`copy_with_update` replaces the per-job half and carries the run half intact.
+
+ A nested pipe's span is part of the same run, so it must attribute to the
+ same groups. Losing them here would leave the group facet empty for every
+ span but the outermost one.
+ """
+ parent = _metadata({"organization": "org_acme"})
+ child = parent.copy_with_update(otel_context=None, pipe_code="nested_pipe")
+ assert child.run_metadata.analytics_groups == {"organization": "org_acme"}
+ assert child.pipe_code == "nested_pipe"
+
+ def test_the_copy_does_not_alias_the_parents_mapping(self) -> None:
+ """`copy_with_update` deep-copies, so a child mutating its groups cannot reach the parent."""
+ parent = _metadata({"organization": "org_acme"})
+ child = parent.copy_with_update(otel_context=None)
+ child.run_metadata.analytics_groups["organization"] = "org_other"
+ assert parent.run_metadata.analytics_groups == {"organization": "org_acme"}
+
+ def test_the_helper_returns_the_mapping_it_was_given(self) -> None:
+ groups = {"organization": "org_acme"}
+ assert validate_analytics_groups(value=groups) == groups
+
+ def test_the_helper_raises_value_error_rather_than_a_pydantic_error(self) -> None:
+ """It is shared by the field validator and the wire payload, so it speaks stdlib."""
+ with pytest.raises(ValueError, match="analytics_groups"):
+ validate_analytics_groups(value={"Organization": "org_acme"})
+
+ def test_the_patterns_are_anchored_by_fullmatch_not_by_the_dollar_sign(self) -> None:
+ """`re.match` with a trailing `$` accepts one final newline; `fullmatch` does not."""
+ assert ANALYTICS_GROUP_TYPE_PATTERN.match("organization\n") is not None
+ assert ANALYTICS_GROUP_TYPE_PATTERN.fullmatch("organization\n") is None
+ assert ANALYTICS_GROUP_KEY_PATTERN.match("org_acme\n") is not None
+ assert ANALYTICS_GROUP_KEY_PATTERN.fullmatch("org_acme\n") is None