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.
Guard against rogue outbound headers: unknown per-model backend keys must be header-shaped (#1109)
Louis Choqueld2d6664190d1
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.tomlindex cb91e5b60..4be8d0c7c 100644--- a/.drift/acks/cli-docs.toml+++ b/.drift/acks/cli-docs.toml@@ -1,8 +1,8 @@contract = "cli-docs"-digest = "sha256:91b2f3b364728697c389ea2e1b2bf030a20e841e9d9c7bd176fc16b2faf7f3ee"+digest = "sha256:922bd9bc5dd5f6ef955ffee4b5843331613c69a8849a730b9f13a4f69f1177e3"reviewed_by = "Louis Choquel"-reviewed_at = "2026-08-15T07:04:47Z"-rationale = "pipelex run --dry-run now boots keyless (needs_inference=not dry_run, needs_model_specs=True), matching pipelex-agent run --dry-run. Reviewed docs/tools/cli/run.md and noted on each --dry-run flag row that no inference credentials are needed; agent-CLI CLAUDE.md already describes the keyless dry-run boot and is unaffected by this bare-CLI change."+reviewed_at = "2026-08-15T08:29:38Z"+rationale = "Comment-only change in _run_core.py: reworded the dry-run boot comment so it no longer promises model-handle resolution on a keyless machine (needs_model_specs only keeps real gateway specs; lenient load still skips keyless backends). Reviewed docs/tools/cli/run.md and the agent-CLI CLAUDE.md: neither makes that promise, so no doc change needed."[trigger_files]"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"@@ -109,7 +109,7 @@ rationale = "pipelex run --dry-run now boots keyless (needs_inference=not dry_ru"pipelex/cli/commands/run/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/run/_inputs_file_loader.py" = "blob:dde781f846968b667a0acfb4b3e3cea01cef7049""pipelex/cli/commands/run/_inputs_path_resolver.py" = "blob:c8ec89d98718e18af7aaaded44c9f545be60adab"-"pipelex/cli/commands/run/_run_core.py" = "blob:c2fe39ee9a1c26656847094240d673f3fad6ebd9"+"pipelex/cli/commands/run/_run_core.py" = "blob:bde638fe3075dd9d8ebe6e306f427583904717ec""pipelex/cli/commands/run/app.py" = "blob:a7090b0ff6bf2f1d47827fa27d2a138096a2e148""pipelex/cli/commands/run/bundle_cmd.py" = "blob:cb420bf4879c863d64c5e20ed535c42732b720a2""pipelex/cli/commands/run/exceptions.py" = "blob:e9552226e597922b6ac0757f7b52eb880a2e1472"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 204e8d230..c63283270 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,11 +10,12 @@- **Reasoning budgets are worker-owned**: The thinking-budget lookup is keyed by a family constant on the worker class rather than read from the model spec's `prompting_target`. Behavior is unchanged; the budget maps keep their `anthropic` and `gemini` keys.- **`templating_style` tables reject unknown keys (Breaking)**: `TemplatingStyle` and the rich template table of `PipeCompose` (`[pipe.name.template]`, i.e. `TemplateBlueprint`) are now `extra="forbid"` like every other blueprint. A misspelled optional key — `{ tag_style = "xml", text_formt = "markdown" }`, or `templating_stile` / `extra_contxt` on a template table — used to be dropped silently, yielding a prompt rendered under a shape the author never asked for; it is a validation error now. The MTHDS JSON Schema gains `additionalProperties: false` on both definitions.- **`pipelex run --dry-run` no longer requires credentials**: A dry run makes no inference call, so it now boots keyless (every run forced to DRY) with real model specs — the same boot `pipelex-agent run --dry-run` already used. Until now `pipelex run --dry-run` booted as if for a live run and failed outright on a machine without an API key, while the agent CLI succeeded; the two CLIs now agree. Anyone who relied on `pipelex run --dry-run` as a credentials check should use a live run for that.+- **Unknown per-model backend keys must be header-shaped (Breaking)**: A key in a per-model table of a backend TOML that is not a model-spec field is sent to the provider as an HTTP request header — that mechanism is now documented, and it is gated on shape: the key must contain a hyphen (`x-portkey-provider`, `anthropic-beta`). An unknown key without one (`max_tokns`, or a field deleted from the blueprint) used to go out on the wire silently while the real setting stayed unset; it now fails the backend load, in strict and lenient boots alike, with an error naming the key, the model and the file. A hyphenated spelling of a real field (`max-tokens`) is rejected too, naming the field it resembles, and so is a header-shaped key whose value is not a string (`x-foo = 3`) — a header value must be a quoted string, and is never stringified onto the wire. A key that clears the shape gate must also be usable as a header on the wire: the name may contain only letters, digits and RFC 7230 token punctuation, so a quoted `"x-foo bar"` is refused, and the value must be printable ASCII on a single line with no leading or trailing whitespace, so a line break or an invisible trailing space is refused — each of those used to load fine and have the HTTP client reject the request on the first call to that model. In the remotely served Pipelex Gateway config the same rule prunes such keys instead of failing, as version skew. `endpoint_path` — the provider-side route the Gateway image models are called by — is a declared model-spec field rather than a header entry.- **Remote inference config bumped to `pipelex_remote_config_12.json`**: The Pipelex Gateway model specs are fetched from a new versioned URL whose `defaults` no longer declare the removed field. Earlier releases stay pinned to `_11`, which is frozen. Unknown keys in the *remote* config's `defaults` are now pruned rather than rejected, so a gateway config written by a different release than the client reading it is version skew to tolerate; local backend files stay strict.### Removed-- **`prompting_target` (Breaking)**: Gone from `LLMSetting`, `InferenceModelSpec`, `InferenceModelSpecBlueprint` and every backend TOML, along with the `PromptingTarget` enum and the per-target style map (`[pipelex.prompting_config]` and its `prompting_styles` sub-table, replaced by `[pipelex.templating_config]`). **Migration:** delete every `prompting_target` line from your own `.pipelex/inference/backends/*.toml` — backend files are read strictly, so a surviving one fails the boot. Check `portkey.toml` in particular: the key appears in `[defaults]` *and* on individual model entries, and an unknown per-model key is sent to the provider as an HTTP header rather than rejected.+- **`prompting_target` (Breaking)**: Gone from `LLMSetting`, `InferenceModelSpec`, `InferenceModelSpecBlueprint` and every backend TOML, along with the `PromptingTarget` enum and the per-target style map (`[pipelex.prompting_config]` and its `prompting_styles` sub-table, replaced by `[pipelex.templating_config]`). **Migration:** delete every `prompting_target` line from your own `.pipelex/inference/backends/*.toml` — backend files are read strictly, so a surviving one fails the boot. Check `portkey.toml` in particular: the key appears in `[defaults]` *and* on individual model entries, and a surviving per-model one is rejected by name as an unknown, non-header key.- **`LLMPromptTemplate` and friends**: Removed the unused prompt-template module along with `LLMPromptFactoryAbstract`, `LLMPromptTemplateInputs` and `LLMPromptTemplateInputsError`. Their hardcoded XML+Markdown style predated the configurable one and had no production consumer.## [v0.45.0] - 2026-08-14diff --git a/docs/configuration/config-technical/inference-backend-config.md b/docs/configuration/config-technical/inference-backend-config.mdindex a7b9ea2b8..997c2a95f 100644--- a/docs/configuration/config-technical/inference-backend-config.md+++ b/docs/configuration/config-technical/inference-backend-config.md@@ -316,6 +316,38 @@ outputs = ["image"]costs = { input = 0.04, output = 0.0 }```+#### Sending extra request headers per model++A model table may carry keys beyond the model-spec fields. A key shaped like a request header — it contains a hyphen and its value is a string — is sent to the provider **as an HTTP request header** on each call to that model; this is how, for example, the Portkey backend routes each model to its upstream provider:++```toml+# portkey.toml+[gpt-4o-mini]+model_id = "gpt-4o-mini"+x-portkey-provider = "@openai" # forwarded as the `x-portkey-provider` request header+```++Because these strings go out over the network, an extra key is accepted as a header **only if it is shaped like one — it must contain a hyphen** (`x-portkey-provider`, `anthropic-beta`, `api-version`) **and its value must be a string** (quote it in TOML). Model-spec field names never contain a hyphen, so an unknown key without one is a misspelled setting or a field that no longer exists, and it is a configuration error rather than a header: the backend fails to load and the error names the key, the model and the file. A hyphenated spelling of a real field (`max-tokens` for `max_tokens`) is rejected the same way, with the field it resembles, and so is a header-shaped key whose value is not a string (`x-foo = 3`) — it is never stringified onto the wire. This holds in every boot mode, including the credential-free one used by `pipelex validate` and dry runs — a typo must never silently drop a backend and surface later as "model not found".++```text+Unknown key on model 'gpt-4o' for backend 'openai' from file '.pipelex/inference/backends/openai.toml':+'max_tokns' is not a known model-spec field, and not header-shaped. A per-model key that is not a+model-spec field is sent to the provider as a request header and must contain a hyphen+(e.g. 'x-portkey-provider'): fix the typo, or name the key like a header if that is what it is meant to be.+```++A key that clears that gate must also be *usable* as a header, so the name and the value are checked against what HTTP itself allows. A header name may contain only letters, digits and the characters ``!#$%&'*+-.^_`|~`` — so a quoted key like `"x-foo bar"` is rejected — and a header value must be printable ASCII on a single line with no leading or trailing whitespace, which rules out a line break, a control character, an accented letter, and the invisible trailing space in `x-foo = "value "`. Without this check the backend loaded happily and the HTTP client refused the request on the first call to that model, far from the file that caused it.++```text+Unknown key on model 'gpt-4o' for backend 'openai' from file '.pipelex/inference/backends/openai.toml':+'x-foo bar' cannot be a header name: ' ' is not allowed in one — a header name may contain only+letters, digits and the characters !#$%&'*+-.^_`|~.+```++The Pipelex Gateway's model specs are fetched from Pipelex servers rather than read from a local file, and there the same rule is applied leniently: a header-shaped key whose name and value the wire can carry becomes a header, and any other unknown key — including a header-shaped one whose value is not a string, or whose name or value HTTP would refuse — is dropped instead of failing the boot, since a served config can legitimately be newer or older than the client reading it.++`endpoint_path` is a declared model-spec field, not a header: it names the provider-side route for models that are called by raw path (the Gateway's image models), and is never sent on the wire.+## Routing ProfilesRouting profiles determine which backend handles specific models. This is where you configure the **Mix & Match approach** (Option C) to optimize your setup. Configure them in `.pipelex/inference/routing_profiles.toml`:diff --git a/pipelex/cli/commands/run/_run_core.py b/pipelex/cli/commands/run/_run_core.pyindex c2fe39ee9..bde638fe3 100644--- a/pipelex/cli/commands/run/_run_core.py+++ b/pipelex/cli/commands/run/_run_core.py@@ -416,9 +416,13 @@ def execute_run(Shared between the ``method`` and ``pipe`` subcommands."""- # A dry run makes no inference call, so it must not demand credentials: boot keyless (every run- # is then forced to DRY) but with real model specs, so model handles resolve as on a live run.- # This is the same boot `pipelex-agent run --dry-run` uses, so the two CLIs agree on a keyless machine.+ # A dry run makes no inference call, so it must not demand credentials: `needs_inference=False`+ # forces every run to DRY and skips a backend whose key is missing instead of failing the boot.+ # `needs_model_specs=True` keeps the real gateway model specs (not the dummy ones), so wherever+ # credentials ARE present a dry run resolves model handles exactly as a live run would. It does not+ # help on a machine with no key at all: a skipped backend contributes no models, so a pipe pinning a+ # bare handle served only by that backend reports it as not found (see docs/features/validation-dry-run.md).+ # This is the same boot `pipelex-agent run --dry-run` uses, so the two CLIs agree either way.make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_PIPE_RUN,library_dirs=library_dir,diff --git a/pipelex/cogt/model_backends/backend_library.py b/pipelex/cogt/model_backends/backend_library.pyindex b9828ff26..8debcf65e 100644--- a/pipelex/cogt/model_backends/backend_library.py+++ b/pipelex/cogt/model_backends/backend_library.py@@ -24,6 +24,7 @@ from pipelex.cogt.model_backends.model_spec_factory import (InferenceModelSpecBlueprint,InferenceModelSpecFactory,)+from pipelex.cogt.model_backends.model_spec_keys import ModelSpecSource, describe_rejected_keys, split_model_spec_keysfrom pipelex.system.environment import get_optional_envfrom pipelex.system.pipelex_service.gateway_config_merger import GatewayConfigMergerfrom pipelex.system.runtime import runtime_manager@@ -96,7 +97,6 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):# We'll split the read settings into standard fields and extra configbackend_blueprint_standard_fields = InferenceBackendBlueprint.model_fields.keys()- model_spec_blueprint_standard_fields = InferenceModelSpecBlueprint.model_fields.keys()for backend_name, backend_dict in backends_dict.items():extra_config: dict[str, Any] = {}inference_backend_blueprint_dict_raw = backend_dict.copy()@@ -158,6 +158,7 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):# Handle pipelex_gateway specially - use remote configbackend_config_source: str+ model_spec_source: ModelSpecSourceif PipelexBackend.is_gateway_backend(backend_name):if gateway_config is None:if lenient:@@ -166,6 +167,7 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):msg = "Pipelex Gateway backend is enabled but remote model specs were not provided"raise InferenceBackendLibraryError(msg)extra_config["aws_region"] = gateway_config.aws_region+ model_spec_source = ModelSpecSource.REMOTE_GATEWAYmodel_specs_dict, backend_config_source = self._load_gateway_model_specs(gateway_config=gateway_config,backend_name=backend_name,@@ -173,6 +175,7 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):substitute_vars_with_provider=substitute_vars_with_provider,)else:+ model_spec_source = ModelSpecSource.LOCAL_FILEmodel_specs_dict, backend_config_source = self._load_local_model_specs(backend_name=backend_name,backends_dir_path=backends_dir_path,@@ -187,16 +190,28 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):raise InferenceModelSpecError(msg)model_spec_dict: dict[str, Any] = cast("dict[str, Any]", value)try:- # Start from the defaults+ # A per-model key the blueprint does not know is a request header only if it is shaped+ # like one; anything else is a typo or a dead field, and what happens to it depends on+ # where the table came from.+ key_split = split_model_spec_keys(model_spec_dict=model_spec_dict)+ if key_split.rejected:+ match model_spec_source:+ case ModelSpecSource.LOCAL_FILE:+ # Fatal in lenient mode too: leniency covers credentials only (see the docstring),+ # and this is not a credentials error, so the lenient `except` below lets it through.+ plural = "s" if len(key_split.rejected) > 1 else ""+ msg = (+ f"Unknown key{plural} on model '{model_spec_name}' for backend '{backend_name}' "+ f"from {backend_config_source}: {describe_rejected_keys(rejected=key_split.rejected)}"+ )+ raise InferenceBackendLibraryError(msg)+ case ModelSpecSource.REMOTE_GATEWAY:+ # Version skew, the same judgement `drop_unknown_gateway_defaults` makes for the+ # `defaults` block: pruned, and silently — this can run before the log hub is set.+ pass+ # Start from the defaults, then override with the model's own fieldsmodel_spec_blueprint_dict = defaults_dict.copy()- # Override with the attributes from the model spec dict- model_spec_blueprint_dict.update(model_spec_dict)-- # We'll split the read settings into standard fields and extra headers- extra_headers: dict[str, str] = {}- for model_spec_key in model_spec_dict:- if model_spec_key not in model_spec_blueprint_standard_fields:- extra_headers[model_spec_key] = model_spec_blueprint_dict.pop(model_spec_key)+ model_spec_blueprint_dict.update(key_split.fields)model_spec_blueprint = InferenceModelSpecBlueprint.model_validate(model_spec_blueprint_dict)model_spec = InferenceModelSpecFactory.make_inference_model_spec(backend_name=backend_name,@@ -204,7 +219,7 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):blueprint=model_spec_blueprint,backend_listed_constraints=backend_blueprint.listed_constraints,backend_valued_constraints=backend_blueprint.valued_constraints,- extra_headers=extra_headers,+ extra_headers=key_split.headers,)backend_model_specs[model_spec_name] = model_specexcept ValidationError as validation_error:diff --git a/pipelex/cogt/model_backends/gateway_config.py b/pipelex/cogt/model_backends/gateway_config.pyindex 4b9e10b99..08b33d606 100644--- a/pipelex/cogt/model_backends/gateway_config.py+++ b/pipelex/cogt/model_backends/gateway_config.py@@ -21,9 +21,9 @@ def drop_unknown_gateway_defaults(*, gateway_model_specs: BackendModelSpecs) ->is version skew, and dropping it keeps a boot working across that skew; a *local* backend filestays strict, because there an unknown key really is the author's typo.- Scoped to `defaults` on purpose. A per-model key the blueprint does not know is already meaningful- — `InferenceBackendLibrary.load` reclassifies it as an outbound HTTP header — and that behaviour is not this- function's to reinterpret.+ Scoped to `defaults` on purpose. A per-model key gets its own rule in `InferenceBackendLibrary.load`,+ via `split_model_spec_keys`: header-shaped keys are outbound request headers, and the rest is pruned+ from a remote payload (the same skew judgement as here) or fatal in a local file.Deliberately pure, and deliberately silent: it runs on the success path of every gateway-backendload, including loads that happen before `runtime_hub.set_config()` has configured the logdiff --git a/pipelex/cogt/model_backends/model_spec.py b/pipelex/cogt/model_backends/model_spec.pyindex 1d2fa0694..966bbfb13 100644--- a/pipelex/cogt/model_backends/model_spec.py+++ b/pipelex/cogt/model_backends/model_spec.py@@ -33,6 +33,7 @@ class InferenceModelSpec(ConfigModel):valued_constraints: dict[ValuedConstraint, Any] = Field(default_factory=empty_dict_factory_of(ValuedConstraint))extra_headers: dict[str, str] | None = Nonerules: ImgGenModelRules | None = None+ endpoint_path: str | None = None@propertydef tag(self) -> str:diff --git a/pipelex/cogt/model_backends/model_spec_factory.py b/pipelex/cogt/model_backends/model_spec_factory.pyindex a7b3e03f2..24e5ece5a 100644--- a/pipelex/cogt/model_backends/model_spec_factory.py+++ b/pipelex/cogt/model_backends/model_spec_factory.py@@ -31,6 +31,9 @@ class InferenceModelSpecBlueprint(ConfigModel):listed_constraints: list[ListedConstraint] = Field(default_factory=empty_list_factory_of(ListedConstraint))valued_constraints: dict[ValuedConstraint, Any] = Field(default_factory=empty_dict_factory_of(ValuedConstraint))rules: ImgGenModelRules | None = None+ # Provider-side route for models the worker calls by raw path (today: the gateway image models). Our own+ # routing metadata, not a request header — which is why it is a declared field and not an `extra_headers` entry.+ endpoint_path: str | None = None@field_validator("rules", mode="before")@staticmethod@@ -107,4 +110,5 @@ class InferenceModelSpecFactory(BaseModel):valued_constraints=merged_valued_constraints,extra_headers=extra_headers,rules=blueprint.rules,+ endpoint_path=blueprint.endpoint_path,)diff --git a/pipelex/cogt/model_backends/model_spec_keys.py b/pipelex/cogt/model_backends/model_spec_keys.pynew file mode 100644index 000000000..888bfa818--- /dev/null+++ b/pipelex/cogt/model_backends/model_spec_keys.py@@ -0,0 +1,174 @@+"""Sorting a per-model backend table into blueprint fields, request headers, and everything else.++`InferenceModelSpecBlueprint` is strict, so a per-model key it does not know cannot simply be validated+away. Historically every such key was moved to `extra_headers` and sent to the provider as a request+header — which is right for `x-portkey-config` and wrong for a typo or a field deleted from the blueprint,+both of which then went out on the wire while the real setting stayed unset.++The rule here is a shape rule, not a name allowlist, so the served gateway config can start carrying a+new `x-portkey-*` header without waiting for a client release: **an unknown key is a header only if it+contains a hyphen and its value is a string.** Header names conventionally do; blueprint field names+never do, because they are Python identifiers. A hyphenated spelling of a known field (`max-tokens`) is+the one hole that leaves, and it is closed by name. The value half is not coercion: `x-foo = 3` is an+unquoted value, and `str(True)` or `str(["a"])` on the wire is exactly the rogue header this guards+against, so a non-string value is rejected rather than stringified.++Shaped like a header is not the same as usable as one, so a second gate follows the first: the name+must be an RFC 7230 token, and the value must be printable ASCII on a single line with no leading or+trailing whitespace. Both are what the HTTP stack itself enforces — a quoted key like `x-foo bar`, or+a value carrying a CR/LF or an invisible trailing space, is refused by h11 when the request is built,+so without this gate the author hears about the mistake on the first inference call instead of at+boot. One deliberate divergence: h11 accepts `0x7f` (DEL) in a value and this does not, because a DEL+in a config file is never intentional and "printable ASCII" is a rule a reader can hold in their head.+Nothing here couples to h11's own patterns — it is a transitive dependency of httpx, and the rule must+not become "whatever this version of h11 does".++This module is deliberately pure and deliberately silent. It runs on the success path of every backend+load, including loads that precede `runtime_hub.set_config()`, so a `log` call here would turn a data+transform into a boot-order dependency. It also does not decide what a rejected key *means*: only the+caller knows whether the table came from a local file (where a rejected key is the author's typo, and+fatal) or from the served gateway config (where it is version skew, and pruned).+"""++import re+from enum import StrEnum+from typing import Any, NamedTuple++from pipelex.cogt.model_backends.model_spec_factory import InferenceModelSpecBlueprint++HEADER_KEY_EXAMPLE = "x-portkey-provider"+HEADER_NAME_CHARACTERS = "letters, digits and the characters !#$%&'*+-.^_`|~"++# An RFC 7230 header field name is a token, and a field value is printable ASCII on a single line.+_HEADER_NAME_PATTERN = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")+_HEADER_VALUE_PATTERN = re.compile(r"([\x21-\x7e]([ \t\x21-\x7e]*[\x21-\x7e])?)?")+++class ModelSpecSource(StrEnum):+ """Where a per-model table was read from — the only thing that decides what a rejected key means."""++ LOCAL_FILE = "local_file"+ REMOTE_GATEWAY = "remote_gateway"+++class ModelSpecKeyRejection(StrEnum):+ """Why an unknown per-model key was not accepted as a request header."""++ NOT_HEADER_SHAPED = "not_header_shaped"+ HYPHENATED_KNOWN_FIELD = "hyphenated_known_field"+ ILLEGAL_HEADER_NAME = "illegal_header_name"+ NON_STRING_VALUE = "non_string_value"+ ILLEGAL_HEADER_VALUE = "illegal_header_value"+++class RejectedModelSpecKey(NamedTuple):+ key: str+ reason: ModelSpecKeyRejection+ near_miss_of: str | None = None+ """The known blueprint field this header-shaped key is a hyphenated spelling of — set for `HYPHENATED_KNOWN_FIELD` only."""+ illegal_character: str | None = None+ """The first character barring this key from being a header field name — set for `ILLEGAL_HEADER_NAME` only."""++ def describe(self) -> str:+ """The per-key reason; `describe_rejected_keys` adds the hyphen rule once for the whole list when it applies."""+ match self.reason:+ case ModelSpecKeyRejection.NOT_HEADER_SHAPED:+ return f"'{self.key}' is not a known model-spec field, and not header-shaped"+ case ModelSpecKeyRejection.HYPHENATED_KNOWN_FIELD:+ return f"'{self.key}' looks like the model-spec field '{self.near_miss_of}' spelled with hyphens — use '{self.near_miss_of}'"+ case ModelSpecKeyRejection.ILLEGAL_HEADER_NAME:+ return (+ f"'{self.key}' cannot be a header name: {self.illegal_character!r} is not allowed in one — "+ f"a header name may contain only {HEADER_NAME_CHARACTERS}"+ )+ case ModelSpecKeyRejection.NON_STRING_VALUE:+ return f"'{self.key}' is header-shaped, but its value is not a string — a request header value must be a quoted string"+ case ModelSpecKeyRejection.ILLEGAL_HEADER_VALUE:+ return (+ f"'{self.key}' is header-shaped, but its value cannot be sent as a header value — it must be printable ASCII "+ "on a single line, with no leading or trailing whitespace"+ )+++class ModelSpecKeySplit(NamedTuple):+ fields: dict[str, Any]+ headers: dict[str, str]+ rejected: list[RejectedModelSpecKey]+++def describe_rejected_keys(*, rejected: list[RejectedModelSpecKey]) -> str:+ """The reasons for every rejected key, then the hyphen rule once if any key lacked one, phrased for the person who has to fix the file.++ Only a `NOT_HEADER_SHAPED` key earns the trailer: every other rejection already has a hyphen and is told what is+ actually wrong with it — the field it resembles, the illegal character, the unquoted value — so "add a hyphen"+ would be wrong advice.+ """+ reasons = "; ".join(rejected_key.describe() for rejected_key in rejected)+ if not any(rejected_key.reason is ModelSpecKeyRejection.NOT_HEADER_SHAPED for rejected_key in rejected):+ return f"{reasons}."+ return (+ f"{reasons}. A per-model key that is not a model-spec field is sent to the provider as a request header "+ f"and must contain a hyphen (e.g. '{HEADER_KEY_EXAMPLE}'): fix the typo, or name the key like a header if that is what it is meant to be."+ )+++def is_header_shaped(*, key: str) -> bool:+ """Whether the author meant this key as a header at all: a blueprint field name is an identifier and never carries a hyphen."""+ return "-" in key+++def is_legal_header_name(*, key: str) -> bool:+ """Whether the wire will carry this key as a header field name."""+ return _HEADER_NAME_PATTERN.fullmatch(key) is not None+++def first_illegal_header_name_character(*, key: str) -> str | None:+ """The first character barring this key from being a header field name, so the error can name it."""+ for character in key:+ if _HEADER_NAME_PATTERN.fullmatch(character) is None:+ return character+ return None+++def is_legal_header_value(*, value: str) -> bool:+ """Whether the wire will carry this string as a header field value."""+ return _HEADER_VALUE_PATTERN.fullmatch(value) is not None+++def split_model_spec_keys(*, model_spec_dict: dict[str, Any]) -> ModelSpecKeySplit:+ """Split one per-model table into blueprint fields, request headers, and rejected keys.++ Order is preserved throughout, and the input is not modified.+ """+ known_fields = InferenceModelSpecBlueprint.model_fields.keys()+ fields: dict[str, Any] = {}+ headers: dict[str, str] = {}+ rejected: list[RejectedModelSpecKey] = []+ for key, value in model_spec_dict.items():+ if key in known_fields:+ fields[key] = value+ continue+ if not is_header_shaped(key=key):+ rejected.append(RejectedModelSpecKey(key=key, reason=ModelSpecKeyRejection.NOT_HEADER_SHAPED))+ continue+ underscored = key.replace("-", "_")+ if underscored in known_fields:+ rejected.append(RejectedModelSpecKey(key=key, reason=ModelSpecKeyRejection.HYPHENATED_KNOWN_FIELD, near_miss_of=underscored))+ continue+ if not is_legal_header_name(key=key):+ rejected.append(+ RejectedModelSpecKey(+ key=key,+ reason=ModelSpecKeyRejection.ILLEGAL_HEADER_NAME,+ illegal_character=first_illegal_header_name_character(key=key),+ )+ )+ continue+ if not isinstance(value, str):+ rejected.append(RejectedModelSpecKey(key=key, reason=ModelSpecKeyRejection.NON_STRING_VALUE))+ continue+ if not is_legal_header_value(value=value):+ rejected.append(RejectedModelSpecKey(key=key, reason=ModelSpecKeyRejection.ILLEGAL_HEADER_VALUE))+ continue+ headers[key] = value+ return ModelSpecKeySplit(fields=fields, headers=headers, rejected=rejected)diff --git a/pipelex/providers/gateway/gateway_img_gen_worker.py b/pipelex/providers/gateway/gateway_img_gen_worker.pyindex c9cfcd80e..0ba5b028e 100644--- a/pipelex/providers/gateway/gateway_img_gen_worker.py+++ b/pipelex/providers/gateway/gateway_img_gen_worker.py@@ -83,7 +83,7 @@ class GatewayImgGenWorker(ImgGenWorkerAbstract):model_name=self.inference_model.name,)- endpoint_path = (self.inference_model.extra_headers or {}).get("endpoint_path")+ endpoint_path = self.inference_model.endpoint_pathif not endpoint_path:msg = f"Model '{self.inference_model.name}' does not have an endpoint_path configured but it's required for this model/sdk."raise ImgGenParameterError(msg)diff --git a/tests/unit/pipelex/cogt/model_backends/test_backend_library_leniency.py b/tests/unit/pipelex/cogt/model_backends/test_backend_library_leniency.pyindex fa5ff615d..d5a4c67b2 100644--- a/tests/unit/pipelex/cogt/model_backends/test_backend_library_leniency.py+++ b/tests/unit/pipelex/cogt/model_backends/test_backend_library_leniency.py@@ -46,6 +46,66 @@ a_field_we_removed = "openai"model_id = "acme-one""""+MODEL_SPECS_TOML_WITH_UNKNOWN_PER_MODEL_KEY = """+[defaults]+model_type = "llm"+sdk = "openai_responses"++["acme-one"]+model_id = "acme-one"+max_tokns = 4096+"""++MODEL_SPECS_TOML_WITH_NEAR_MISS_PER_MODEL_KEY = """+[defaults]+model_type = "llm"+sdk = "openai_responses"++["acme-one"]+model_id = "acme-one"+max-tokens = 4096+"""++MODEL_SPECS_TOML_WITH_HEADER_KEY = """+[defaults]+model_type = "llm"+sdk = "openai_responses"++["acme-one"]+model_id = "acme-one"+x-portkey-provider = "@openai"+"""++MODEL_SPECS_TOML_WITH_NON_STRING_HEADER_VALUE = """+[defaults]+model_type = "llm"+sdk = "openai_responses"++["acme-one"]+model_id = "acme-one"+x-foo = 3+"""++MODEL_SPECS_TOML_WITH_ILLEGAL_HEADER_NAME = """+[defaults]+model_type = "llm"+sdk = "openai_responses"++["acme-one"]+model_id = "acme-one"+"x-foo bar" = "value"+"""++MODEL_SPECS_TOML_WITH_ILLEGAL_HEADER_VALUE = """+[defaults]+model_type = "llm"+sdk = "openai_responses"++["acme-one"]+model_id = "acme-one"+x-foo = "trailing "+"""+MODEL_SPECS_TOML_WITH_MISSING_CREDENTIAL = f"""[defaults]model_type = "llm"@@ -107,6 +167,102 @@ class TestBackendLibraryLeniency:lenient=lenient,)+ @pytest.mark.parametrize("lenient", [True, False])+ def test_an_unknown_per_model_key_in_a_local_backend_is_fatal_in_both_modes(self, tmp_path: Path, lenient: bool) -> None:+ """A per-model typo used to be sent to the provider as a request header, silently, while the+ real setting stayed unset. It is now a boot error that names the key, the model and the file.+ """+ with pytest.raises(InferenceBackendLibraryError) as exc_info:+ self._load(+ tmp_path,+ backends_toml=BACKENDS_TOML,+ model_specs_toml=MODEL_SPECS_TOML_WITH_UNKNOWN_PER_MODEL_KEY,+ lenient=lenient,+ )++ message = str(exc_info.value)+ assert "'max_tokns'" in message+ assert "'acme-one'" in message+ assert "acme.toml" in message+ assert "hyphen" in message++ def test_a_hyphenated_spelling_of_a_known_field_is_fatal_and_names_the_field(self, tmp_path: Path) -> None:+ with pytest.raises(InferenceBackendLibraryError, match=r"'max-tokens'.*'max_tokens'"):+ self._load(+ tmp_path,+ backends_toml=BACKENDS_TOML,+ model_specs_toml=MODEL_SPECS_TOML_WITH_NEAR_MISS_PER_MODEL_KEY,+ lenient=False,+ )++ @pytest.mark.parametrize("lenient", [True, False])+ def test_a_header_shaped_key_with_a_non_string_value_is_fatal_in_both_modes(self, tmp_path: Path, lenient: bool) -> None:+ """`x-foo = 3` is an unquoted value, not a header to stringify. The message is the rule's, not pydantic's:+ it names the key, the model and the file, and says the value must be a quoted string.+ """+ with pytest.raises(InferenceBackendLibraryError) as exc_info:+ self._load(+ tmp_path,+ backends_toml=BACKENDS_TOML,+ model_specs_toml=MODEL_SPECS_TOML_WITH_NON_STRING_HEADER_VALUE,+ lenient=lenient,+ )++ message = str(exc_info.value)+ assert "'x-foo'" in message+ assert "'acme-one'" in message+ assert "acme.toml" in message+ assert "must be a quoted string" in message+ assert "string_type" not in message++ @pytest.mark.parametrize("lenient", [True, False])+ def test_a_header_shaped_key_the_wire_cannot_carry_is_fatal_in_both_modes(self, tmp_path: Path, lenient: bool) -> None:+ """A quoted TOML key can hold a character no header field name may carry. Such a key used to load+ fine and raise `LocalProtocolError: Illegal header name` on the first inference call instead.+ """+ with pytest.raises(InferenceBackendLibraryError) as exc_info:+ self._load(+ tmp_path,+ backends_toml=BACKENDS_TOML,+ model_specs_toml=MODEL_SPECS_TOML_WITH_ILLEGAL_HEADER_NAME,+ lenient=lenient,+ )++ message = str(exc_info.value)+ assert "'x-foo bar'" in message+ assert "'acme-one'" in message+ assert "acme.toml" in message+ assert "' '" in message++ @pytest.mark.parametrize("lenient", [True, False])+ def test_a_header_value_the_wire_cannot_carry_is_fatal_in_both_modes(self, tmp_path: Path, lenient: bool) -> None:+ """`x-foo = "trailing "` is valid TOML and the mistake is invisible in the file, which is exactly+ why the error must name it — the HTTP stack otherwise reports it much later, mid-run.+ """+ with pytest.raises(InferenceBackendLibraryError) as exc_info:+ self._load(+ tmp_path,+ backends_toml=BACKENDS_TOML,+ model_specs_toml=MODEL_SPECS_TOML_WITH_ILLEGAL_HEADER_VALUE,+ lenient=lenient,+ )++ message = str(exc_info.value)+ assert "'x-foo'" in message+ assert "'acme-one'" in message+ assert "acme.toml" in message+ assert "no leading or trailing whitespace" in message++ def test_a_header_shaped_per_model_key_still_becomes_a_request_header(self, tmp_path: Path) -> None:+ """The regression that matters: `x-portkey-provider` in the local portkey.toml keeps working."""+ library = self._load(tmp_path, backends_toml=BACKENDS_TOML, model_specs_toml=MODEL_SPECS_TOML_WITH_HEADER_KEY, lenient=False)++ backend = library.get_inference_backend(backend_name="acme")+ assert backend is not None+ model_spec = backend.model_specs["acme-one"]+ assert model_spec.extra_headers == {"x-portkey-provider": "@openai"}+ assert model_spec.model_id == "acme-one"+@pytest.mark.parametrize("lenient", [True, False])def test_a_missing_per_backend_toml_is_fatal_in_both_modes(self, tmp_path: Path, lenient: bool) -> None:with pytest.raises(InferenceBackendLibraryError, match=r"acme\.toml"):diff --git a/tests/unit/pipelex/cogt/model_backends/test_gateway_unknown_defaults.py b/tests/unit/pipelex/cogt/model_backends/test_gateway_unknown_defaults.pyindex 337c1c764..f0cd633f6 100644--- a/tests/unit/pipelex/cogt/model_backends/test_gateway_unknown_defaults.py+++ b/tests/unit/pipelex/cogt/model_backends/test_gateway_unknown_defaults.py@@ -4,6 +4,10 @@ It is served by a component that deploys on its own schedule, so a client can reby a different release than itself. `InferenceModelSpecBlueprint` forbids extra fields, so withoutthis pruning an unknown key in the remote `defaults` block hard-fails the boot — which is exactlywhat happened the day `prompting_target` was removed while the served config still declared it.++The same skew tolerance applies per model, where it is the loader's rule rather than this function's —+see `test_gateway_unknown_per_model_keys.py`. A local backend file gets the strict counterpart of both+rules — see `test_backend_library_leniency.py`."""from typing import Any, cast@@ -58,7 +62,7 @@ class TestGatewayUnknownDefaults:assert pruned["defaults"] == {"max_tokens": 4096}def test_per_model_unknown_keys_are_untouched(self) -> None:- """A per-model unknown key means something already — it becomes an outbound HTTP header."""+ """This function is scoped to `defaults`; the per-model rule is the loader's, tested in `test_gateway_unknown_per_model_keys.py`."""# The unknown key in `defaults` is what forces the deep-copy prune to run at all: without it# the function early-returns and this test proves nothing.specs = self._specs(defaults={"max_tokens": 4096, "a_field_we_removed": "anthropic"})diff --git a/tests/unit/pipelex/cogt/model_backends/test_gateway_unknown_per_model_keys.py b/tests/unit/pipelex/cogt/model_backends/test_gateway_unknown_per_model_keys.pynew file mode 100644index 000000000..a6ea4f434--- /dev/null+++ b/tests/unit/pipelex/cogt/model_backends/test_gateway_unknown_per_model_keys.py@@ -0,0 +1,148 @@+"""The remote gateway config may carry per-model keys this client's model-spec blueprint does not know.++It is served by a component that deploys on its own schedule, so a client can read a config written+by a different release than itself. The loader's per-model rule tolerates that skew: an unknown+per-model key that is header-shaped is a request header the back office started serving on purpose,+and anything else is pruned rather than sent to the provider. The `defaults` block gets the same+tolerance in `test_gateway_unknown_defaults.py`; a local backend file gets the strict counterpart of+the rule — see `test_backend_library_leniency.py`.+"""++from pathlib import Path+from typing import Any, cast++from pytest_mock import MockerFixture++from pipelex import log+from pipelex.cogt.llm.llm_job import LLMJob+from pipelex.cogt.model_backends.backend_library import InferenceBackendLibrary+from pipelex.cogt.model_backends.gateway_config import GatewayConfig+from pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs+from pipelex.providers.gateway.gateway_factory import GatewayFactory+from pipelex.tools.secrets.env_secrets_provider import EnvSecretsProvider++GATEWAY_BACKENDS_TOML = """+[pipelex_gateway]+enabled = true+api_key = "pk-not-a-real-key"+"""+++class TestGatewayUnknownPerModelKeys:+ """The loader's per-model rule on a remote payload: header-shaped keys are headers, the rest is pruned."""++ def _load(self, tmp_path: Path, *, model_specs: BackendModelSpecs) -> InferenceBackendLibrary:+ backends_dir = tmp_path / "backends"+ backends_dir.mkdir()+ backends_library_path = tmp_path / "backends.toml"+ backends_library_path.write_text(GATEWAY_BACKENDS_TOML)+ library = InferenceBackendLibrary.make_empty()+ library.load(+ secrets_provider=EnvSecretsProvider(),+ backends_library_path=str(backends_library_path),+ backends_dir_path=str(backends_dir),+ gateway_config=GatewayConfig(model_specs=model_specs, aws_region="eu-west-3"),+ )+ return library++ def _remote_specs(self, *, per_model_extras: dict[str, Any]) -> BackendModelSpecs:+ return cast(+ "BackendModelSpecs",+ {+ "defaults": {"model_type": "llm", "sdk": "gateway_completions"},+ "gpt-4o-mini": {"model_id": "gpt-4o-mini", **per_model_extras},+ },+ )++ def test_a_header_shaped_key_becomes_a_request_header(self, tmp_path: Path) -> None:+ """`x-portkey-config` is on every served model; without it the gateway cannot route."""+ library = self._load(tmp_path, model_specs=self._remote_specs(per_model_extras={"x-portkey-config": "pc-openai-6e7576"}))++ backend = library.get_inference_backend(backend_name="pipelex_gateway")+ assert backend is not None+ assert backend.model_specs["gpt-4o-mini"].extra_headers == {"x-portkey-config": "pc-openai-6e7576"}++ def test_a_non_header_key_is_pruned_and_the_boot_survives(self, tmp_path: Path) -> None:+ """Version skew, same as an unknown `defaults` key: pruned, not fatal, and not sent to the provider."""+ library = self._load(+ tmp_path,+ model_specs=self._remote_specs(per_model_extras={"x-portkey-config": "pc-openai-6e7576", "a_field_we_removed": "openai"}),+ )++ backend = library.get_inference_backend(backend_name="pipelex_gateway")+ assert backend is not None+ model_spec = backend.model_specs["gpt-4o-mini"]+ assert model_spec.extra_headers == {"x-portkey-config": "pc-openai-6e7576"}+ assert model_spec.model_id == "gpt-4o-mini"++ def test_a_header_shaped_key_with_a_non_string_value_is_pruned_and_the_boot_survives(self, tmp_path: Path) -> None:+ """A request header value must be a string. A served non-string one is skew too: pruned, never+ stringified onto the wire, and never a boot failure — that would defeat the whole tolerance.+ """+ library = self._load(+ tmp_path,+ model_specs=self._remote_specs(per_model_extras={"x-portkey-config": "pc-openai-6e7576", "x-weird": 3}),+ )++ backend = library.get_inference_backend(backend_name="pipelex_gateway")+ assert backend is not None+ assert backend.model_specs["gpt-4o-mini"].extra_headers == {"x-portkey-config": "pc-openai-6e7576"}++ def test_a_header_shaped_key_the_wire_cannot_carry_is_pruned_and_the_boot_survives(self, tmp_path: Path) -> None:+ """A served key whose name no header may carry is skew like any other: pruned rather than kept and+ left to raise `Illegal header name` on the first inference call.+ """+ library = self._load(+ tmp_path,+ model_specs=self._remote_specs(per_model_extras={"x-portkey-config": "pc-openai-6e7576", "x-weird key": "value"}),+ )++ backend = library.get_inference_backend(backend_name="pipelex_gateway")+ assert backend is not None+ assert backend.model_specs["gpt-4o-mini"].extra_headers == {"x-portkey-config": "pc-openai-6e7576"}++ def test_a_header_value_the_wire_cannot_carry_is_pruned_and_the_boot_survives(self, tmp_path: Path) -> None:+ """Same for a value the HTTP stack refuses — a line break here would otherwise travel all the way+ to the provider call before anyone heard about it.+ """+ library = self._load(+ tmp_path,+ model_specs=self._remote_specs(per_model_extras={"x-portkey-config": "pc-openai-6e7576", "x-weird": "two\r\nlines"}),+ )++ backend = library.get_inference_backend(backend_name="pipelex_gateway")+ assert backend is not None+ assert backend.model_specs["gpt-4o-mini"].extra_headers == {"x-portkey-config": "pc-openai-6e7576"}++ def test_a_declared_field_that_used_to_ride_in_the_bag_lands_in_the_field(self, tmp_path: Path) -> None:+ """`endpoint_path` is served on the image models today. Had it stayed a bag entry, this rule+ would prune it — the whole reason it was promoted to a field first.+ """+ library = self._load(tmp_path, model_specs=self._remote_specs(per_model_extras={"endpoint_path": "openai/deployments/x/images/generations"}))++ backend = library.get_inference_backend(backend_name="pipelex_gateway")+ assert backend is not None+ model_spec = backend.model_specs["gpt-4o-mini"]+ assert model_spec.endpoint_path == "openai/deployments/x/images/generations"+ assert not model_spec.extra_headers++ def test_the_accepted_header_reaches_the_wire(self, tmp_path: Path, mocker: MockerFixture) -> None:+ telemetry_manager = mocker.MagicMock()+ telemetry_manager.is_pipelex_gateway_portkey_tracing_enabled.return_value = False+ mocker.patch("pipelex.providers.gateway.gateway_factory.get_telemetry_manager", return_value=telemetry_manager)+ library = self._load(tmp_path, model_specs=self._remote_specs(per_model_extras={"x-portkey-config": "pc-openai-6e7576"}))+ backend = library.get_inference_backend(backend_name="pipelex_gateway")+ assert backend is not None+ model_spec = backend.model_specs["gpt-4o-mini"]++ extra_headers, _ = GatewayFactory.make_extras(model_spec, inference_job=mocker.MagicMock(spec=LLMJob), output_desc="text")++ assert extra_headers["x-portkey-config"] == "pc-openai-6e7576"++ def test_pruning_a_per_model_key_does_not_need_the_log_hub(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """Same constraint as the `defaults` prune: this runs on gateway loads that precede runtime_hub.set_config()."""+ mocker.patch.object(log.log_dispatch, "_log_config_instance", None)++ library = self._load(tmp_path, model_specs=self._remote_specs(per_model_extras={"a_field_we_removed": "openai"}))++ assert library.get_inference_backend(backend_name="pipelex_gateway") is not Nonediff --git a/tests/unit/pipelex/cogt/model_backends/test_model_spec_key_policy.py b/tests/unit/pipelex/cogt/model_backends/test_model_spec_key_policy.pynew file mode 100644index 000000000..68813612b--- /dev/null+++ b/tests/unit/pipelex/cogt/model_backends/test_model_spec_key_policy.py@@ -0,0 +1,206 @@+"""An unknown per-model key is a request header only if it is shaped like one.++`InferenceBackendLibrary.load` used to move every per-model key the blueprint did not know into+`extra_headers`, and every provider factory forwards that dict to the wire. A typo (`max_tokns`) or+a field deleted from the blueprint therefore became an outbound header, silently, while the real+setting went unset. The classifier below is the pure half of the fix: it splits a raw model table+into blueprint fields, headers, and rejected keys, and leaves the policy — fatal or pruned — to the+loader, which is the only party that knows where the table came from.+"""++import pytest++from pipelex.cogt.model_backends.model_spec_keys import ModelSpecKeyRejection, describe_rejected_keys, split_model_spec_keys+++class TestSplitModelSpecKeys:+ def test_a_known_blueprint_field_is_never_diverted(self) -> None:+ split = split_model_spec_keys(model_spec_dict={"model_id": "gpt-4o", "max_tokens": 4096, "sdk": "openai"})++ assert split.fields == {"model_id": "gpt-4o", "max_tokens": 4096, "sdk": "openai"}+ assert split.headers == {}+ assert split.rejected == []++ @pytest.mark.parametrize("header_key", ["x-portkey-provider", "x-portkey-config", "anthropic-beta", "api-version"])+ def test_a_header_shaped_key_is_accepted_as_a_header(self, header_key: str) -> None:+ split = split_model_spec_keys(model_spec_dict={"model_id": "gpt-4o", header_key: "value"})++ assert split.fields == {"model_id": "gpt-4o"}+ assert split.headers == {header_key: "value"}+ assert split.rejected == []++ @pytest.mark.parametrize("unknown_key", ["max_tokns", "a_field_we_removed", "endpoint", "foobar"])+ def test_an_unknown_key_without_a_hyphen_is_rejected(self, unknown_key: str) -> None:+ """A blueprint field name is a Python identifier — it never carries a hyphen — so an unknown+ hyphen-less key is a typo or a dead field, never a header the author meant to send.+ """+ split = split_model_spec_keys(model_spec_dict={"model_id": "gpt-4o", unknown_key: "value"})++ assert split.fields == {"model_id": "gpt-4o"}+ assert split.headers == {}+ assert [rejected.key for rejected in split.rejected] == [unknown_key]+ assert split.rejected[0].reason == ModelSpecKeyRejection.NOT_HEADER_SHAPED++ @pytest.mark.parametrize(+ ("near_miss", "known_field"), [("max-tokens", "max_tokens"), ("model-id", "model_id"), ("thinking-mode", "thinking_mode")]+ )+ def test_a_hyphenated_spelling_of_a_known_field_is_rejected_despite_its_shape(self, near_miss: str, known_field: str) -> None:+ """The one hole the shape rule leaves: `max-tokens = 4096` is header-shaped and would go out+ on the wire while the real cap stays unset.+ """+ split = split_model_spec_keys(model_spec_dict={"model_id": "gpt-4o", near_miss: 4096})++ assert split.headers == {}+ assert [rejected.key for rejected in split.rejected] == [near_miss]+ assert split.rejected[0].reason == ModelSpecKeyRejection.HYPHENATED_KNOWN_FIELD+ assert split.rejected[0].near_miss_of == known_field++ @pytest.mark.parametrize("value", [3, True, 1.5, ["a"], {"k": "v"}], ids=["int", "bool", "float", "list", "dict"])+ def test_a_header_shaped_key_with_a_non_string_value_is_rejected(self, value: object) -> None:+ """A request header value is a string. `x-foo = 3` is an unquoted-value mistake, not a header+ to stringify: `str(True)` or `str(["a"])` on the wire is exactly the rogue header this guards against.+ """+ split = split_model_spec_keys(model_spec_dict={"model_id": "gpt-4o", "x-foo": value})++ assert split.fields == {"model_id": "gpt-4o"}+ assert split.headers == {}+ assert [rejected.key for rejected in split.rejected] == ["x-foo"]+ assert split.rejected[0].reason == ModelSpecKeyRejection.NON_STRING_VALUE++ @pytest.mark.parametrize(+ ("illegal_key", "illegal_character"),+ [+ ("x-foo bar", " "),+ ("x-foo@bar", "@"),+ ("x-foo/bar", "/"),+ ("x-foo(bar)", "("),+ ("x-foo:bar", ":"),+ ("x-foo\u00e9", "\u00e9"),+ ("x-foo\u00a0bar", "\u00a0"),+ ],+ ids=["space", "at", "slash", "paren", "colon", "non_ascii", "non_breaking_space"],+ )+ def test_a_header_shaped_key_the_wire_cannot_carry_is_rejected(self, illegal_key: str, illegal_character: str) -> None:+ """Shaped like a header is not the same as usable as one: a quoted TOML key can hold a character+ no header name may carry, and the HTTP stack only says so on the first inference call.+ """+ split = split_model_spec_keys(model_spec_dict={"model_id": "gpt-4o", illegal_key: "value"})++ assert split.headers == {}+ assert [rejected.key for rejected in split.rejected] == [illegal_key]+ assert split.rejected[0].reason == ModelSpecKeyRejection.ILLEGAL_HEADER_NAME+ assert split.rejected[0].illegal_character == illegal_character++ @pytest.mark.parametrize("header_key", ["x-foo_bar", "x-foo.bar", "x-foo|bar", "x-foo~bar", "x-foo!bar", "x-foo'bar"])+ def test_an_unusual_token_character_is_still_a_legal_header_name(self, header_key: str) -> None:+ """The guard against over-tightening: underscore, dot, pipe, tilde, bang and apostrophe are all+ RFC 7230 token characters, so a header carrying one must keep working.+ """+ split = split_model_spec_keys(model_spec_dict={header_key: "value"})++ assert split.headers == {header_key: "value"}+ assert split.rejected == []++ @pytest.mark.parametrize(+ "illegal_value",+ ["a\r\nb", "a\nb", "a\rb", "a\x00b", " lead", "trail ", " ", "\ttab-led", "\u00e9acute", "a\x1bb", "a\x7fb"],+ ids=["crlf", "lf", "cr", "nul", "leading_space", "trailing_space", "only_spaces", "leading_tab", "non_ascii", "escape", "del"],+ )+ def test_a_header_value_the_wire_cannot_carry_is_rejected(self, illegal_value: str) -> None:+ """A line break, a control character, a non-ASCII character or an edge space is refused by the+ HTTP stack at send time; the author should hear about it while reading the file, not mid-run.+ """+ split = split_model_spec_keys(model_spec_dict={"model_id": "gpt-4o", "x-foo": illegal_value})++ assert split.headers == {}+ assert [rejected.key for rejected in split.rejected] == ["x-foo"]+ assert split.rejected[0].reason == ModelSpecKeyRejection.ILLEGAL_HEADER_VALUE++ @pytest.mark.parametrize(+ "legal_value",+ ["pc-openai-6e7576", "@openai", "a b", "a\tb", "", "a-very/odd_value:with,punctuation"],+ ids=["config_id", "provider", "inner_space", "inner_tab", "empty", "punctuation"],+ )+ def test_a_header_value_the_wire_accepts_is_kept(self, legal_value: str) -> None:+ """The other half of the guard against over-tightening: everything the wire carries must still pass."""+ split = split_model_spec_keys(model_spec_dict={"x-foo": legal_value})++ assert split.headers == {"x-foo": legal_value}+ assert split.rejected == []++ def test_an_illegal_name_is_reported_before_an_illegal_value(self) -> None:+ """One reason per key: the name is what the author reads first, so it is what the error names first."""+ split = split_model_spec_keys(model_spec_dict={"x-foo bar": 3})++ assert [rejected.reason for rejected in split.rejected] == [ModelSpecKeyRejection.ILLEGAL_HEADER_NAME]++ def test_rejected_keys_explain_themselves_and_state_the_rule_once(self) -> None:+ split = split_model_spec_keys(model_spec_dict={"max_tokns": 4096, "max-tokens": 4096})++ description = describe_rejected_keys(rejected=split.rejected)++ assert "'max_tokns' is not a known model-spec field" in description+ assert "'max-tokens' looks like the model-spec field 'max_tokens'" in description+ assert description.count("must contain a hyphen") == 1++ def test_a_near_miss_alone_is_explained_without_the_hyphen_rule(self) -> None:+ """`max-tokens` already contains a hyphen and its own message already names the field to use;+ telling the author the key "must contain a hyphen" would contradict both.+ """+ split = split_model_spec_keys(model_spec_dict={"max-tokens": 4096})++ description = describe_rejected_keys(rejected=split.rejected)++ assert "'max-tokens' looks like the model-spec field 'max_tokens'" in description+ assert "must contain a hyphen" not in description++ def test_a_non_string_value_is_explained_without_the_hyphen_rule(self) -> None:+ """The key does contain a hyphen; telling the author to add one would be wrong advice."""+ split = split_model_spec_keys(model_spec_dict={"x-foo": 3})++ description = describe_rejected_keys(rejected=split.rejected)++ assert "'x-foo' is header-shaped, but its value is not a string" in description+ assert "must be a quoted string" in description+ assert "must contain a hyphen" not in description++ def test_an_illegal_header_name_is_explained_without_the_hyphen_rule(self) -> None:+ """The key already has a hyphen; what it lacks is a legal character, and the message names it."""+ split = split_model_spec_keys(model_spec_dict={"x-foo bar": "value"})++ description = describe_rejected_keys(rejected=split.rejected)++ assert "'x-foo bar' cannot be a header name" in description+ assert "' '" in description+ assert "must contain a hyphen" not in description++ def test_an_illegal_header_value_is_explained_without_the_hyphen_rule(self) -> None:+ split = split_model_spec_keys(model_spec_dict={"x-foo": "trailing "})++ description = describe_rejected_keys(rejected=split.rejected)++ assert "'x-foo' is header-shaped, but its value cannot be sent as a header value" in description+ assert "no leading or trailing whitespace" in description+ assert "must contain a hyphen" not in description++ def test_a_shape_rejection_beside_a_value_rejection_still_states_the_hyphen_rule_once(self) -> None:+ split = split_model_spec_keys(model_spec_dict={"max_tokns": 4096, "x-foo": 3})++ description = describe_rejected_keys(rejected=split.rejected)++ assert "'max_tokns' is not a known model-spec field" in description+ assert "'x-foo' is header-shaped, but its value is not a string" in description+ assert description.count("must contain a hyphen") == 1++ def test_the_input_table_is_left_untouched(self) -> None:+ model_spec_dict = {"model_id": "gpt-4o", "x-portkey-provider": "openai", "max_tokns": 4096}+ before = dict(model_spec_dict)++ split_model_spec_keys(model_spec_dict=model_spec_dict)++ assert model_spec_dict == before++ def test_the_rejected_list_keeps_table_order(self) -> None:+ split = split_model_spec_keys(model_spec_dict={"zzz_first": 1, "model_id": "gpt-4o", "aaa_second": 2})++ assert [rejected.key for rejected in split.rejected] == ["zzz_first", "aaa_second"]diff --git a/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_edit_routing.py b/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_edit_routing.pyindex 4b72b15cc..3ab57afe1 100644--- a/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_edit_routing.py+++ b/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_edit_routing.py@@ -28,7 +28,7 @@ _PNG_BYTES = b"\x89PNG\r\n\x1a\n" + b"\x00" * 8_PNG_FILE_TUPLE = ("image_0.png", _PNG_BYTES, "image/png")_PNG_FILE_TUPLE_2 = ("image_1.png", _PNG_BYTES, "image/png")-# Production gateway config style: the explicit endpoint_path key on the model spec,+# Production gateway config style: the explicit endpoint_path field on the model spec,# with no leading slash (httpx's base_url merge makes the two forms equivalent)._GENERATIONS_ENDPOINT_PATH = "openai/deployments/gpt-image-1-2025-04-15/images/generations?api-version=2025-04-01-preview"_EDITS_ENDPOINT_PATH = "openai/deployments/gpt-image-1-2025-04-15/images/edits?api-version=2025-04-01-preview"@@ -41,7 +41,8 @@ def _make_worker(mocker: MockerFixture, *, endpoint_path: str = _GENERATIONS_ENDmock_model.model_id = "gpt-image-1"mock_model.name = "gpt-image-1"mock_model.desc = "test-gateway-img-model"- mock_model.extra_headers = {"endpoint_path": endpoint_path}+ mock_model.endpoint_path = endpoint_path+ mock_model.extra_headers = {}mock_model.rules = mocker.MagicMock()worker.inference_model = mock_modeldiff --git a/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_malformed_body.py b/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_malformed_body.pyindex f41c80869..cfbb28c37 100644--- a/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_malformed_body.py+++ b/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_malformed_body.py@@ -38,7 +38,8 @@ def _make_worker(mocker: MockerFixture) -> GatewayImgGenWorker:mock_model.model_id = "gpt-image-1"mock_model.name = "gpt-image-1"mock_model.desc = "test-gateway-img-model"- mock_model.extra_headers = {"endpoint_path": "/gpt-image-1"}+ mock_model.endpoint_path = "/gpt-image-1"+ mock_model.extra_headers = {}mock_model.rules = mocker.MagicMock()worker.inference_model = mock_modeldiff --git a/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_semantic.py b/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_semantic.pyindex dd50853e8..27f4fa64b 100644--- a/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_semantic.py+++ b/tests/unit/pipelex/providers/gateway/test_gateway_img_gen_worker_semantic.py@@ -33,7 +33,8 @@ def _make_worker(mocker: MockerFixture) -> GatewayImgGenWorker:mock_model.model_id = "gpt-image-1"mock_model.name = "gpt-image-1"mock_model.desc = "test-gateway-img-model"- mock_model.extra_headers = {"endpoint_path": "/gpt-image-1"}+ mock_model.endpoint_path = "/gpt-image-1"+ mock_model.extra_headers = {}mock_model.rules = mocker.MagicMock()worker.inference_model = mock_modeldiff --git a/tests/unit/pipelex/providers/gateway/test_gateway_quota_detection.py b/tests/unit/pipelex/providers/gateway/test_gateway_quota_detection.pyindex 47957b6a5..b76fea174 100644--- a/tests/unit/pipelex/providers/gateway/test_gateway_quota_detection.py+++ b/tests/unit/pipelex/providers/gateway/test_gateway_quota_detection.py@@ -70,7 +70,8 @@ def _make_gateway_img_gen_worker(mocker: MockerFixture) -> GatewayImgGenWorker:mock_model.model_id = "gpt-image-1"mock_model.name = "gpt-image-1"mock_model.tag = "test-imggen-tag"- mock_model.extra_headers = {"endpoint_path": "/gpt-image-1"}+ mock_model.endpoint_path = "/gpt-image-1"+ mock_model.extra_headers = {}mock_model.rules = mocker.MagicMock()worker.inference_model = mock_modeldiff --git a/wip/drift-contracts/dogfood-log.md b/wip/drift-contracts/dogfood-log.mdindex 35039c535..671d4d492 100644--- a/wip/drift-contracts/dogfood-log.md+++ b/wip/drift-contracts/dogfood-log.md@@ -97,3 +97,6 @@ The surviving finding is real and small: the table under "What a programmatic caThe transferable part is **who missed it, and why the miss was structurally invited**. The entry directly above is the ack that let it through, and its rationale is precise about what it checked: the module table was AST-diffed and found complete *including* `concrete_llm_model_handle`, and the Gates claim was verified as "still matches that test's own stated exception." Both statements are true. The reviewer checked the table against the code, and the doc against the test — but never the *test's* claim against the code, which is where the new function fell out of the enumeration. **A consistency check between two documents is not a check against reality**, and two mutually-agreeing prose claims are exactly the shape that survives it. This is the inverse of the 2026-08-09 lesson: there, mechanical checks produced false positives that opening the file dismissed; here, a careful human check produced a false negative that only re-deriving the claim from the code would have caught.Also worth noting for the friction verdict above: that entry proposed mechanizing the module table because it "keeps being checked and keeps being fine." The table was indeed fine again. The row that rotted is the one nobody proposed mechanizing — and it rotted *because* it counts ("the three"), the one construct the workspace writing rules already ban for going stale silently. A derived check that enumerates deck-reading kernel functions and asserts the boot-contract test's exception list matches would be cheaper than the table check and would have caught this; the table check would not have.Third consecutive clean review is now second, and the reopening it complained about turned out to be the one that mattered.++- **2026-08-15 · rogue-extra-headers guard · no contract opened, and one should have had a stake** — The change rewrote how `InferenceBackendLibrary.load` (`pipelex/cogt/model_backends/backend_library.py`) treats a per-model key of a backend TOML: an unknown key used to become an outbound HTTP header unconditionally, and now it must be header-shaped or the load fails. That is a user-facing configuration rule — it decides what a line in `.pipelex/inference/backends/*.toml` means and what error the author gets — and it was undocumented until this change wrote it into `docs/configuration/config-technical/inference-backend-config.md`. No contract fired: `backend_library.py`, `model_spec_factory.py` and the new `model_spec_keys.py` are in no contract's trigger set (`config-docs` watches the `ConfigModel` tree, `pipelex.toml`, and a handful of named submodel modules — the shape of `pipelex.toml`, not the shape of the backend files it points at).+ Same finding as the 2026-08-14 `config-docs` scope-miss, from the other direction. There, the doc lived outside the review target; here, the code lives outside the trigger set. Both come from the same gap between what the contract says and what it watches: its `description` says *user-facing configuration docs must track the config model and the shipped defaults*, and the backend TOMLs **are** shipped defaults — `pipelex/kit/configs/inference/backends/*.toml` ships in the package, mirrored by the `.pipelex/inference/backends/*.toml` overrides — yet the only shipped default in the trigger set is `pipelex/pipelex.toml`. So the description promises more than the triggers deliver, and it is the backend TOMLs, the configuration surface a user edits most and the only one that sends strings to third parties, that fall through. They are a second config schema, defined by `InferenceModelSpecBlueprint` / `InferenceBackendBlueprint` and the loader's reclassification rules, and nothing declares that schema owes anything to `docs/configuration/`. Recorded, not acted on, per the pilot's bias: the candidate is a trigger for `pipelex/cogt/model_backends/{backend_library,model_spec_factory,backend_factory,model_spec_keys}.py` (and, by the description's own words, the shipped backend TOMLs under `pipelex/kit/configs/inference/`) on `config-docs`, or a sibling `backend-config-docs` contract with `inference-backend-config.md` as its review target — small either way, and worth deciding at verdict time together with the scope-miss above rather than one at a time.diff --git a/wip/rogue-extra-headers-guard-plan.md b/wip/rogue-extra-headers-guard-plan.mdindex ce16c8e58..79d1cff87 100644--- a/wip/rogue-extra-headers-guard-plan.md+++ b/wip/rogue-extra-headers-guard-plan.md@@ -103,24 +103,24 @@ Everything unknown that is *not* header-shaped is then handled by source:Goal: the one non-header key in the bag stops pretending to be a header. No behaviour change, no served-config change, no config URL bump — the served TOML is untouched, the new client merely classifies the key differently, and older clients keep reading it out of `extra_headers` exactly as before.-- [ ] `InferenceModelSpecBlueprint.endpoint_path: str | None = None` (`model_spec_factory.py`) and the matching field on `InferenceModelSpec` (`model_spec.py`), with the factory passthrough.-- [ ] `gateway_img_gen_worker.py:86` reads `self.inference_model.endpoint_path` instead of digging in `extra_headers`. Its existing "does not have an endpoint_path configured" error stays — it is the right error, it just now guards a real field.-- [ ] Update the image-worker tests that stub the bag: `test_gateway_img_gen_worker_semantic.py`, `test_gateway_img_gen_worker_malformed_body.py`, `test_gateway_img_gen_worker_edit_routing.py`, `test_gateway_quota_detection.py`. Each sets `mock_model.extra_headers = {"endpoint_path": …}`; they should set the field and leave the bag to the headers that belong in it.-- [ ] Verify against the live payload that the key still parses into the field and that `x-portkey-config` still lands in `extra_headers` — a real boot, not only mocks.-- [ ] Gates: targeted tests, `make tb`, stage + `make agent-check`.+- [x] `InferenceModelSpecBlueprint.endpoint_path: str | None = None` (`model_spec_factory.py`) and the matching field on `InferenceModelSpec` (`model_spec.py`), with the factory passthrough.+- [x] `gateway_img_gen_worker.py:86` reads `self.inference_model.endpoint_path` instead of digging in `extra_headers`. Its existing "does not have an endpoint_path configured" error stays — it is the right error, it just now guards a real field.+- [x] Update the image-worker tests that stub the bag: `test_gateway_img_gen_worker_semantic.py`, `test_gateway_img_gen_worker_malformed_body.py`, `test_gateway_img_gen_worker_edit_routing.py`, `test_gateway_quota_detection.py`. Each sets `mock_model.extra_headers = {"endpoint_path": …}`; they should set the field and leave the bag to the headers that belong in it.+- [x] Verify against the live payload that the key still parses into the field and that `x-portkey-config` still lands in `extra_headers` — a real boot, not only mocks.+- [x] Gates: targeted tests, `make tb`, stage + `make agent-check`.## Phase 2 — the shape guardGoal: an unknown per-model key is either a plausible header or a loud error, and never a silent outbound string. TDD throughout — each box's test lands red first.-- [ ] **Tests first (red):** new `tests/unit/pipelex/cogt/model_backends/test_model_spec_key_policy.py` — header-shaped key accepted; snake_case unknown rejected; D3 near-miss (`max-tokens`) rejected; known blueprint field never diverted.-- [ ] New `pipelex/cogt/model_backends/model_spec_keys.py` (D1): the pure classifier plus `ModelSpecSource` (D2).-- [ ] Wire it into `InferenceBackendLibrary.load` (`backend_library.py:195-199`), replacing the unconditional loop. Local source raises `InferenceBackendLibraryError` with D6's message; gateway source prunes.-- [ ] **Tests (red first):** a local backend TOML carrying a synthetic unknown snake_case key fails the load with a message naming the key, the model and the file; the same key in a remote payload is pruned and the boot survives. Extend `test_gateway_unknown_defaults.py` rather than starting a parallel module — it already owns the remote-tolerance story, including the no-log-hub constraint.-- [ ] **Regression, and the point of the whole change:** `x-portkey-provider` from local `portkey.toml` and `x-portkey-config` from the remote payload still reach `extra_headers` and still reach the wire.-- [ ] **Leniency interaction:** confirm what a rejected key does under `lenient=True`. A typo must not silently delete a backend — that is the existing ruling in `InferenceBackendLibrary.load`'s docstring, and this new raise sits inside the same `try`. Decide deliberately and record the answer here; if it needs to escape the lenient skip, say why in a comment at the raise site.-- [ ] **Mutation-check the new tests:** revert the guard, confirm the new tests go red, restore. A guard whose tests pass without it is not a guard.-- [ ] Gates: `make tb`, targeted tests, stage + `make agent-check`, **full `make agent-test`**.+- [x] **Tests first (red):** new `tests/unit/pipelex/cogt/model_backends/test_model_spec_key_policy.py` — header-shaped key accepted; snake_case unknown rejected; D3 near-miss (`max-tokens`) rejected; known blueprint field never diverted.+- [x] New `pipelex/cogt/model_backends/model_spec_keys.py` (D1): the pure classifier plus `ModelSpecSource` (D2).+- [x] Wire it into `InferenceBackendLibrary.load` (`backend_library.py:195-199`), replacing the unconditional loop. Local source raises `InferenceBackendLibraryError` with D6's message; gateway source prunes.+- [x] **Tests (red first):** a local backend TOML carrying a synthetic unknown snake_case key fails the load with a message naming the key, the model and the file; the same key in a remote payload is pruned and the boot survives. Extend `test_gateway_unknown_defaults.py` rather than starting a parallel module — it already owns the remote-tolerance story, including the no-log-hub constraint.+- [x] **Regression, and the point of the whole change:** `x-portkey-provider` from local `portkey.toml` and `x-portkey-config` from the remote payload still reach `extra_headers` and still reach the wire.+- [x] **Leniency interaction:** confirm what a rejected key does under `lenient=True`. A typo must not silently delete a backend — that is the existing ruling in `InferenceBackendLibrary.load`'s docstring, and this new raise sits inside the same `try`. Decide deliberately and record the answer here; if it needs to escape the lenient skip, say why in a comment at the raise site.+- [x] **Mutation-check the new tests:** revert the guard, confirm the new tests go red, restore. A guard whose tests pass without it is not a guard.+- [x] Gates: `make tb`, targeted tests, stage + `make agent-check`, **full `make agent-test`**.### ✋ CHECKPOINT — HARD STOP@@ -130,10 +130,10 @@ Do not start Phase 3 without Louis' explicit go. This is where a config that boo## Phase 3 — Docs, changelog, dogfood-- [ ] `docs/configuration/config-technical/inference-backend-config.md` — document the mechanism for the first time: extra per-model keys are sent to the provider as request headers, they must be header-shaped, anything else is a configuration error, and `endpoint_path` is a declared field. Include what a rejected key looks like.-- [ ] Changelog `## [Unreleased]`, condensed style, **breaking**: a per-model key that is neither a known model-spec field nor header-shaped now fails the backend load instead of being sent to the provider as a request header; `endpoint_path` is a declared model-spec field.-- [ ] Append a dogfood entry to `wip/drift-contracts/dogfood-log.md`. The observation worth recording: **`backend_library.py` shapes user-facing configuration and sits in no contract's trigger set** — the same shape of finding as the Phase 4 templating entry (a config surface documented outside `docs/configuration/`), from the other direction. Record it; per the pilot's bias, do not act on it here.-- [ ] Gates: stage + `make agent-check`.+- [x] `docs/configuration/config-technical/inference-backend-config.md` — document the mechanism for the first time: extra per-model keys are sent to the provider as request headers, they must be header-shaped, anything else is a configuration error, and `endpoint_path` is a declared field. Include what a rejected key looks like.+- [x] Changelog `## [Unreleased]`, condensed style, **breaking**: a per-model key that is neither a known model-spec field nor header-shaped now fails the backend load instead of being sent to the provider as a request header; `endpoint_path` is a declared model-spec field.+- [x] Append a dogfood entry to `wip/drift-contracts/dogfood-log.md`. The observation worth recording: **`backend_library.py` shapes user-facing configuration and sits in no contract's trigger set** — the same shape of finding as the Phase 4 templating entry (a config surface documented outside `docs/configuration/`), from the other direction. Record it; per the pilot's bias, do not act on it here.+- [x] Gates: stage + `make agent-check`.## Cross-repo / release-gated follow-ups@@ -149,4 +149,76 @@ Do not start Phase 3 without Louis' explicit go. This is where a config that boo## Checkpoint log-*(Filled in as the checkpoint is reached: status, decisions taken, open questions, state of the code.)*+### 2026-08-15 — Phase 1 and Phase 2 done, stopped at the ✋ checkpoint++**Branch and PR shape.** `feat/rogue-extra-headers-guard`, stacked on `fix/keyless-followups` (PR #1106), which is itself stacked on `fix/Keyless-dry-run` (PR #1104). Two commits, one per phase, so Phase 1 could ship alone if ever needed: "endpoint_path is a declared model-spec field, not an extra header" and "Unknown per-model backend keys are headers only if header-shaped". Opened as a draft PR because Phase 3 (docs, changelog, dogfood log) is not started.++**Re-measurement (2026-08-15).** Identical to the 2026-08-14 table: local `portkey.toml` carries `x-portkey-provider` per model and nothing else; the served `_12` payload carries `x-portkey-config` on every LLM model and `endpoint_path` on the four image models; the served `[defaults]` block is clean. The local `~/.pipelex/cache/remote_config.json` (`schema_version` / `cached_at` / `raw_config`, no source URL) was refreshed this morning, so this session did not reproduce the `_11`-body-under-a-`_12`-pin condition — but nothing in the change depends on it, and the remote path prunes rather than raises precisely so that condition stays harmless.++**What was built.**++- Phase 1: `endpoint_path: str | None = None` on `InferenceModelSpecBlueprint` and `InferenceModelSpec`, factory passthrough, `gateway_img_gen_worker.py` reads the field. The four image-worker tests set the field and leave `extra_headers` to headers. Verified with a real `Pipelex.make(needs_inference=False, needs_model_specs=True)` boot against the live payload: `gpt-image-1.endpoint_path` is the Azure route, `gpt-image-1.extra_headers == {'x-portkey-config': …}`, `gpt-4o-mini.endpoint_path is None`, and the local portkey model still carries `{'x-portkey-provider': '@openai'}`.+- Phase 2: `pipelex/cogt/model_backends/model_spec_keys.py` — `ModelSpecSource` (D2), `split_model_spec_keys` returning a `ModelSpecKeySplit(fields, headers, rejected)` NamedTuple, `RejectedModelSpecKey(key, near_miss_of)`, `describe_rejected_keys` for the wording. Fully keyword-only, no subject grant. `InferenceBackendLibrary.load` threads the source (`REMOTE_GATEWAY` on the `is_gateway_backend` branch, `LOCAL_FILE` otherwise) and does a `match`/`case`: local raises `InferenceBackendLibraryError`, remote prunes with no log call. `drop_unknown_gateway_defaults`'s docstring updated to point at the new per-model rule.+- Tests: `test_model_spec_key_policy.py` (classifier), three new cases in `test_backend_library_leniency.py` (unknown per-model key fatal in both modes naming key/model/file; near-miss fatal naming the field; `x-portkey-provider` still becomes a header), and a new `TestGatewayUnknownPerModelKeys` class (header kept, non-header pruned and boot survives, `endpoint_path` lands in the field, header reaches `GatewayFactory.make_extras`, prune needs no log hub).++**Gates.** `make tb`, `make agent-check` (staged), and the full `make agent-test` are all green. Mutation check done: with the guard replaced by the old "everything unknown is a header" behaviour, exactly the four guard tests go red; restored, all green.++**Answer to the leniency question.** A rejected key from a local file is fatal in *both* modes. No new mechanism was needed: the raise is an `InferenceBackendLibraryError` inside the same `try` as before, and the lenient `except` only catches `InferenceBackendCredentialsError`, so it lets this through — exactly the docstring's ruling ("a config typo must never silently delete a backend"). A comment at the raise site says so, and `test_an_unknown_per_model_key_in_a_local_backend_is_fatal_in_both_modes` is parametrized over `lenient`.++**Worked example of the error, as a user sees it** (a local `openai.toml` with `max_tokns = 4096` on `gpt-4o`):++> Unknown key on model 'gpt-4o' for backend 'openai' from file '.pipelex/inference/backends/openai.toml': 'max_tokns' is not a known model-spec field, and not header-shaped. A per-model key that is not a model-spec field is sent to the provider as a request header and must contain a hyphen (e.g. 'x-portkey-provider'): fix the typo, or name the key like a header if that is what it is meant to be.++The near-miss variant (`max-tokens = 4096`):++> Unknown key on model 'gpt-4o' for backend 'openai' from file '.pipelex/inference/backends/openai.toml': 'max-tokens' looks like the model-spec field 'max_tokens' spelled with hyphens — use 'max_tokens'. A per-model key that is not a model-spec field is sent to the provider as a request header and must contain a hyphen (e.g. 'x-portkey-provider'): fix the typo, or name the key like a header if that is what it is meant to be.++Several rejected keys on one model are listed in one message ("Unknown keys on model …: 'prompting_target' is …; 'max_tokns' is …"), with the rule stated once at the end.++**Awaiting Louis' rulings.**++- D3 (near-miss): built as planned; separable — dropping it removes `near_miss_of`, the second `describe` branch, and one test each in the classifier and leniency modules.+- Leniency: fatal in both modes, as above. Confirm.+- Commit/PR shape: two commits on one draft PR stacked on #1106. Confirm, or ask for a squash / a separate Phase 1 PR.++### 2026-08-15 — Louis' rulings, and Phase 3 done++**Rulings.** Leniency: **confirmed** — a rejected local key is fatal in both modes. D3 near-miss: **confirmed, kept**. PR shape: one PR (#1107), not a draft; two commits kept.++**Phase 3.** The docs page gained a "Sending extra request headers per model" subsection under Model Specifications — the mechanism's first documentation: the header rule, the shape requirement, the error as a user sees it, the lenient treatment of the served Gateway config, and `endpoint_path` as a declared field. Changelog: a condensed breaking entry under `[Unreleased]`, and the `prompting_target` removal entry's sentence about per-model keys becoming headers rewritten to the new truth. Dogfood log: recorded the "no contract has a stake in the backend-TOML schema" observation, paired with the 2026-08-14 scope-miss.++**Remaining:** nothing on this branch. The cross-repo / release-gated follow-ups below stand as written.++### 2026-08-15 — Review-bot pass on PR #1107++Three unresolved bot threads, two issues, both fixed. (1) codex + cubic: `TestGatewayUnknownPerModelKeys` shared a module with `TestGatewayUnknownDefaults`, against the one-TestClass-per-module rule — moved to its own `test_gateway_unknown_per_model_keys.py`. (2) cubic: a header-shaped key with a non-string value (`x-foo = 3`) fell through the classifier into strict `extra_headers: dict[str, str]`, so pydantic raised `string_type` — fatal for a *remote* payload too, which contradicts the skew-tolerance contract, and in pydantic's voice rather than D6's for a local file. The bot's suggested remedy (`str(value)`) was declined: stringifying `True` or a list onto the wire is the rogue header this branch exists to stop. Instead the value check joined the shape check: `RejectedModelSpecKey` now carries a `ModelSpecKeyRejection` reason (`NOT_HEADER_SHAPED` / `HYPHENATED_KNOWN_FIELD` / `NON_STRING_VALUE`), a non-string value is rejected like any other rogue key, and the loader's existing per-source `match` does the rest with no call-site change — local fatal naming key/model/file and saying the value must be a quoted string, remote pruned. The hyphen trailer in `describe_rejected_keys` is emitted only when a shape rejection is present, so a value-only failure is not told to add a hyphen. Tests red-first in the classifier, leniency and gateway per-model modules; docs page and changelog entry extended with the value half of the rule.++### 2026-08-15 — Review-bot pass on PR #1109++Five unresolved threads (one greptile, four cubic); four fixed, one deferred.++- **Fixed — near-miss got the hyphen trailer** (cubic, `describe_rejected_keys`). `HYPHENATED_KNOWN_FIELD` was grouped with `NOT_HEADER_SHAPED` under `is_about_shape`, so a lone `max-tokens` was told the key "must contain a hyphen … name the key like a header" right after being told to use `max_tokens` — the key already has a hyphen, and the advice contradicted its own message. The property is gone; only a `NOT_HEADER_SHAPED` rejection earns the trailer. Red-first test in the classifier module. The near-miss worked example in the Phase 1/2 checkpoint above therefore no longer carries the trailer.+- **Fixed — docs led with the old behaviour** (cubic, `inference-backend-config.md`). The subsection's first sentence said every extra key is sent as a header; it now states the gate up front, and the full rule paragraph follows unchanged.+- **Fixed — dogfood-log premise** (cubic, `wip/drift-contracts/dogfood-log.md`). The entry claimed the backend TOMLs are "neither the config model nor a shipped default"; they *are* shipped defaults (`pipelex/kit/configs/inference/backends/*.toml`, mirrored by the `.pipelex/` overrides). Reworded: the finding sharpens rather than dissolves — the contract's description promises "the shipped defaults" while its trigger set names only `pipelex/pipelex.toml`.+- **Fixed — stale "Superseded note"** (cubic, this file). The trailing paragraph reasserting Phase 3 as not done was an archived Phase 1/2 remark sitting after the Phase 3-done entries; deleted, since its one surviving fact (the `prompting_target` changelog sentence needed rewriting) is recorded in the rulings entry above.+- **Deferred — strict header-name/value validation** (greptile, `is_header_shaped`). h11 rejects an illegal name or value at send time, so it is a boot-vs-first-call timing gap for a deliberately quoted key, not a wire risk. Thread left open at the time; taken up the same day — see the entry below.++### 2026-08-15 — Strict header-name and header-value validation (the deferred greptile item, built)++Louis' ruling: close the gap now, at **wire parity** — boot rejects exactly what the HTTP stack rejects — landing as a third commit on PR #1109 so the thread closes where it was raised.++**The rule as built.** A key still has to be *shaped* like a header (contains a hyphen, string value) before anything else; the new gate asks whether it is *usable* as one. A header name must be an RFC 7230 token — letters, digits and `` !#$%&'*+-.^_`|~ `` — and a header value must be printable ASCII on a single line with no leading or trailing whitespace. Two new `ModelSpecKeyRejection` members carry it, `ILLEGAL_HEADER_NAME` and `ILLEGAL_HEADER_VALUE`, and `RejectedModelSpecKey` gained an `illegal_character` field so the name error can name the character — the failure is routinely invisible in the file (a pasted non-breaking space, a trailing space), which is the whole reason to say it out loud. `InferenceBackendLibrary.load` needed no edit at all: its per-source `match` already turns any rejection into a local fatal error or a remote prune, which is the payoff of D1 keeping the policy at the call site.++**Wire parity, measured not assumed.** Checked in the venv against h11 and httpx before writing the predicates: `x-foo bar`, `x-foo@bar`, `x-foo/bar`, `x-foo(bar)` and a non-ASCII name are refused (`LocalProtocolError: Illegal header name`, or `UnicodeEncodeError` from httpx); `a\r\nb`, a NUL, a leading space, a trailing space and a non-ASCII value are refused; `a b`, `a\tb`, the empty string, `x-foo_bar`, `x-foo.bar` and `x-foo|bar` are all accepted — underscore, dot and pipe are token characters, so the over-tightening trap has its own test. One deliberate divergence, recorded in the module docstring: h11 accepts `0x7f` (DEL) in a value and we do not. Deliberately **no** test couples our predicates to h11's own patterns — it is a transitive dependency of httpx, and the rule must not become "whatever this version of h11 does".++**Nothing in the wild moves.** Re-measured through the real classifier rather than a hand-rolled regex: every per-model key in `.pipelex/inference/backends/*.toml`, in the shipped `pipelex/kit/configs/inference/backends/*.toml`, and in the live `_12` payload still classifies exactly as before — `x-portkey-provider` and `x-portkey-config` accepted, nothing rejected. Confirmed by a real boot too (`Pipelex.make(needs_inference=False, needs_model_specs=True)`): the gateway models still carry `x-portkey-config`, `gpt-image-1.endpoint_path` still resolves to the Azure route, and the local Portkey model still carries `x-portkey-provider`.++**Worked examples, as a user sees them.**++> Unknown key on model 'gpt-4o' for backend 'openai' from file '.pipelex/inference/backends/openai.toml': 'x-foo bar' cannot be a header name: ' ' is not allowed in one — a header name may contain only letters, digits and the characters !#$%&'*+-.^_`|~.++> Unknown key on model 'gpt-4o' for backend 'openai' from file '.pipelex/inference/backends/openai.toml': 'x-foo' is header-shaped, but its value cannot be sent as a header value — it must be printable ASCII on a single line, with no leading or trailing whitespace.++Neither earns the hyphen trailer, and both have a test saying so: the key already has a hyphen, so "add a hyphen" would be the same contradiction the previous review pass removed from the near-miss message.++**Tests and mutation check.** New cases in all three modules that own this story — the classifier (`test_model_spec_key_policy.py`), the local-file fatal path (`test_backend_library_leniency.py`, including `x-foo = "trailing "`, valid TOML and invisible on the page), and the remote prune path (`test_gateway_unknown_per_model_keys.py`, where an illegal name or value is skew like any other and must not break the boot). Mutation check: with both new predicates stubbed to `return True`, exactly the new tests go red across the three modules and nothing else moves; restored, all green.