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.
fix/Kernel-log-context · L-260927-a43abf (#1283)
Louis Choquel4520b42a2457
diff --git a/.drift/acks/pipelex-kernel-docs.toml b/.drift/acks/pipelex-kernel-docs.tomlindex e90dcc010..cbb4f41a9 100644--- a/.drift/acks/pipelex-kernel-docs.toml+++ b/.drift/acks/pipelex-kernel-docs.toml@@ -1,28 +1,28 @@contract = "pipelex-kernel-docs"-digest = "sha256:c9de05f94227aa7679111cf720166b97249792b096a54bdcdc2ecac99168b860"-reviewed_by = "thomashebrard"-reviewed_at = "2026-09-24T09:00:51Z"-rationale = "PipelexKernel.make renamed its analytics_groups parameter to extras (opaque host-supplied labels). The kernel doc's run-scoped-state bullet already names extras on run_metadata and says the host supplies it at make time; the two make examples pass neither and stay correct."+digest = "sha256:e3d7af90de41b84414d57788256a8dd00350049d845262d8d1c427435b785bb9"+reviewed_by = "Louis Choquel"+reviewed_at = "2026-09-27T18:04:39Z"+rationale = "Review round 1 fixes: PipelexKernel.make now refuses an empty pipeline_run_id with ValueError, stated in its docstring and the changelog; the kernel doc's log-context section now claims only what the PipeLLM test pins."[trigger_files]"pipelex/kernel/__init__.py" = "blob:c4f1b0fe2ccc17db9110733f71b612f4ac1ba4ce""pipelex/kernel/compose_ops.py" = "blob:ccd8ba141246380eb5e9d55e693fa6fedf38233a""pipelex/kernel/compose_results.py" = "blob:a837ae9680c7d4d0eb4dee37d4657c410e5b5cea""pipelex/kernel/exceptions.py" = "blob:45e9ad60c2699f7b57cad0a46c13f0b07b4cfbc9"-"pipelex/kernel/extract_ops.py" = "blob:cd596c03e45ab57eccca6fe1bf332e5977d1f2b2"+"pipelex/kernel/extract_ops.py" = "blob:19d556f0254017d7d52c30f4f1a46e2235289042""pipelex/kernel/extract_results.py" = "blob:79405a56760f3d4b483660d76441fff95f58c64d""pipelex/kernel/func_ops.py" = "blob:97c68c977ddc260c9b36b7eda5f4c7964e956a27""pipelex/kernel/func_results.py" = "blob:a7425a0ddc21571f23c53b92f5d7559ffdd08b71"-"pipelex/kernel/img_gen_ops.py" = "blob:01988c6f086929e4f745500d82054d7a5e3592de"+"pipelex/kernel/img_gen_ops.py" = "blob:b85360f6c118e93be53bf8d1a04504ccb7552469""pipelex/kernel/img_gen_prompt.py" = "blob:e4f72040561929aa0d96ad5f00b1c4af652d3f77""pipelex/kernel/img_gen_results.py" = "blob:46b4ca11c70d906ae6d58ce66461f9b3414f1bfa"-"pipelex/kernel/llm_ops.py" = "blob:ec93c42dd6d0af4142981f060ce3f9656072ba7a"+"pipelex/kernel/llm_ops.py" = "blob:64a6d3d77a165f4f70614ced69876f56d873a8c7""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:70d0cca4c8c009103e139594dc938fa0de287478"+"pipelex/kernel/pipelex_kernel.py" = "blob:355a6e1b118b9b3236fe84ed71887e7c11612c63""pipelex/kernel/prompt_references.py" = "blob:03ec9ef67ae84f141d072ca2d2c3ef888549ccc0"-"pipelex/kernel/search_ops.py" = "blob:ed0a8c7953aca1e38de852d0ddef11731b819539"+"pipelex/kernel/search_ops.py" = "blob:f9c1dc09dd3beaf1a54ac8e3774db1d510cbdaa3""pipelex/kernel/search_results.py" = "blob:101b70dc96cc5ee1721c9f6b1cb725a5ca78ff70""pipelex/kernel/templating_style_ops.py" = "blob:395473806d600dfc4f124c07f2afebb951fc086b"-"tests/unit/pipelex/kernel/test_kernel_boot_contract.py" = "blob:4f440b21ad51f27c098efff4d3a04433b53914bc"+"tests/unit/pipelex/kernel/test_kernel_boot_contract.py" = "blob:b9e95adeed43a1eaa5467cb146cda1ba65127273"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 47ec23251..ad4958291 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,16 @@# Changelog+## [Unreleased]++### Added++- **`PipelexKernel.log_context()` and `JobMetadata.log_context()`**: `JobMetadata.log_context()` binds a job's `request_id`, `pipeline_run_id` and `pipe_run_id` onto the log context in one call, and `PipelexKernel.log_context()` binds a kernel run's `request_id` and `pipeline_run_id`, which a host wraps its run in so the lines it emits between kernel calls name the run.+- **`PipelexKernel.make` takes `request_id` and `pipeline_run_id`**: a kernel-driven run can now carry the inbound request id a hosted deployment filters its logs on, and name itself with an id the host chooses. A host inside a replay-based executor passes a `pipeline_run_id` or a trace context, since the default `uuid4` changes on every replay; a trace context and a `pipeline_run_id` that disagree, or an empty `pipeline_run_id`, raise `ValueError`.++### Fixed++- **A kernel step's log lines name its run and its step**: `run_llm_text`, `run_llm_object`, `generate_object_content`, `run_extract`, `run_search` and `run_img_gen` now bind the `job_metadata` they are handed for the whole call, so a program driving the kernel directly gets log records carrying `request_id`, `pipeline_run_id` and `pipe_run_id`, as an interpreted run's do. An interpreted run's lines are unchanged.+## [v0.67.1] - 2026-09-27### Changeddiff --git a/docs/tools/logging.md b/docs/tools/logging.mdindex f6420efe9..d194494a1 100644--- a/docs/tools/logging.md+++ b/docs/tools/logging.md@@ -105,12 +105,14 @@ The context is a `LogContext` with three optional identifiers, `request_id`, `piThe identifiers travel in the payload, and the contextvar is in-process plumbing bound after deserialization and nothing else; it never crosses a process boundary. Each process entry binds from the payload it received:-- **A direct-mode run**: `PipeRun.run` binds `request_id` and `pipeline_run_id` from the job's `JobMetadata` for the whole run, delivery included, and releases the binding when the run returns. The metadata a submission builds carries no `pipe_run_id` yet.+- **A direct-mode run**: `PipeRun.run` binds `request_id` and `pipeline_run_id` from the job's `JobMetadata` for the whole run, delivery included, through `JobMetadata.log_context()`, and releases the binding when the run returns. The metadata a submission builds carries no `pipe_run_id` yet.- **Every pipe run**: `live_run_pipe` mints the pipe run's id and binds `pipe_run_id` around the whole of the run, the line announcing it, its span lines and its failure included, so every record emitted during a pipe's run names the run it belongs to, a nested pipe rebinding its own and the outer id coming back when it returns, however it returns. A pipe lifted for absent optional inputs does not run and has no id: its skip line carries the enclosing binding, the parent pipe's or none. This is the binding every orchestration shares, direct or distributed.+- **Every kernel step**: each kernel function that takes a `job_metadata` — `run_llm_text`, `run_llm_object`, `generate_object_content`, `run_extract`, `run_search` and `run_img_gen` — binds it for the length of its call, so a program driving the kernel directly gets lines naming the run and the step. Inside the interpreter the operator hands the kernel the `pipe_run_id` that `live_run_pipe` already bound, so this nested binding changes nothing there.+- **A kernel-driven run**: the host wraps its run in `PipelexKernel.log_context()`, which binds `request_id` and `pipeline_run_id` and no step. The kernel has no run boundary of its own, so this binding is the host's, and each step's binding merges over it. See [The Pipelex Kernel](../under-the-hood/pipelex-kernel.md#the-log-context).- **An API request**: the runner's request middleware is where `request_id` is bound from the inbound request, for the request's duration.- **A durable-execution activity or workflow**: the entry is where the identifiers are bound from the payload the orchestrator handed it.-The last two are the runner's and the orchestration plugin's to bind, beside the payload they read; the runtime only provides `log.context`.+The last two are the runner's and the orchestration plugin's to bind, beside the payload they read. The runtime provides `log.context` for any identifiers, and `JobMetadata.log_context()` to bind the three a `JobMetadata` carries in one call.### The trace contextdiff --git a/docs/under-the-hood/pipelex-kernel.md b/docs/under-the-hood/pipelex-kernel.mdindex 61b85cf57..b6c257097 100644--- a/docs/under-the-hood/pipelex-kernel.md+++ b/docs/under-the-hood/pipelex-kernel.md@@ -68,7 +68,7 @@ Both façade calls take the concept and the output class the caller wants, defau| Module | Entry points ||---|---|-| `pipelex.kernel.pipelex_kernel` | `PipelexKernel.make`, `.llm_text`, `.llm_object`, `.make_step_metadata` |+| `pipelex.kernel.pipelex_kernel` | `PipelexKernel.make`, `.llm_text`, `.llm_object`, `.make_step_metadata`, `.log_context` || `pipelex.kernel.llm_ops` | `resolve_llm_setting_for_text` / `_for_object`, `concrete_llm_model_handle`, `derive_structure_prompt`, `generate_object_content`, `run_llm_text`, `run_llm_object` || `pipelex.kernel.templating_style_ops` | `resolve_templating_style` || `pipelex.kernel.extract_ops` | `resolve_extract_setting`, `build_extract_job_params`, `run_extract` |@@ -127,9 +127,10 @@ 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`, `extras` — 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 `extras` 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.+- **`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`, `extras` — 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`, `request_id` and `extras` 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. `request_id` is the inbound request the run serves, validated by `RunMetadata` exactly as on the pipeline entry points, and it is what a hosted deployment filters its logs on. 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.+- **The run's own id** follows the same rule, once per run rather than once per step. `make` takes it from a `trace_context`'s `graph_id` when one is given, else from `pipeline_run_id=…`, else from a fresh `uuid4`. **A host inside a replay-based executor must pass one of the two**, because the `uuid4` default re-mints on every replay and the replayed run would then name itself differently from the run it replays. Such a host mints the id from its own replay-safe source (a workflow's deterministic random, or its workflow id) and passes the value; a value is enough here where the step id needs a callable, because the run id is minted exactly once.Nothing derived from config or the model deck is cached on the instance — resolved settings and templating styles are computed per call, because cached derived state would shadow a later config or deck change and break per-call variation.@@ -154,12 +155,29 @@ finally:get_report_delegate().clear_event_log(context_key=trace_context.lookup_key)```-Passing a `trace_context` adopts its `graph_id` as the run's `pipeline_run_id`. The two are one identity: letting them diverge would scatter a single run's usage events across two ids, because the registered-context emit path stamps the event log's id while the runner fallback stamps the metadata's — and a read-back keyed on either would silently miss the other's.+Passing a `trace_context` adopts its `graph_id` as the run's `pipeline_run_id`, and passing a `pipeline_run_id` that differs from it raises `ValueError` rather than letting either win. The two are one identity: letting them diverge would scatter a single run's usage events across two ids, because the registered-context emit path stamps the event log's id while the runner fallback stamps the metadata's — and a read-back keyed on either would silently miss the other's.`pipelex.tracing` holds both halves a caller needs (`make_event_log` for a configured backend, `UsageAggregator` for the read-back) and is kernel-layer, so none of this costs the boot contract. The records that come out are the same [`TokensUsage` wire records](./tokens-usage-wire-records.md) an `/execute` response carries — pinned by an integration test that runs the same step through both callers and compares them.---+## The log context++A record emitted inside a `log.context` block carries the run's identifiers — `request_id`, `pipeline_run_id` and `pipe_run_id` — as fields a sink can filter on ([Logging](../tools/logging.md#the-run-scoped-context)). The interpreter binds them around a run and around each pipe; a program driving the kernel has no interpreter around it, so the kernel binds them itself, split the same way as the usage lifecycle above.++- **Each step binds itself.** Every kernel function that takes a `job_metadata` — `run_llm_text`, `run_llm_object`, `generate_object_content`, `run_extract`, `run_search` and `run_img_gen` — opens its body with `with job_metadata.log_context():`, so every line it emits, from prompt assembly to the memory write-back and any failure raised on the way, names the run and the step. A unit test sweeps `pipelex/kernel/` and fails on a function that takes a `job_metadata` without opening its body that way, so the rule holds for the next function added as well.+- **The host binds the run.** `PipelexKernel.log_context()` binds `request_id` and `pipeline_run_id` and no step, and a host wraps its run in it. The kernel cannot do this for the host, for the reason it cannot own the usage lifecycle: a kernel call has no run boundary to hang the binding on. Inside the host's block, each step's binding merges over the run's for the length of the call, so a line the host emits between two calls names the run, and a line emitted during one names the step as well.++```python+kernel = PipelexKernel.make(user_id="my-service", storage_scope="my-service", request_id=request_id, pipeline_run_id=run_id)+with kernel.log_context():+ result = await kernel.llm_text(memory=memory, user="Summarize $topic", result="summary")+```++`JobMetadata.log_context()` is the one spelling of the binding, used by both layers and by the interpreter's `PipeRun.run`. Inside the interpreter the kernel's binding changes nothing: the metadata an operator hands the kernel carries the `pipe_run_id` that `live_run_pipe` minted and already bound, so the nested binding rebinds equal values. A test on `PipeLLM` pins that equality for the operator the other kernel-backed operators follow; none of them copies the metadata it hands down, and one that started minting its own id would re-attribute its lines to a pipe run nobody announced. `run_compose_template` and `run_func` take no `job_metadata`, so their lines carry the host's run-level binding and no step.++---+## What the kernel deliberately does not coverTwo arms of the interpreter stayed interpreter-side, both because moving them would cost more than the caller gains:diff --git a/pipelex/kernel/extract_ops.py b/pipelex/kernel/extract_ops.pyindex cd596c03e..19d556f02 100644--- a/pipelex/kernel/extract_ops.py+++ b/pipelex/kernel/extract_ops.py@@ -80,17 +80,18 @@ async def run_extract(when the source is a single image — so there is no multiplicity fork here as there is on the LLMand image-generation paths."""- page_contents = await get_content_generator().make_extract_pages(- extract_input=extract_input,- cogt_run_params=cogt_run_params,- extract_handle=extract_setting.model,- job_metadata=job_metadata,- extract_job_params=extract_job_params,- extract_job_config=ExtractJobConfig(),- )- content: ListContent[PageContent] = ListContent(items=page_contents)- return ExtractResult(- memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),- content=content,- extract_setting=extract_setting,- )+ with job_metadata.log_context():+ page_contents = await get_content_generator().make_extract_pages(+ extract_input=extract_input,+ cogt_run_params=cogt_run_params,+ extract_handle=extract_setting.model,+ job_metadata=job_metadata,+ extract_job_params=extract_job_params,+ extract_job_config=ExtractJobConfig(),+ )+ content: ListContent[PageContent] = ListContent(items=page_contents)+ return ExtractResult(+ memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),+ content=content,+ extract_setting=extract_setting,+ )diff --git a/pipelex/kernel/img_gen_ops.py b/pipelex/kernel/img_gen_ops.pyindex 01988c6f0..b85360f6c 100644--- a/pipelex/kernel/img_gen_ops.py+++ b/pipelex/kernel/img_gen_ops.py@@ -122,31 +122,32 @@ async def run_img_gen(image is re-validated onto it, because the content generator returns a plain `ImageContent` andthe declared output concept may refine it."""- img_gen_job_config = get_config().inference.img_gen.img_gen_job- content_generator = get_content_generator()- content: StuffContent- if nb_images > 1:- image_contents = await content_generator.make_image_list(- job_metadata=job_metadata,- cogt_run_params=cogt_run_params,- img_gen_handle=img_gen_setting.model,- img_gen_prompt=img_gen_prompt,- nb_images=nb_images,- img_gen_job_params=img_gen_job_params,- img_gen_job_config=img_gen_job_config,+ with job_metadata.log_context():+ img_gen_job_config = get_config().inference.img_gen.img_gen_job+ content_generator = get_content_generator()+ content: StuffContent+ if nb_images > 1:+ image_contents = await content_generator.make_image_list(+ job_metadata=job_metadata,+ cogt_run_params=cogt_run_params,+ img_gen_handle=img_gen_setting.model,+ img_gen_prompt=img_gen_prompt,+ nb_images=nb_images,+ img_gen_job_params=img_gen_job_params,+ img_gen_job_config=img_gen_job_config,+ )+ content = ListContent(items=[output_class.model_validate(image_content.smart_dump()) for image_content in image_contents])+ else:+ image_content = await content_generator.make_single_image(+ job_metadata=job_metadata,+ cogt_run_params=cogt_run_params,+ img_gen_handle=img_gen_setting.model,+ img_gen_prompt=img_gen_prompt,+ img_gen_job_params=img_gen_job_params,+ img_gen_job_config=img_gen_job_config,+ )+ content = output_class.model_validate(image_content.smart_dump())+ return ImgGenResult(+ memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),+ content=content,)- content = ListContent(items=[output_class.model_validate(image_content.smart_dump()) for image_content in image_contents])- else:- image_content = await content_generator.make_single_image(- job_metadata=job_metadata,- cogt_run_params=cogt_run_params,- img_gen_handle=img_gen_setting.model,- img_gen_prompt=img_gen_prompt,- img_gen_job_params=img_gen_job_params,- img_gen_job_config=img_gen_job_config,- )- content = output_class.model_validate(image_content.smart_dump())- return ImgGenResult(- memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),- content=content,- )diff --git a/pipelex/kernel/llm_ops.py b/pipelex/kernel/llm_ops.pyindex ec93c42dd..64a6d3d77 100644--- a/pipelex/kernel/llm_ops.py+++ b/pipelex/kernel/llm_ops.py@@ -148,28 +148,29 @@ async def generate_object_content(generator, so nothing rebuilds a class from a schema when the class already exists. The schemaround-trip further down still serves the distributed-activity boundary and is untouched."""- content_generator = get_content_generator()- if is_multiple_output:- count_desc = f"{fixed_nb_output}x" if fixed_nb_output else "list of "- log.verbose(f"Kernel generating {count_desc}{output_class.__name__} by object_direct")- generated_objects = await content_generator.make_object_list(+ with job_metadata.log_context():+ content_generator = get_content_generator()+ if is_multiple_output:+ count_desc = f"{fixed_nb_output}x" if fixed_nb_output else "list of "+ log.verbose(f"Kernel generating {count_desc}{output_class.__name__} by object_direct")+ generated_objects = await content_generator.make_object_list(+ job_metadata=job_metadata,+ cogt_run_params=cogt_run_params,+ object_class=output_class,+ llm_prompt_for_object_list=llm_prompt,+ llm_setting_for_object_list=llm_setting,+ nb_items=fixed_nb_output,+ )+ return ListContent(items=generated_objects)++ log.verbose(f"Kernel generating a single {output_class.__name__} by object_direct")+ return await content_generator.make_object(job_metadata=job_metadata,cogt_run_params=cogt_run_params,object_class=output_class,- llm_prompt_for_object_list=llm_prompt,- llm_setting_for_object_list=llm_setting,- nb_items=fixed_nb_output,+ llm_prompt_for_object=llm_prompt,+ llm_setting_for_object=llm_setting,)- return ListContent(items=generated_objects)-- log.verbose(f"Kernel generating a single {output_class.__name__} by object_direct")- return await content_generator.make_object(- job_metadata=job_metadata,- cogt_run_params=cogt_run_params,- object_class=output_class,- llm_prompt_for_object=llm_prompt,- llm_setting_for_object=llm_setting,- )async def run_llm_text(@@ -191,31 +192,32 @@ async def run_llm_text(`templating_style` is an argument because the style is an authoring decision the caller holds —what the step declared, resolved against the runtime default — not something derivable here."""- llm_prompt = await assemble_llm_prompt(- prompt_content=prompt_content,- context_provider=memory,- output_structure_prompt=None,- extra_params=extra_params,- templating_style=templating_style,- )- generated_text = await get_content_generator().make_llm_text(- job_metadata=job_metadata,- cogt_run_params=cogt_run_params,- llm_prompt_for_text=llm_prompt,- llm_setting_main=llm_setting,- )- # `model_validate` rather than `output_class(text=...)`: the class arrives typed as- # `type[StuffContent]`, whose declared fields do not include `text` — the subclasses that a- # Text-compatible concept resolves to are what carry it. Validation, and the `ValidationError`- # a mismatch raises, are identical either way.- content = output_class.model_validate({"text": generated_text})- return LlmTextResult(- memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),- text=generated_text,- rendered_prompt=llm_prompt,- llm_setting=llm_setting,- structuring_path=StructuringPath.TEXT,- )+ with job_metadata.log_context():+ llm_prompt = await assemble_llm_prompt(+ prompt_content=prompt_content,+ context_provider=memory,+ output_structure_prompt=None,+ extra_params=extra_params,+ templating_style=templating_style,+ )+ generated_text = await get_content_generator().make_llm_text(+ job_metadata=job_metadata,+ cogt_run_params=cogt_run_params,+ llm_prompt_for_text=llm_prompt,+ llm_setting_main=llm_setting,+ )+ # `model_validate` rather than `output_class(text=...)`: the class arrives typed as+ # `type[StuffContent]`, whose declared fields do not include `text` — the subclasses that a+ # Text-compatible concept resolves to are what carry it. Validation, and the `ValidationError`+ # a mismatch raises, are identical either way.+ content = output_class.model_validate({"text": generated_text})+ return LlmTextResult(+ memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),+ text=generated_text,+ rendered_prompt=llm_prompt,+ llm_setting=llm_setting,+ structuring_path=StructuringPath.TEXT,+ )async def run_llm_object(@@ -242,31 +244,32 @@ async def run_llm_object(same prompt by default — a prompt supplied only from outside would have left the derivation ateach caller and let the two defaults fork."""- output_structure_prompt = (- structure_prompt- if structure_prompt is not None- else await derive_structure_prompt(output_class=output_class, templating_style=templating_style)- )- llm_prompt = await assemble_llm_prompt(- prompt_content=prompt_content,- context_provider=memory,- output_structure_prompt=output_structure_prompt,- extra_params=extra_params,- templating_style=templating_style,- )- content = await generate_object_content(- job_metadata=job_metadata,- cogt_run_params=cogt_run_params,- llm_prompt=llm_prompt,- llm_setting=llm_setting,- output_class=output_class,- is_multiple_output=is_multiple_output,- fixed_nb_output=fixed_nb_output,- )- return LlmObjectResult(- memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),- content=content,- rendered_prompt=llm_prompt,- llm_setting=llm_setting,- structuring_path=StructuringPath.OBJECT_LIST if is_multiple_output else StructuringPath.OBJECT_DIRECT,- )+ with job_metadata.log_context():+ output_structure_prompt = (+ structure_prompt+ if structure_prompt is not None+ else await derive_structure_prompt(output_class=output_class, templating_style=templating_style)+ )+ llm_prompt = await assemble_llm_prompt(+ prompt_content=prompt_content,+ context_provider=memory,+ output_structure_prompt=output_structure_prompt,+ extra_params=extra_params,+ templating_style=templating_style,+ )+ content = await generate_object_content(+ job_metadata=job_metadata,+ cogt_run_params=cogt_run_params,+ llm_prompt=llm_prompt,+ llm_setting=llm_setting,+ output_class=output_class,+ is_multiple_output=is_multiple_output,+ fixed_nb_output=fixed_nb_output,+ )+ return LlmObjectResult(+ memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),+ content=content,+ rendered_prompt=llm_prompt,+ llm_setting=llm_setting,+ structuring_path=StructuringPath.OBJECT_LIST if is_multiple_output else StructuringPath.OBJECT_DIRECT,+ )diff --git a/pipelex/kernel/pipelex_kernel.py b/pipelex/kernel/pipelex_kernel.pyindex 70d0cca4c..355a6e1b1 100644--- a/pipelex/kernel/pipelex_kernel.py+++ b/pipelex/kernel/pipelex_kernel.py@@ -30,9 +30,15 @@ reading the events back and clearing the registration stay the caller's, and thewhat stands between a kernel run and the interpreter's cost reporting. ``pipelex/tracing/`` holdsboth halves a caller needs (``make_event_log``, ``UsageAggregator``) and is kernel-layer, so none ofthis costs the boot contract. See ``docs/under-the-hood/pipelex-kernel.md``.++**The log context splits the same way.** Each kernel function that takes a ``job_metadata`` binds+it for the length of its call, so a step's lines name the run and the step. The run-level binding,+which covers the lines a host emits between steps, is the caller's for the same reason as above:+the host wraps its run in :meth:`PipelexKernel.log_context`."""from collections.abc import Callable+from contextlib import AbstractContextManagerfrom typing import Any, Selffrom uuid import uuid4@@ -57,6 +63,7 @@ from pipelex.runtime_hub import resolve_run_mode_for_bootfrom pipelex.system.job_metadata import JobMetadata, RunMetadatafrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.system.trace_context import TraceContext+from pipelex.tools.log.log_context import LogContextfrom pipelex.tools.templating.templating_style import TemplatingStyle@@ -86,6 +93,8 @@ class PipelexKernel:run_mode: PipeRunMode = PipeRunMode.LIVE,user_id: str,storage_scope: str,+ request_id: str | None = None,+ pipeline_run_id: str | None = None,extras: dict[str, str] | None = None,is_mock_usage: bool = False,trace_context: TraceContext | None = None,@@ -102,6 +111,11 @@ class PipelexKernel:so an illegal LIVE request must fail loud on every boot rather than be silently legalised bya keyless process forcing it to DRY.+ ``request_id`` is the inbound request this run serves, the identifier a hosted deployment+ filters its logs on. It rides the run metadata beside ``user_id``, reaches every step's+ metadata and the log context each step binds, and is validated by ``RunMetadata`` exactly as+ on the pipeline entry points.+``trace_context`` is what makes cost/usage reporting reach parity with an interpreter run:the cogt leaf emits a usage event only when the metadata it is handed carries one. Passing itadopts its ``graph_id`` as this run's ``pipeline_run_id`` rather than minting a fresh id —@@ -109,6 +123,18 @@ class PipelexKernel:across two ids (the registered-context emit path stamps the event log's id, the runnerfallback stamps the metadata's), so the read-back would silently miss half of them.+ ``pipeline_run_id`` names the run when no trace context does. The run id is a trace+ context's ``graph_id`` when one is given, else this value, else a fresh ``uuid4``. A trace+ context and a ``pipeline_run_id`` that disagree raise ``ValueError``, since neither could+ win without splitting the run's identity; equal ones are accepted. An empty+ ``pipeline_run_id`` raises ``ValueError`` too, rather than silently minting an id a+ replaying host did not ask for. **A host inside a+ replay-based executor must pass one of the two**: the ``uuid4`` default takes a different+ value every time the host re-executes the code, so a replayed run would name itself+ differently from the run it replays. Such a host mints the id from its own replay-safe+ source and passes the value; unlike a step id, it is minted once per run, so a value is+ enough where ``step_id_source`` needs a callable.+``extras`` is the opaque, host-supplied mapping of labels about this run, carried beside``user_id`` and ``storage_scope``. This tier is the direct programmatic entrypoint, so a multi-tenant host embedding the kernel needs the same seam the pipeline entry@@ -129,7 +155,8 @@ class PipelexKernel:run_metadata=RunMetadata(user_id=user_id,storage_scope=storage_scope,- pipeline_run_id=trace_context.graph_id if trace_context is not None else str(uuid4()),+ pipeline_run_id=cls._resolve_pipeline_run_id(trace_context=trace_context, pipeline_run_id=pipeline_run_id),+ request_id=request_id,extras=extras or {},),trace_context=trace_context,@@ -138,6 +165,33 @@ class PipelexKernel:step_id_source=step_id_source,)+ @classmethod+ def _resolve_pipeline_run_id(cls, *, trace_context: TraceContext | None, pipeline_run_id: str | None) -> str:+ """The run's id: the trace context's ``graph_id``, else the caller's ``pipeline_run_id``, else a fresh ``uuid4``."""+ if pipeline_run_id == "":+ msg = "PipelexKernel.make was given an empty pipeline_run_id: pass the run's id, or None to have one minted."+ raise ValueError(msg)+ if trace_context is None:+ return pipeline_run_id if pipeline_run_id is not None else str(uuid4())+ if pipeline_run_id is not None and pipeline_run_id != trace_context.graph_id:+ msg = (+ f"PipelexKernel.make was given a trace context for run '{trace_context.graph_id}' and a pipeline_run_id "+ f"'{pipeline_run_id}': they name one run, so they must agree. Pass one of them, or the same id twice."+ )+ raise ValueError(msg)+ return trace_context.graph_id++ def log_context(self) -> AbstractContextManager[LogContext]:+ """Bind this run's ``request_id`` and ``pipeline_run_id`` onto every record emitted inside the block.++ **The host wraps its run in it**, because the kernel has no run boundary of its own to hang a+ binding on — the same reason it leaves the usage and trace lifecycle to the caller. It binds+ the run and no step: the run-level metadata carries no ``pipe_run_id``, and each kernel step+ function binds its own step's over this one for the length of the call, so a line emitted+ between two calls names the run and a line emitted during one names the step as well.+ """+ return self.job_metadata.log_context()+def make_step_metadata(self, *, pipe_code: str | None = None) -> JobMetadata:"""A per-step copy of the run-level metadata, carrying its own ``pipe_run_id``.diff --git a/pipelex/kernel/search_ops.py b/pipelex/kernel/search_ops.pyindex ed0a8c795..f9c1dc09d 100644--- a/pipelex/kernel/search_ops.py+++ b/pipelex/kernel/search_ops.py@@ -84,34 +84,35 @@ async def run_search(it replay-safe under a distributed orchestrator and lets its failures cross a workflow boundary asclassified errors instead of hanging."""- query_text = await render_template(- template=template,- category=category,- context=memory.generate_context(),- templating_style=templating_style,- )- search_assignment = SearchAssignment(- job_metadata=job_metadata,- cogt_run_params=cogt_run_params,- query=query_text,- search_setting=search_setting,- include_domains=include_domains,- exclude_domains=exclude_domains,- from_date=from_date,- to_date=to_date,- )- content_generator = get_content_generator()- content: StuffContent- if output_structure_class is None:- content = await content_generator.make_search_sourced_answer(search_assignment=search_assignment)- else:- content = await content_generator.make_search_structured(- output_structure_class=output_structure_class,- search_assignment=search_assignment,+ with job_metadata.log_context():+ query_text = await render_template(+ template=template,+ category=category,+ context=memory.generate_context(),+ templating_style=templating_style,+ )+ search_assignment = SearchAssignment(+ job_metadata=job_metadata,+ cogt_run_params=cogt_run_params,+ query=query_text,+ search_setting=search_setting,+ include_domains=include_domains,+ exclude_domains=exclude_domains,+ from_date=from_date,+ to_date=to_date,+ )+ content_generator = get_content_generator()+ content: StuffContent+ if output_structure_class is None:+ content = await content_generator.make_search_sourced_answer(search_assignment=search_assignment)+ else:+ content = await content_generator.make_search_structured(+ output_structure_class=output_structure_class,+ search_assignment=search_assignment,+ )+ return SearchResult(+ memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),+ content=content,+ rendered_query=query_text,+ search_setting=search_setting,)- return SearchResult(- memory=store_result(memory=memory, concept=concept, content=content, result_name=result_name, result_code=result_code),- content=content,- rendered_query=query_text,- search_setting=search_setting,- )diff --git a/pipelex/pipe_run/pipe_run.py b/pipelex/pipe_run/pipe_run.pyindex c202599e7..ebeae84c0 100644--- a/pipelex/pipe_run/pipe_run.py+++ b/pipelex/pipe_run/pipe_run.py@@ -35,15 +35,9 @@ class PipeRun(PipeRunProtocol):*,delivery_assignment: DeliveryAssignment | None = None,) -> PipeOutput:- job_metadata = pipe_job.job_metadata- pipeline_run_id: str = job_metadata.run_metadata.pipeline_run_id# The run's identifiers ride the payload; here is where a direct-mode run binds them onto every# record it emits, the delivery's included. The binding is released when the run returns.- with log.context(- request_id=job_metadata.run_metadata.request_id,- pipeline_run_id=pipeline_run_id,- pipe_run_id=job_metadata.pipe_run_id,- ):+ with pipe_job.job_metadata.log_context():return await self._run_bound(pipe_job=pipe_job, delivery_assignment=delivery_assignment)async def _run_bound(diff --git a/pipelex/system/job_metadata.py b/pipelex/system/job_metadata.pyindex 32678c372..5e3942dbc 100644--- a/pipelex/system/job_metadata.py+++ b/pipelex/system/job_metadata.py@@ -1,3 +1,4 @@+from contextlib import AbstractContextManagerfrom datetime import datetimefrom enum import StrEnumfrom typing import Any@@ -8,6 +9,7 @@ from pipelex.system.run_extras import validate_run_extrasfrom pipelex.system.storage_scope import validate_storage_scopefrom pipelex.system.telemetry.otel_context import OtelContextfrom pipelex.system.trace_context import TraceContext+from pipelex.tools.log.log_context import LogContext, bind_log_contextclass SpecialPipelineId(StrEnum):@@ -208,6 +210,22 @@ class JobMetadata(BaseModel):return (self.completed_at - self.started_at).total_seconds()return None+ def log_context(self) -> AbstractContextManager[LogContext]:+ """Bind this job's identifiers onto every record emitted inside the block.++ The one spelling of the binding: ``request_id`` and ``pipeline_run_id`` from the run half,+ ``pipe_run_id`` from the job half. It merges over whatever is already bound, so an identifier+ this metadata does not carry (a submission's ``pipe_run_id``, a run with no ``request_id``)+ inherits the enclosing binding rather than clearing it, and the previous binding comes back+ when the block exits. ``PipeRun.run`` binds a direct-mode run through it, and every kernel+ function that takes a ``job_metadata`` binds its step through it.+ """+ return bind_log_context(+ request_id=self.run_metadata.request_id,+ pipeline_run_id=self.run_metadata.pipeline_run_id,+ pipe_run_id=self.pipe_run_id,+ )+def copy_with_update(self,*,diff --git a/tests/unit/pipelex/kernel/test_kernel_binds_job_metadata.py b/tests/unit/pipelex/kernel/test_kernel_binds_job_metadata.pynew file mode 100644index 000000000..cc01bef79--- /dev/null+++ b/tests/unit/pipelex/kernel/test_kernel_binds_job_metadata.py@@ -0,0 +1,96 @@+"""A kernel function that takes a ``job_metadata`` opens its body by binding it onto the log context.++The rule is stated by signature rather than as a list of functions, so that it covers the next function+added as well as the ones written today: every module-level function in ``pipelex/kernel/`` with a+``job_metadata`` parameter must open its body — after its docstring — with+``with job_metadata.log_context():``. Opening the body is what makes the binding cover the whole step,+prompt assembly and write-back included, and not only the generation call in the middle.++The kernel's doctrine records that five ops were once added with every gate green and none of them+covered; this sweep is what keeps a sixth from arriving without its binding. The behaviour the rule+buys is tested in ``test_kernel_log_context.py``; this test only makes the rule impossible to forget.+"""++import ast+from pathlib import Path++import pipelex.kernel++KERNEL_DIR = Path(pipelex.kernel.__file__).parent++JOB_METADATA_PARAMETER = "job_metadata"+++def _is_the_binding_call(expression: ast.expr) -> bool:+ """Whether ``expression`` is exactly ``job_metadata.log_context()``."""+ if not isinstance(expression, ast.Call) or expression.args or expression.keywords:+ return False+ method = expression.func+ if not isinstance(method, ast.Attribute) or method.attr != "log_context":+ return False+ return isinstance(method.value, ast.Name) and method.value.id == JOB_METADATA_PARAMETER+++def _opens_with_the_binding(function: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:+ """Whether the body's first statement, past a docstring, is ``with job_metadata.log_context():``."""+ body = function.body+ if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str):+ body = body[1:]+ if not body or not isinstance(body[0], ast.With):+ return False+ return any(_is_the_binding_call(item.context_expr) for item in body[0].items)+++def unbound_functions(*, source: str) -> list[str]:+ """The module-level functions in ``source`` that take a ``job_metadata`` and do not open by binding it."""+ offenders: list[str] = []+ for node in ast.parse(source).body:+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ continue+ arguments = node.args+ parameter_names = {argument.arg for argument in (*arguments.posonlyargs, *arguments.args, *arguments.kwonlyargs)}+ if JOB_METADATA_PARAMETER in parameter_names and not _opens_with_the_binding(node):+ offenders.append(node.name)+ return offenders+++class TestKernelBindsJobMetadata:+ def test_every_kernel_function_taking_job_metadata_opens_by_binding_it(self) -> None:+ offenders = [+ f"{module_path.name}::{function_name}"+ for module_path in sorted(KERNEL_DIR.glob("*.py"))+ for function_name in unbound_functions(source=module_path.read_text(encoding="utf-8"))+ ]++ assert not offenders, (+ f"these kernel functions take a `job_metadata` but do not open their body with "+ f"`with job_metadata.log_context():`: {offenders}. A program driving the kernel has no interpreter "+ "to bind the run and the step for it, so a kernel step that does not bind them emits lines naming "+ "neither. See docs/under-the-hood/pipelex-kernel.md, 'The log context'."+ )++ def test_the_sweep_sees_a_function_that_does_not_bind(self) -> None:+ """The control: without it, a predicate that matched nothing would leave the real case green forever."""+ source = '''+async def binds(*, job_metadata):+ """Docstring."""+ with job_metadata.log_context():+ return 1++async def forgets(*, job_metadata):+ return 1++async def binds_too_late(*, job_metadata):+ value = 1+ with job_metadata.log_context():+ return value++async def binds_something_else(*, job_metadata, other):+ with other.log_context():+ return 1++def takes_no_job_metadata(*, memory):+ return memory+'''++ assert unbound_functions(source=source) == ["forgets", "binds_too_late", "binds_something_else"]diff --git a/tests/unit/pipelex/kernel/test_kernel_boot_contract.py b/tests/unit/pipelex/kernel/test_kernel_boot_contract.pyindex 4f440b21a..b9e95adee 100644--- a/tests/unit/pipelex/kernel/test_kernel_boot_contract.py+++ b/tests/unit/pipelex/kernel/test_kernel_boot_contract.py@@ -118,6 +118,7 @@ _KERNEL_CALL_SCRIPT = textwrap.dedent(from pipelex.system.registries.func_registry import func_registryfrom pipelex.system.runtime import IntegrationModefrom pipelex.tools.jinja2.template_category import TemplateCategory+ from pipelex.tools.log.log_context import get_log_contextinterpreter_packages = frozenset(sys.argv[1:])# An empty set would make the sweep flag nothing and the test pass vacuously — the same guard both@@ -243,14 +244,21 @@ _KERNEL_CALL_SCRIPT = textwrap.dedent(if not isinstance(extracted_item, NumberContent):fail(f"a list extraction helper yielded a {type(extracted_item).__name__}, not the NumberContent it was asked for")- text_result = asyncio.run(- kernel.llm_text(- memory=WorkingMemoryFactory.make_empty(),- model=model,- user="Say something.",- result="reply",+ # The host's run-level log binding, entered the way a host enters it: around its kernel calls.+ # It binds the run and no step, and releases the binding on exit.+ with kernel.log_context() as run_binding:+ if run_binding.pipeline_run_id != kernel.job_metadata.run_metadata.pipeline_run_id or run_binding.pipe_run_id is not None:+ fail(f"kernel.log_context() bound {run_binding!r}, not the run's own id with no step")+ text_result = asyncio.run(+ kernel.llm_text(+ memory=WorkingMemoryFactory.make_empty(),+ model=model,+ user="Say something.",+ result="reply",+ ))- )+ if get_log_context() is not None:+ fail("kernel.log_context() did not release its binding on exit")if not isinstance(text_result, LlmTextResult):fail(f"llm_text returned {type(text_result).__name__}, not an LlmTextResult")diff --git a/tests/unit/pipelex/kernel/test_kernel_log_context.py b/tests/unit/pipelex/kernel/test_kernel_log_context.pynew file mode 100644index 000000000..5e8e50614--- /dev/null+++ b/tests/unit/pipelex/kernel/test_kernel_log_context.py@@ -0,0 +1,218 @@+"""Every kernel step function binds the metadata it is handed onto the log context, for its whole body.++A program driving the kernel directly has no interpreter around it, so nothing else binds the run and+the step: without this, the lines a kernel step emits name neither. The assertion is taken from+*inside* the call — a probe standing in for the content generator records the context bound when the+function reaches it — rather than by counting the lines a run emits, because a DRY run is nearly+silent and would prove nothing either way.++The metadata comes from the façade, as a host builds it: a run-level ``PipelexKernel.make`` carrying a+``request_id``, and a per-step copy from ``make_step_metadata``. Nothing is bound before the call, so+every identifier the probe sees was bound by the function itself, and nothing is bound after it.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++import pytest++from pipelex.cogt.extract.extract_input import ExtractInput+from pipelex.cogt.extract.extract_setting import ExtractSetting+from pipelex.cogt.img_gen.img_gen_prompt import ImgGenPrompt+from pipelex.cogt.img_gen.img_gen_setting import ImgGenSetting+from pipelex.cogt.llm.llm_prompt import LLMPrompt+from pipelex.cogt.llm.llm_setting import LLMSetting+from pipelex.cogt.search.search_setting import SearchSetting+from pipelex.core.concepts.concept_factory import ConceptFactory+from pipelex.core.concepts.native.concept_native import NativeConceptCode+from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.core.stuffs.image_content import ImageContent+from pipelex.core.stuffs.number_content import NumberContent+from pipelex.core.stuffs.search_result_content import SearchResultContent+from pipelex.core.stuffs.text_content import TextContent+from pipelex.kernel.extract_ops import build_extract_job_params, run_extract+from pipelex.kernel.img_gen_ops import build_img_gen_job_params, run_img_gen+from pipelex.kernel.llm_ops import generate_object_content, run_llm_object, run_llm_text+from pipelex.kernel.llm_prompt_content import LlmPromptContent+from pipelex.kernel.pipelex_kernel import PipelexKernel+from pipelex.kernel.search_ops import run_search+from pipelex.kernel.templating_style_ops import resolve_templating_style+from pipelex.system.pipe_run_mode import PipeRunMode+from pipelex.tools.jinja2.template_category import TemplateCategory+from pipelex.tools.log.log_context import LogContext, get_log_context++if TYPE_CHECKING:+ from pytest_mock import MockerFixture++ from pipelex.system.job_metadata import JobMetadata++REQUEST_ID = "req-kernel-step"++#: Named but never resolved: the probe replaces the content generator, so no worker is looked up.+LLM_SETTING = LLMSetting(model="kernel-log-context-model", temperature=0.5)+++class ContentGeneratorProbe:+ """Stands in for the content generator and records the log context bound when a kernel function reaches it."""++ def __init__(self) -> None:+ self.seen: list[LogContext | None] = []++ def _record(self) -> None:+ self.seen.append(get_log_context())++ async def make_llm_text(self, **kwargs: Any) -> str: # ruff: ignore[unused-method-argument]+ self._record()+ return "generated text"++ async def make_object(self, **kwargs: Any) -> NumberContent: # ruff: ignore[unused-method-argument]+ self._record()+ return NumberContent(number=7)++ async def make_object_list(self, **kwargs: Any) -> list[NumberContent]: # ruff: ignore[unused-method-argument]+ self._record()+ return [NumberContent(number=7), NumberContent(number=8)]++ async def make_extract_pages(self, **kwargs: Any) -> list[Any]: # ruff: ignore[unused-method-argument]+ self._record()+ return []++ async def make_search_sourced_answer(self, **kwargs: Any) -> SearchResultContent: # ruff: ignore[unused-method-argument]+ self._record()+ return SearchResultContent(answer="found")++ async def make_single_image(self, **kwargs: Any) -> ImageContent: # ruff: ignore[unused-method-argument]+ self._record()+ return ImageContent(url="https://example.com/kernel-log-context.png")+++def _install_probe(mocker: MockerFixture, *, ops_module: str) -> ContentGeneratorProbe:+ """Replace the content generator where the kernel ops module under test reads it."""+ probe = ContentGeneratorProbe()+ mocker.patch(f"pipelex.kernel.{ops_module}.get_content_generator", return_value=probe)+ return probe+++def _kernel_and_step() -> tuple[PipelexKernel, JobMetadata]:+ kernel = PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="kernel-log-context", request_id=REQUEST_ID)+ return kernel, kernel.make_step_metadata()+++def _assert_the_step_was_bound(*, probe: ContentGeneratorProbe, step: JobMetadata) -> None:+ assert step.pipe_run_id is not None+ assert probe.seen == [+ LogContext(request_id=REQUEST_ID, pipeline_run_id=step.run_metadata.pipeline_run_id, pipe_run_id=step.pipe_run_id),+ ], "a kernel step function must bind the metadata it is handed — the run's two identifiers and the step's own"+ assert get_log_context() is None, "the binding must be released when the step returns"++[email protected](loop_scope="class")+class TestKernelLogContext:+ async def test_run_llm_text_binds_its_step(self, mocker: MockerFixture) -> None:+ probe = _install_probe(mocker, ops_module="llm_ops")+ kernel, step = _kernel_and_step()++ await run_llm_text(+ memory=WorkingMemoryFactory.make_empty(),+ prompt_content=LlmPromptContent.make_from_text(user="Say something."),+ llm_setting=LLM_SETTING,+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.TEXT),+ output_class=TextContent,+ job_metadata=step,+ cogt_run_params=kernel.cogt_run_params,+ templating_style=resolve_templating_style(authored=None),+ result_name="reply",+ )++ _assert_the_step_was_bound(probe=probe, step=step)++ async def test_run_llm_object_binds_its_step(self, mocker: MockerFixture) -> None:+ probe = _install_probe(mocker, ops_module="llm_ops")+ kernel, step = _kernel_and_step()++ await run_llm_object(+ memory=WorkingMemoryFactory.make_empty(),+ prompt_content=LlmPromptContent.make_from_text(user="Pick a number."),+ llm_setting=LLM_SETTING,+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.NUMBER),+ output_class=NumberContent,+ job_metadata=step,+ cogt_run_params=kernel.cogt_run_params,+ templating_style=resolve_templating_style(authored=None),+ result_name="answer",+ )++ _assert_the_step_was_bound(probe=probe, step=step)++ @pytest.mark.parametrize("is_multiple_output", [False, True])+ async def test_generate_object_content_binds_its_step(self, mocker: MockerFixture, is_multiple_output: bool) -> None:+ """A documented entry point of its own, which `PipeStructure` calls directly, so it binds too."""+ probe = _install_probe(mocker, ops_module="llm_ops")+ kernel, step = _kernel_and_step()++ await generate_object_content(+ job_metadata=step,+ cogt_run_params=kernel.cogt_run_params,+ llm_prompt=LLMPrompt(user_text="Pick a number."),+ llm_setting=LLM_SETTING,+ output_class=NumberContent,+ is_multiple_output=is_multiple_output,+ )++ _assert_the_step_was_bound(probe=probe, step=step)++ async def test_run_extract_binds_its_step(self, mocker: MockerFixture) -> None:+ probe = _install_probe(mocker, ops_module="extract_ops")+ kernel, step = _kernel_and_step()+ extract_setting = ExtractSetting(model="kernel-log-context-extract-model")++ await run_extract(+ memory=WorkingMemoryFactory.make_empty(),+ extract_input=ExtractInput(document_uri="https://example.com/kernel-log-context.pdf"),+ extract_setting=extract_setting,+ extract_job_params=build_extract_job_params(extract_setting=extract_setting),+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.PAGE),+ job_metadata=step,+ cogt_run_params=kernel.cogt_run_params,+ result_name="pages",+ )++ _assert_the_step_was_bound(probe=probe, step=step)++ async def test_run_search_binds_its_step(self, mocker: MockerFixture) -> None:+ probe = _install_probe(mocker, ops_module="search_ops")+ kernel, step = _kernel_and_step()++ await run_search(+ memory=WorkingMemoryFactory.make_empty(),+ template="What binds the log context?",+ category=TemplateCategory.LLM_PROMPT,+ search_setting=SearchSetting(model="kernel-log-context-search-model"),+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.TEXT),+ job_metadata=step,+ cogt_run_params=kernel.cogt_run_params,+ templating_style=resolve_templating_style(authored=None),+ result_name="findings",+ )++ _assert_the_step_was_bound(probe=probe, step=step)++ async def test_run_img_gen_binds_its_step(self, mocker: MockerFixture) -> None:+ probe = _install_probe(mocker, ops_module="img_gen_ops")+ kernel, step = _kernel_and_step()+ img_gen_setting = ImgGenSetting(model="kernel-log-context-img-gen-model")++ await run_img_gen(+ memory=WorkingMemoryFactory.make_empty(),+ img_gen_prompt=ImgGenPrompt(positive_text="Draw the log context."),+ img_gen_setting=img_gen_setting,+ img_gen_job_params=build_img_gen_job_params(img_gen_setting=img_gen_setting),+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.IMAGE),+ output_class=ImageContent,+ job_metadata=step,+ cogt_run_params=kernel.cogt_run_params,+ result_name="picture",+ )++ _assert_the_step_was_bound(probe=probe, step=step)diff --git a/tests/unit/pipelex/kernel/test_pipelex_kernel_run_state.py b/tests/unit/pipelex/kernel/test_pipelex_kernel_run_state.pyindex b8f87c1a4..5e403c84d 100644--- a/tests/unit/pipelex/kernel/test_pipelex_kernel_run_state.py+++ b/tests/unit/pipelex/kernel/test_pipelex_kernel_run_state.py@@ -5,10 +5,15 @@ interpreter run's. These pin the links, because a parity failure there says "nosaying which link dropped: the run-level metadata, the per-step copy, or the run mode."""+from __future__ import annotations++from typing import TYPE_CHECKINGfrom uuid import UUIDimport pytest+from pydantic import ValidationError+from pipelex.cogt.llm.llm_setting import LLMSettingfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactory@@ -26,6 +31,10 @@ from pipelex.kernel.pipelex_kernel import PipelexKernelfrom pipelex.system.data_inclusion_config import DataInclusionConfigfrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.system.trace_context import TraceContext+from pipelex.tools.log.log_context import LogContext, get_log_context++if TYPE_CHECKING:+ from pytest_mock import MockerFixture_GRAPH_ID = "kernel-run-state"@@ -66,6 +75,106 @@ class TestPipelexKernelRunState:assert first.job_metadata.trace_context is Noneassert first.job_metadata.run_metadata.pipeline_run_id != second.job_metadata.run_metadata.pipeline_run_id+ def test_a_request_id_rides_the_run_metadata(self) -> None:+ """The field a hosted deployment filters its logs on, carried like `user_id` and `storage_scope`."""+ kernel = PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user", request_id="req-kernel")++ assert kernel.job_metadata.run_metadata.request_id == "req-kernel"+ assert kernel.make_step_metadata().run_metadata.request_id == "req-kernel"++ def test_a_malformed_request_id_is_refused_by_the_run_metadata(self) -> None:+ """The validation is `RunMetadata`'s own, so `make` refuses exactly what the pipeline entry points refuse."""+ with pytest.raises(ValidationError):+ PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user", request_id="forged\nline")++ def test_a_supplied_pipeline_run_id_becomes_the_runs_identity(self) -> None:+ """A host inside a replay-based executor mints the id from its own replay-safe source and hands it over."""+ kernel = PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user", pipeline_run_id="plr-host")++ assert kernel.job_metadata.run_metadata.pipeline_run_id == "plr-host"+ assert kernel.job_metadata.trace_context is None++ def test_a_trace_context_and_an_equal_pipeline_run_id_are_one_identity(self) -> None:+ kernel = PipelexKernel.make(+ storage_scope="test/scope",+ run_mode=PipeRunMode.DRY,+ user_id="test-user",+ trace_context=_trace_context(),+ pipeline_run_id=_GRAPH_ID,+ )++ assert kernel.job_metadata.run_metadata.pipeline_run_id == _GRAPH_ID++ def test_a_trace_context_and_a_different_pipeline_run_id_are_refused(self) -> None:+ """Neither silently wins: letting the two diverge would scatter the run's usage events across two ids."""+ with pytest.raises(ValueError, match="plr-elsewhere"):+ PipelexKernel.make(+ storage_scope="test/scope",+ run_mode=PipeRunMode.DRY,+ user_id="test-user",+ trace_context=_trace_context(),+ pipeline_run_id="plr-elsewhere",+ )++ def test_an_empty_pipeline_run_id_is_refused(self) -> None:+ """An empty id is a caller's bug, and minting one in its place would hide it from a replaying host."""+ with pytest.raises(ValueError, match="empty pipeline_run_id"):+ PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user", pipeline_run_id="")++ def test_with_neither_the_run_id_is_a_fresh_uuid4(self) -> None:+ kernel = PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user")++ assert UUID(kernel.job_metadata.run_metadata.pipeline_run_id).version == 4++ def test_the_run_level_log_context_binds_the_run_and_no_step(self) -> None:+ """The host's binding: the run's two identifiers, and no `pipe_run_id`, which each step binds for itself."""+ kernel = PipelexKernel.make(+ storage_scope="test/scope",+ run_mode=PipeRunMode.DRY,+ user_id="test-user",+ request_id="req-kernel",+ pipeline_run_id="plr-kernel",+ )++ assert get_log_context() is None+ with kernel.log_context() as bound:+ assert bound == LogContext(request_id="req-kernel", pipeline_run_id="plr-kernel")+ assert get_log_context() == bound+ assert get_log_context() is None++ @pytest.mark.asyncio+ async def test_a_facade_call_inside_the_run_level_binding_binds_its_step_over_it(self, mocker: MockerFixture) -> None:+ """The two layers together, as a host uses them: the run bound by the host, the step by the kernel."""+ seen: list[LogContext | None] = []++ async def make_llm_text(**kwargs: object) -> str: # ruff: ignore[unused-function-argument, unused-async]+ seen.append(get_log_context())+ return "generated text"++ content_generator = mocker.MagicMock()+ content_generator.make_llm_text = make_llm_text+ mocker.patch("pipelex.kernel.llm_ops.get_content_generator", return_value=content_generator)+ step_ids = iter(["step-0"])+ kernel = PipelexKernel.make(+ storage_scope="test/scope",+ run_mode=PipeRunMode.DRY,+ user_id="test-user",+ request_id="req-kernel",+ pipeline_run_id="plr-kernel",+ step_id_source=lambda: next(step_ids),+ )++ with kernel.log_context():+ await kernel.llm_text(+ memory=WorkingMemoryFactory.make_empty(),+ model=LLMSetting(model="kernel-run-state-model", temperature=0.5),+ user="Say something.",+ result="reply",+ )+ assert get_log_context() == LogContext(request_id="req-kernel", pipeline_run_id="plr-kernel")++ assert seen == [LogContext(request_id="req-kernel", pipeline_run_id="plr-kernel", pipe_run_id="step-0")]+def test_each_step_inherits_the_trace_context_and_carries_its_own_run_id(self) -> None:"""The per-step copy: same trace context (so every step attributes to it), distinct pipe_run_id."""kernel = PipelexKernel.make(storage_scope="test/scope", run_mode=PipeRunMode.DRY, user_id="test-user", trace_context=_trace_context())diff --git a/tests/unit/pipelex/pipe_operators/pipe_llm/test_pipe_llm_log_context.py b/tests/unit/pipelex/pipe_operators/pipe_llm/test_pipe_llm_log_context.pynew file mode 100644index 000000000..d75e69524--- /dev/null+++ b/tests/unit/pipelex/pipe_operators/pipe_llm/test_pipe_llm_log_context.py@@ -0,0 +1,111 @@+"""An interpreted pipe's log lines are unchanged by the kernel binding its own step.++Every kernel function that takes a ``job_metadata`` binds it (``test_kernel_log_context.py``). Inside+the interpreter that binding nests within the one ``live_run_pipe`` opened, so it must be a no-op: the+operator has to hand the kernel metadata carrying the very ``pipe_run_id`` that ``live_run_pipe``+minted and bound. This pins that equality on ``PipeLLM``, so that if it ever hands the kernel a copy+with an id of its own, it goes red here instead of silently re-attributing its lines to a step nobody+announced. The other kernel-backed operators hand down their metadata the same way and are not pinned+here.++The pipe runs in LIVE through ``live_run_pipe`` itself. Two observers sit on the path: a spy on the+operator's call into ``run_llm_text``, which records the metadata the operator hands down and the+binding around the call, and a probe standing in for the content generator, which records the binding+the kernel leaves in place when it reaches the generation. The probe answers the generation, so+nothing reaches a provider.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any, Callable++import pytest++from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.kernel import llm_ops+from pipelex.pipe_machinery.pipe_factory import PipeFactory+from pipelex.pipe_operators.llm.pipe_llm import PipeLLM+from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.pipeline.pipeline_factory import PipelineFactory+from pipelex.system.job_metadata import JobMetadata, RunMetadata+from pipelex.system.pipe_run_mode import PipeRunMode+from pipelex.tools.log.log_context import LogContext, get_log_context++if TYPE_CHECKING:+ from pytest_mock import MockerFixture++ from pipelex.kernel.llm_results import LlmTextResult++MINTED_PIPE_RUN_ID = "pr-minted-by-live-run-pipe"+PIPELINE_RUN_ID = "plr-interpreted"+REQUEST_ID = "req-interpreted"+++class ContentGeneratorProbe:+ """Answers the text generation and records the log context bound when the kernel reaches it."""++ def __init__(self) -> None:+ self.seen: list[LogContext | None] = []++ async def make_llm_text(self, **kwargs: Any) -> str: # ruff: ignore[unused-method-argument]+ self.seen.append(get_log_context())+ return "generated text"+++class KernelCallSpy:+ """Wraps the operator's call into ``run_llm_text``: records what it was handed and what was bound, then delegates."""++ def __init__(self) -> None:+ self.handed_pipe_run_ids: list[str | None] = []+ self.bound: list[LogContext | None] = []++ async def __call__(self, **kwargs: Any) -> LlmTextResult:+ job_metadata: JobMetadata = kwargs["job_metadata"]+ self.handed_pipe_run_ids.append(job_metadata.pipe_run_id)+ self.bound.append(get_log_context())+ return await llm_ops.run_llm_text(**kwargs)+++def _make_pipe() -> PipeLLM:+ blueprint = PipeLLMBlueprint(+ description="log-context test pipe",+ output="native.Text",+ prompt="Say something.",+ )+ return PipeFactory[PipeLLM].make_from_blueprint(domain_code="test_log_context", pipe_code="say_something", blueprint=blueprint)++[email protected](loop_scope="class")+class TestPipeLLMLogContext:+ async def test_the_kernel_is_handed_and_binds_the_id_live_run_pipe_minted(+ self,+ mocker: MockerFixture,+ load_empty_library: Callable[[], str],+ ) -> None:+ load_empty_library()+ mocker.patch.object(PipelineFactory, "make_pipe_run_id", return_value=MINTED_PIPE_RUN_ID)+ probe = ContentGeneratorProbe()+ mocker.patch.object(llm_ops, "get_content_generator", return_value=probe)+ spy = KernelCallSpy()+ mocker.patch("pipelex.pipe_operators.llm.pipe_llm.run_llm_text", new=spy)+ job_metadata = JobMetadata(+ run_metadata=RunMetadata(user_id="pytest", storage_scope="test/scope", pipeline_run_id=PIPELINE_RUN_ID, request_id=REQUEST_ID),+ )+ expected = LogContext(request_id=REQUEST_ID, pipeline_run_id=PIPELINE_RUN_ID, pipe_run_id=MINTED_PIPE_RUN_ID)++ # The run-level binding `PipeRun.run` opens around a direct-mode run.+ with job_metadata.log_context():+ await _make_pipe().live_run_pipe(+ job_metadata=job_metadata,+ working_memory=WorkingMemoryFactory.make_empty(),+ pipe_run_params=PipeRunParams(run_mode=PipeRunMode.LIVE, batch_max_concurrency=1, pipe_stack_limit=10),+ )++ assert spy.handed_pipe_run_ids == [MINTED_PIPE_RUN_ID], (+ "the operator must hand the kernel the pipe run id `live_run_pipe` minted — a fresh one would make the "+ "kernel's own binding re-attribute the step's lines to a pipe run nobody announced"+ )+ assert spy.bound == [expected]+ assert probe.seen == [expected], "the kernel's nested binding must leave the interpreter's context exactly as it was"+ assert get_log_context() is Nonediff --git a/tests/unit/pipelex/system/test_job_metadata_log_context.py b/tests/unit/pipelex/system/test_job_metadata_log_context.pynew file mode 100644index 000000000..cc051664d--- /dev/null+++ b/tests/unit/pipelex/system/test_job_metadata_log_context.py@@ -0,0 +1,53 @@+"""``JobMetadata.log_context()`` is the one spelling of "bind this job's identifiers onto the log context".++The run half (``request_id`` and ``pipeline_run_id``) comes from ``run_metadata`` and the step half+(``pipe_run_id``) from the metadata itself. It is a ``bind_log_context`` block like any other: an absent+identifier inherits the outer binding rather than clearing it, and the previous binding comes back when+the block exits, whether it returns or raises.+"""++import pytest++from pipelex import log+from pipelex.system.job_metadata import JobMetadata, RunMetadata+from pipelex.tools.log.log_context import LogContext, get_log_context+++def _job_metadata(*, request_id: str | None = None, pipe_run_id: str | None = None) -> JobMetadata:+ return JobMetadata(+ run_metadata=RunMetadata(user_id="pytest", storage_scope="test/scope", pipeline_run_id="plr-job", request_id=request_id),+ pipe_run_id=pipe_run_id,+ )+++class TestJobMetadataLogContext:+ def test_binds_the_run_identifiers_and_the_step_identifier(self) -> None:+ job_metadata = _job_metadata(request_id="req-job", pipe_run_id="pr-job")++ assert get_log_context() is None+ with job_metadata.log_context() as bound:+ assert bound == LogContext(request_id="req-job", pipeline_run_id="plr-job", pipe_run_id="pr-job")+ assert get_log_context() == bound+ assert get_log_context() is None++ def test_an_absent_identifier_inherits_the_outer_binding(self) -> None:+ """A submission's metadata carries no ``pipe_run_id``: binding it must not erase an enclosing step's."""+ with log.context(request_id="req-outer", pipe_run_id="pr-outer"), _job_metadata().log_context() as bound:+ assert bound == LogContext(request_id="req-outer", pipeline_run_id="plr-job", pipe_run_id="pr-outer")++ def test_the_previous_binding_comes_back_on_return_and_on_raise(self) -> None:+ job_metadata = _job_metadata(request_id="req-job", pipe_run_id="pr-job")+ outer = LogContext(pipeline_run_id="plr-outer", pipe_run_id="pr-outer")++ def explode() -> None:+ msg = "boom"+ raise RuntimeError(msg)++ with log.context(pipeline_run_id="plr-outer", pipe_run_id="pr-outer"):+ with job_metadata.log_context():+ pass+ assert get_log_context() == outer++ with pytest.raises(RuntimeError, match="boom"), job_metadata.log_context():+ explode()+ assert get_log_context() == outer