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/Json-sink-per-value-fallback · L-260930-7961f7 (#1386)

Louis Choquel5ab350dc8d6d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7fc730cb2..b6734a67d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@
- **Stored names are plain input names (Breaking)**: every name under which a step stores a value in working memory, a `PipeSequence` step's or a `PipeParallel` branch's `result`, the `batch_as` of either, and a `PipeBatch`'s `input_item_name`, must now be a plain input name matching `[a-z][a-z0-9_]*`, as a binding step's `result` already had to, and a name in any other form, such as `Pages`, `doc.pages` or `_pages`, is refused as `invalid_input_name` wherever a bundle loads, and by the MTHDS JSON Schema, which now carries the input-name pattern on these fields. Rename such a name to a plain one, such as `pages`, along with every input, binding path and `batch_over` that reads it; a plain `batch_over` is still refused only when it starts with the reserved `_bound_`.
- **Hosted-run guidance in messages and help**: the next step of a refused Pipelex API key names `pipelex login` and the working directory's `.env` rather than a shell export, which a `.env` file setting the key overrides, and `pipelex login` names `[run] execution = "hosted"` rather than `pipelex init` to make hosted runs the default. A CLI run missing a provider key, and the `pipelex doctor` report, offer the hosted Pipelex API as a way out; a failed `pipelex-agent` boot points at `pipelex-agent migrate` and `pipelex-agent init` rather than the interactive `pipelex init config`; and `FormerReleaseConfigError` carries its remedy, `pipelex migrate`, as its `user_action`. The `run` help of both CLIs names hosted runs, catalog ids, local method directories and TOML or inline inputs, and `pipelex-agent --help` describes the program rather than printing an internal note.
+### Fixed
+
+- **The `json` log sink keeps each field's type**: a field value JSON refuses outright, a mapping with a non-string key or a circular reference, is written as its `repr` alone, where it used to turn every other field on the line into its `repr` as well, so a number or a boolean beside it arrived as `"7"` or `"True"` and a query over that field missed the line. The other fields now keep their JSON types, as they already did under the `gcp` sink.
+
## [v0.79.1] - 2026-10-09
### Fixed
diff --git a/docs/configuration/config-practical/logging-config.md b/docs/configuration/config-practical/logging-config.md
index 01ab64b55..f1397aa85 100644
--- a/docs/configuration/config-practical/logging-config.md
+++ b/docs/configuration/config-practical/logging-config.md
@@ -198,7 +198,7 @@ keywords_to_hilight = []
## The `json` Sink
-No section of its own: the sink writes to `console_log_target`, one JSON object per line and no ANSI ever. Each line carries `time` (ISO 8601, UTC, milliseconds, `Z`), `severity` (the level name), `logger` (the module-named logger), `message`, `exception` when the record carries one, `trace_id`, `span_id` and `trace_flags` when OpenTelemetry's current span names a trace, `pipelex.trace_id` and `pipelex.span_id` when a Pipelex span is active, and then every field, the run-scoped identifiers and the `data` attribute flat beside them, under their own names. The three standard trace keys are the ones OpenTelemetry specifies for trace context in a JSON log that is not OTLP, lowercase hex at their full widths (32, 16 and 2 digits), and they name OpenTelemetry's current span, your own code's, which Pipelex reads and never changes, so a collector or an error tracker joins the line to your trace. The two `pipelex.*` keys, 32 and 16 hex digits, name the Pipelex span active at the log call, the pipe's own or the LLM call's during a run. The two sets are independent, so a line in a run under no span of yours carries only the `pipelex.*` keys (see [Logging](../../tools/logging.md#the-trace-context)). Every key the sink writes, the trace keys included, is reserved on every line, so a field named like one of them is carried under a `field_` prefix whether or not the line carries an exception or a span, and a non-finite float is written as the string `"NaN"`, `"Infinity"` or `"-Infinity"`. The key names are the ones the CloudWatch agent, the Google Cloud Logging agent and any OTLP collector ingest without a parser.
+No section of its own: the sink writes to `console_log_target`, one JSON object per line and no ANSI ever. Each line carries `time` (ISO 8601, UTC, milliseconds, `Z`), `severity` (the level name), `logger` (the module-named logger), `message`, `exception` when the record carries one, `trace_id`, `span_id` and `trace_flags` when OpenTelemetry's current span names a trace, `pipelex.trace_id` and `pipelex.span_id` when a Pipelex span is active, and then every field, the run-scoped identifiers and the `data` attribute flat beside them, under their own names. The three standard trace keys are the ones OpenTelemetry specifies for trace context in a JSON log that is not OTLP, lowercase hex at their full widths (32, 16 and 2 digits), and they name OpenTelemetry's current span, your own code's, which Pipelex reads and never changes, so a collector or an error tracker joins the line to your trace. The two `pipelex.*` keys, 32 and 16 hex digits, name the Pipelex span active at the log call, the pipe's own or the LLM call's during a run. The two sets are independent, so a line in a run under no span of yours carries only the `pipelex.*` keys (see [Logging](../../tools/logging.md#the-trace-context)). Every key the sink writes, the trace keys included, is reserved on every line, so a field named like one of them is carried under a `field_` prefix whether or not the line carries an exception or a span, and a non-finite float is written as the string `"NaN"`, `"Infinity"` or `"-Infinity"`. A value JSON refuses outright, a circular reference or a mapping with a non-string key, is written as its `repr`, and every other field on the same line keeps its JSON type, so a number or a boolean beside it stays queryable as one. The key names are the ones the CloudWatch agent, the Google Cloud Logging agent and any OTLP collector ingest without a parser.
```json
{"time": "2026-09-16T10:12:03.417Z", "severity": "INFO", "logger": "pipelex.pipe_operators.pipe_llm", "message": "Running the pipe", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "span_id": "00f067aa0ba902b7", "trace_flags": "01", "pipelex.trace_id": "0af7651916cd43dd8448eb211c80319c", "pipelex.span_id": "b7ad6b7169203331", "request_id": "req-7f3a", "pipeline_run_id": "plr-01", "pipe_run_id": "pr-9c", "model": "gpt-5"}
diff --git a/docs/tools/logging.md b/docs/tools/logging.md
index 8bd973fe9..2cc4838c2 100644
--- a/docs/tools/logging.md
+++ b/docs/tools/logging.md
@@ -64,7 +64,7 @@ Every one of the seven methods (`verbose`, `debug`, `dev`, `info`, `warning`, `e
`fields` is a mapping of named values. Each entry becomes an attribute of the emitted `LogRecord`, which is where a formatter or a sink reads it: `record.files` for the example above, or `%(files)s` in a stdlib format string. Nothing from `fields` is written into the message, so `record.getMessage()` is exactly the text you passed.
-A value can be anything. It rides the record by reference and the sink serializes it on emit, on the calling thread, so what leaves the process is the value as it was at the call, and mutating it afterwards changes nothing already emitted. The `console` sink ignores it, the `json` sink dumps a pydantic model in JSON mode and falls back to `str` for a value JSON does not know, and the `otlp` sink carries a scalar or a sequence of scalars as an attribute and anything else as JSON text; prefer plain JSON-ready values (strings, numbers, booleans, lists and dictionaries of those) for anything meant to be queried later.
+A value can be anything. It rides the record by reference and the sink serializes it on emit, on the calling thread, so what leaves the process is the value as it was at the call, and mutating it afterwards changes nothing already emitted. The `console` sink ignores it, the `json` sink dumps a pydantic model in JSON mode and falls back to `str` for a value JSON does not know, and the `otlp` sink carries a scalar or a sequence of scalars as an attribute and anything else as JSON text; prefer plain JSON-ready values (strings, numbers, booleans, lists and dictionaries of those) for anything meant to be queried later. A value JSON refuses outright, a circular reference or a mapping with a non-string key, is written by the `json` sink as its `repr`, and that costs the value alone: every other field on the line keeps its JSON type, so a number or a boolean beside it is still queried as one.
### Naming convention
diff --git a/pipelex/tools/log/json_log_sink.py b/pipelex/tools/log/json_log_sink.py
index 5e643d0dd..3c57ad72a 100644
--- a/pipelex/tools/log/json_log_sink.py
+++ b/pipelex/tools/log/json_log_sink.py
@@ -15,7 +15,9 @@ keys, the trace keys among them, are reserved whether or not the line carries th
one is carried under the same ``field_`` prefix the record uses for a name the stdlib owns, on every line
and not only the ones with an exception or a span, so no value is lost and a field keeps one wire name.
A non-finite float is written as the string ``"NaN"``, ``"Infinity"`` or ``"-Infinity"``, since JSON has
-no token for it that a strict parser accepts.
+no token for it that a strict parser accepts. A carried value ``json`` refuses outright, a circular
+reference or a mapping with a non-string key, is written as its ``repr`` alone, and every other field on
+the line keeps its JSON type, as under the ``gcp`` sink.
"""
from __future__ import annotations
@@ -36,7 +38,7 @@ from pipelex.system.telemetry.current_span import (
pipelex_trace_fields_for_logs,
)
from pipelex.tools.log.log_fields import COLLIDING_FIELD_PREFIX, carried_attributes
-from pipelex.tools.log.log_sink import LogSink, json_fallback, spell_non_finite
+from pipelex.tools.log.log_sink import LogSink, json_fallback, render_json, spell_non_finite
if TYPE_CHECKING:
from typing import TextIO
@@ -71,15 +73,17 @@ def _json_line(*, payload: dict[str, Any]) -> str:
A model dumps in JSON mode and an unknown object becomes its text. When ``json`` refuses the
payload outright, a circular reference or a mapping with a non-string key inside a carried value,
- every carried value is written as its ``repr`` and the line keeps its shape: a sink must render
+ each value is rendered on its own through the wire renderer the ``gcp`` sink uses, so the value
+ ``json`` refuses is written as its ``repr`` and every other value on the line keeps its JSON type: a
+ number stays a number and a boolean a boolean beside it. The line keeps its shape: a sink must render
every record it is handed, and a serialization failure is a fact about the value, never a reason to
- lose the line or to break the one-object-per-line contract.
+ lose the line, to break the one-object-per-line contract or to cost another field its type.
"""
try:
return json.dumps(payload, ensure_ascii=False, allow_nan=False, default=json_fallback)
except (TypeError, ValueError):
- safe_payload = {key: value if key in FIXED_KEYS else repr(value) for key, value in payload.items()}
- return json.dumps(safe_payload, ensure_ascii=False, default=str)
+ safe_payload = {key: json.loads(render_json(value=value)) for key, value in payload.items()}
+ return json.dumps(safe_payload, ensure_ascii=False, allow_nan=False)
def _trace_context() -> dict[str, str]:
diff --git a/tests/unit/pipelex/tools/test_log_gcp_json_payload_parity.py b/tests/unit/pipelex/tools/test_log_gcp_json_payload_parity.py
index 728b942a3..dbc6f519c 100644
--- a/tests/unit/pipelex/tools/test_log_gcp_json_payload_parity.py
+++ b/tests/unit/pipelex/tools/test_log_gcp_json_payload_parity.py
@@ -113,6 +113,15 @@ class TestTheGcpAndJsonPayloadsAgree:
for key in (PIPELEX_TRACE_ID_KEY, PIPELEX_SPAN_ID_KEY):
assert gcp_payload[key] == json_payload[key]
+ def test_a_value_json_refuses_costs_only_itself_under_both_sinks(self) -> None:
+ """Each sink writes the refused value as its ``repr`` and keeps the type of every value beside it."""
+ json_payload, gcp_payload = self._both_payloads(self._record(fields={"payload": {(1, 2): "tuple-key"}, "count": 7, "ok": True}))
+
+ for payload in (json_payload, gcp_payload):
+ assert payload["payload"] == repr({(1, 2): "tuple-key"})
+ assert payload["count"] == 7
+ assert payload["ok"] is True
+
def test_a_field_named_like_a_pipelex_key_is_prefixed_under_both(self) -> None:
json_payload, gcp_payload = self._both_payloads(self._record(fields={PIPELEX_TRACE_ID_KEY: "mine", PIPELEX_SPAN_ID_KEY: "mine"}))
diff --git a/tests/unit/pipelex/tools/test_log_json_sink.py b/tests/unit/pipelex/tools/test_log_json_sink.py
index d5bbbaa6d..9fc9357dd 100644
--- a/tests/unit/pipelex/tools/test_log_json_sink.py
+++ b/tests/unit/pipelex/tools/test_log_json_sink.py
@@ -166,17 +166,48 @@ class TestJsonLogSink:
assert cyclic_line["loop"] == {"me": CYCLE_TEXT}
def test_a_raw_cycle_reaching_the_formatter_keeps_the_line_an_object(self) -> None:
- """The sink's own guard, for a process with redaction off: a value ``json`` refuses is written as its ``repr``, the line stays one object."""
+ """The sink's own guard, for a process with redaction off: a value ``json`` refuses is written as its ``repr``, the line stays one object.
+
+ The ``repr`` costs the cycle alone: the values beside it keep their JSON types.
+ """
cyclic: dict[str, Any] = {}
cyclic["me"] = cyclic
record = logging.LogRecord(name=__name__, level=logging.INFO, pathname="", lineno=0, msg="cyclic value", args=(), exc_info=None)
record.loop = cyclic
+ record.count = 7
+ record.ok = True
+ record.tags = ["a", "b"]
line = json.loads(JsonLogFormatter().format(record))
assert line[MESSAGE_KEY] == "cyclic value"
assert isinstance(line["loop"], str)
assert "{...}" in line["loop"]
+ assert line["count"] == 7
+ assert line["ok"] is True
+ assert line["tags"] == ["a", "b"]
+
+ def test_a_value_json_refuses_costs_only_itself_its_type(self, json_log: tuple[Log, io.StringIO]) -> None:
+ """A mapping with a non-string key is written as its ``repr``, and the number, the boolean and the rest beside it keep their JSON types.
+
+ The line's recovery used to write every carried value as its ``repr``, so a query over ``count``
+ or ``ok`` silently missed the line: ``count`` arrived as ``"7"`` and ``ok`` as ``"True"``.
+ """
+ fresh, buffer = json_log
+ fresh.info(
+ "one refused value",
+ fields={"payload": {(1, 2): "tuple-key"}, "count": 7, "ok": True, "ratio": 0.5, "reading": float("nan"), "nested": {"flag": False}},
+ )
+
+ (line,) = _own_lines(buffer)
+ assert line[MESSAGE_KEY] == "one refused value"
+ assert line[SEVERITY_KEY] == "INFO"
+ assert line["payload"] == repr({(1, 2): "tuple-key"})
+ assert line["count"] == 7
+ assert line["ok"] is True
+ assert line["ratio"] == 0.5
+ assert line["reading"] == "NaN"
+ assert line["nested"] == {"flag": False}
def test_a_non_finite_float_is_written_as_text_a_strict_parser_accepts(self, json_log: tuple[Log, io.StringIO]) -> None:
"""JSON has no NaN: the bare tokens Python writes by default would cost the whole line, so they are strings."""