Skip to content

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

Rule `Concept[1]` the single form everywhere, at run time too (#1157)

Louis Choquel95708dbd3d10
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 99f6649d8..739fd2bee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@
### Changed
+- **`Concept[1]` is the single form everywhere, at run time too (Breaking)**: The language says a count of one is not a list — `Concept[1]` declares the same slot as `Concept`, with the count written out — and the contract, the schema render and the input-form descriptor all said so, but the runtime's memory shaper framed a `[1]` slot as a one-item list and the output resolution generated one. A consumer that rendered a form from the descriptor and submitted what it said was therefore refused by the shaper. The count now collapses to the single form at the two parsers and the one factory that build a multiplicity, so the value `1` no longer exists downstream: a `[1]` input takes the value itself and refuses a list exactly as a bare declaration does, a `[1]` output produces one object rather than a `ListContent` of one, a header's `Brief` and a definition's `Brief[1]` are one contract instead of a merge mismatch, and a presence marker beside a count of one (`Concept[1]?`) is accepted on inputs as it already was on outputs. A sequence declaring a plural output whose last step yields a count of one no longer validates — a count of one is the single form, and the single form does not fulfill a list expectation — so `is_multiplicity_compatible` answers `False` where it answered `True`. A run-time `output_multiplicity=1` override now means the single form rather than a one-item list, and a re-rendered ref is canonicalized — `Concept[1]` comes back as `Concept`, the other spelling of the same slot. The rule holds across the layers that restate it: the builder's spec validator accepts `Concept[1]?` inputs exactly as the blueprint does, an image-generation pipe declaring `Image[]` honors a run-time count of one instead of refusing it as unresolved, and the static absence-taint pass classifies a one-count step result as single the way the run path resolves it. A zero count is now refused where it is written — `Concept[0]` inputs fail blueprint and spec validation with "multiplicity must be at least 1", as outputs always did — instead of surfacing later as an uncaught parse error. See [Understanding multiplicity](building-methods/pipes/understanding-multiplicity.md).
- **`native.Html`'s `css_class` is optional (Breaking)**: Matching MTHDS v0.9.0, `HtmlContent.css_class` is now `str | None = None` and the pinned blueprint no longer marks the field required — an `Html` value is its markup, and the class is presentation a producer states when it has one. Composed HTML no longer fabricates an empty `css_class` to satisfy the model, JSON rendering omits an unset class instead of emitting an empty string, and structured output no longer forces a generating LLM to invent presentation data nobody asked for.
- **`native.Date` and `native.Html` are `object` nodes in the input-form descriptor (Breaking for descriptor consumers)**: The derivation moves both onto the standard's object arm, deriving `fields` from the pinned definitions like the other structured natives — a `Date` slot is an object with a required `date` and an optional `time` child, an `Html` slot an object with a required `inner_html` and an optional `css_class` — instead of the former `date` and `prose` scalars, which reported shapes the slots' own schemas rejected.
- **Input-form descriptor conformance fixes (Breaking for descriptor consumers)**: A description-only concept's `refines` now carries the authored chain alone (absent when nothing was authored) instead of a fabricated `native.Text` link the spec forbids reconstructing — text-valuedness still reaches the wire as `kind: "prose"`. And a list's `item` node no longer carries a `name` member: the spec states an item has no authored name, and the index labels entries.
@@ -15,7 +16,7 @@
- **`PresenceMarker`'s symbol grammar moved off the enum (Breaking)**: The marker enum is the standard's, so the three helpers that are this engine's `.mthds` suffix grammar rather than wire vocabulary became module-level functions in `pipelex/core/pipes/variable_multiplicity.py`: `PresenceMarker.from_symbol(...)` is `presence_from_symbol(symbol=...)`, `marker.symbol` is `presence_symbol(presence=marker)`, and `marker.is_force` is `is_force_presence(presence=marker)`, all keyword-only per this repo's convention. `is_optional` and `is_plain` stay properties on the enum, which the standard declares.
- **The input-form descriptor's item layer is a type of its own (Breaking for importers)**: The standard now splits the field union in two instead of carrying `name` as an optional slot on one shared base, and `pipelex/pipeline/input_form.py` re-exports both layers. `InputFormField` stays the named union, whose per-kind models (`TextField`, `ObjectField`, …) now require `name: str` rather than admitting `None`; the new `InputFormItem` union is their nameless counterpart (`TextItem`, `ObjectItem`, …), which is what a list's `item` holds and the only shape that position accepts. Two re-exported base classes were renamed with it: `InputFormFieldBase` is now `InputFormItemBase`, and `TextValuedFieldBase` is now `TextValuedItemBase`. **The wire is unchanged** — this engine already stopped emitting `name` on an item; what moved is that the rule is now the shape rather than a convention, so an item built with a name fails at construction and a consumer reading `field.name` gets a `str` with nothing to narrow.
- **Agent-rule refinement on `TypeAdapter`** (`pipelex/kit/agent_rules/python_standards.md`): the flat ban becomes a scoped one — don't design shapes that need a `TypeAdapter`, but validating into a top-level union or container owned by an external contract (a standard's wire model, a log stream of one-of-many event types) is its sanctioned use, as a module-level singleton. The input-form deriver's list-item conversion is exactly that case and keeps its adapter.
-- **Minimum `mthds` version**: The floor moves to `mthds>=0.11.0`, the releases carrying that split and the descriptor's coherence rules — a top-level field whose `required` contradicts its presence marker, one pairing `gating: true` with an optional marker, and a wire node spelling absence as an explicit `null` are now rejected at the parse, which gates this engine's emission at derivation time rather than on the wire. Everyone downstream of Pipelex inherits that floor.
+- **`mthds` is pinned exactly (Breaking for anyone who also depends on `mthds`)**: The dependency moves from a floor to `mthds==0.11.0`, the release carrying that split and the descriptor's coherence rules — a top-level field whose `required` contradicts its presence marker, one pairing `gating: true` with an optional marker, and a wire node spelling absence as an explicit `null` are now rejected at the parse, which gates this engine's emission at derivation time rather than on the wire. Everyone downstream of Pipelex inherits that exact version: a consumer that also depends on `mthds` must move in step with Pipelex rather than take an `mthds` release on its own.
## [v0.53.0] - 2026-08-25
diff --git a/docs/building-methods/pipes/provide-inputs.md b/docs/building-methods/pipes/provide-inputs.md
index d08a2e45b..b9ebae8e4 100644
--- a/docs/building-methods/pipes/provide-inputs.md
+++ b/docs/building-methods/pipes/provide-inputs.md
@@ -101,6 +101,7 @@ When an input is declared multiple (`Tag[]`, or a fixed count `Tag[3]`), provide
- An **empty** list is legal and produces an empty collection.
- A fixed count `Tag[3]` validates the number of items — too few or too many is a clear error.
- Providing a list where the signature declares a **single** value is a clear error (Pipelex won't silently pick one).
+- A count of one is the single form: `Tag[1]` takes the value itself, and a list there — even a one-item list — is the same error as under a bare `Tag`.
See [Understanding Multiplicity](understanding-multiplicity.md) for the full model of single items versus collections.
diff --git a/docs/building-methods/pipes/understanding-multiplicity.md b/docs/building-methods/pipes/understanding-multiplicity.md
index dd6831cc6..3abd1dae9 100644
--- a/docs/building-methods/pipes/understanding-multiplicity.md
+++ b/docs/building-methods/pipes/understanding-multiplicity.md
@@ -105,7 +105,7 @@ The pipe will extract however many line items appear in the invoice. A simple in
**3. Fixed output (bracket notation `[N]`)**
-Use a number in brackets to generate an exact number of items:
+Use a number in brackets to generate an exact number of items (a real list starts at `[2]` — see the note on `[1]` under the input side):
```toml
[concept]
@@ -232,6 +232,10 @@ Describe their similarities, differences, and relative strengths.
"""
```
+!!! note "A count of one is not a list"
+
+ `Concept[1]` declares a **single** instance, not a one-item list — it is the same slot as `Concept`, with the count written out. Nothing wraps such a value in an array, so a fixed count only ever means a real list when it is 2 or more. This holds everywhere the count appears: on an input, on an output, in the validate report, and at run time, where a `[1]` input takes the value itself and refuses a list exactly as a bare declaration does. `Concept[0]` is invalid.
+
## Practical Use Cases
### Use Case 1: Batch Processing with Variable Input
diff --git a/pipelex/builder/pipe/pipe_spec.py b/pipelex/builder/pipe/pipe_spec.py
index aca457f09..4b58b3065 100644
--- a/pipelex/builder/pipe/pipe_spec.py
+++ b/pipelex/builder/pipe/pipe_spec.py
@@ -14,6 +14,8 @@ from pipelex.core.concepts.validation import validate_concept_ref_or_code
from pipelex.core.pipes.variable_multiplicity import (
MULTIPLICITY_PATTERN,
is_force_presence,
+ is_multiple_multiplicity,
+ multiplicity_from_bracket_content,
parse_concept_with_multiplicity,
presence_from_symbol,
presence_symbol,
@@ -150,10 +152,16 @@ class PipeSpec(StructuredContent):
)
raise ValueError(msg)
- # Mirror the blueprint grammar rule (D1, D4): presence markers never combine with multiplicity
bracket_content = match.group(2)
+ if bracket_content and int(bracket_content) <= 0:
+ msg = f"Invalid input '{input_name}': '{concept_spec}'. Multiplicity must be at least 1."
+ raise ValueError(msg)
+
+ # Mirror the blueprint grammar rule (D1, D4): presence markers never combine with
+ # multiplicity — and `[1]` is the single form, not multiplicity, so it takes a marker.
presence = presence_from_symbol(symbol=match.group(3))
- if not presence.is_plain and bracket_content is not None:
+ multiplicity = multiplicity_from_bracket_content(bracket_content=bracket_content)
+ if not presence.is_plain and is_multiple_multiplicity(multiplicity=multiplicity):
msg = (
f"Invalid input '{input_name}': '{concept_spec}'. "
f"The presence marker '{presence_symbol(presence=presence)}' cannot be combined with multiplicity: "
diff --git a/pipelex/core/memory/input_shaper.py b/pipelex/core/memory/input_shaper.py
index 902cbd041..840d416f6 100644
--- a/pipelex/core/memory/input_shaper.py
+++ b/pipelex/core/memory/input_shaper.py
@@ -40,7 +40,7 @@ from pipelex.core.memory.exceptions import (
from pipelex.core.memory.working_memory import WorkingMemory
from pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs
from pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec
-from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity
+from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity, fixed_item_count, is_multiple_multiplicity
from pipelex.core.stuffs.exceptions import StuffContentFactoryError
from pipelex.core.stuffs.list_content import ListContent
from pipelex.core.stuffs.structured_content import StructuredContent
@@ -248,14 +248,13 @@ class InputShaper:
def _peel_multiplicity(cls, multiplicity: VariableMultiplicity | None) -> tuple[bool, int | None]:
"""Peel a declared multiplicity into ``(is_list, fixed_count)`` (D2).
- ``VariableMultiplicity`` is ``None | bool | int``; parsing only ever yields ``None`` (single),
- ``True`` (``X[]`` variable list), or an ``int N>=1`` (``X[N]`` fixed count). A genuine int is a
- fixed-count list, ``True`` a variable list, ``None`` singular. ``bool`` is a subclass of ``int``,
- so the int check must exclude it explicitly.
+ Both halves are the shared projection, not a local re-derivation: ``[]`` is a variable list,
+ ``[N]`` for ``N >= 2`` a fixed-count list carrying its count, and ``None`` — like ``[1]``, which
+ is the single form with its count written out — is singular. Deriving it here again is exactly
+ how this function once came to frame a ``[1]`` slot as a one-item list while the contract, the
+ schema and the descriptor beside it all ruled it single.
"""
- fixed_count = multiplicity if isinstance(multiplicity, int) and not isinstance(multiplicity, bool) else None
- is_list = multiplicity is True or fixed_count is not None
- return is_list, fixed_count
+ return is_multiple_multiplicity(multiplicity=multiplicity), fixed_item_count(multiplicity=multiplicity)
@classmethod
def _shape_with_multiplicity(
@@ -302,7 +301,7 @@ class InputShaper:
inputs_base_dir=inputs_base_dir,
)
- # Singular (multiplicity is None). A list here is ambiguous — hard error (D2).
+ # Singular (no multiplicity, or a count of one). A list here is ambiguous — hard error (D2).
if isinstance(value, list):
raise ListWhereSingularError.make(
variable_name=variable_name,
diff --git a/pipelex/core/pipes/inputs/input_stuff_specs_factory.py b/pipelex/core/pipes/inputs/input_stuff_specs_factory.py
index b080a4a81..43c7f6d21 100644
--- a/pipelex/core/pipes/inputs/input_stuff_specs_factory.py
+++ b/pipelex/core/pipes/inputs/input_stuff_specs_factory.py
@@ -8,7 +8,7 @@ from pipelex.core.concepts.validation import validate_concept_ref_or_code
from pipelex.core.pipes.inputs.exceptions import InputStuffSpecsFactoryError
from pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs, PipeInputsRoot
from pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec
-from pipelex.core.pipes.variable_multiplicity import presence_from_symbol
+from pipelex.core.pipes.variable_multiplicity import multiplicity_from_bracket_content, presence_from_symbol
if TYPE_CHECKING:
from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity
@@ -55,6 +55,7 @@ class InputStuffSpecsFactory:
- "domain.ConceptCode[]" -> multiplicity = True
- "domain.ConceptCode" -> multiplicity = None (single item, default)
- "ConceptCode[5]" -> multiplicity = 5 (resolved with domain)
+ - "ConceptCode[1]" -> multiplicity = None (a count of one IS the single form)
Args:
concept_provider: Resolves the parsed concept ref. Injected rather than looked up so this
@@ -95,15 +96,9 @@ class InputStuffSpecsFactory:
concept_ref_or_code=concept_ref_or_code,
)
- # Determine multiplicity
- multiplicity: VariableMultiplicity | None = None
-
- if multiplicity_str is not None: # Brackets were present
- if multiplicity_str == "": # Empty brackets []
- multiplicity = True
- else: # Number in brackets [5]
- multiplicity = int(multiplicity_str)
- # else: No brackets, multiplicity stays None
+ # The bracket suffix becomes a multiplicity in exactly one place, shared with the io-ref parser,
+ # so this factory cannot rule a `[N]` slot differently from the rest of the chain.
+ multiplicity: VariableMultiplicity | None = multiplicity_from_bracket_content(bracket_content=multiplicity_str)
concept = concept_provider.get_required_concept(concept_ref=concept_ref_with_domain)
return StuffSpec(concept=concept, multiplicity=multiplicity, presence=presence_from_symbol(symbol=marker_symbol))
diff --git a/pipelex/core/pipes/variable_multiplicity.py b/pipelex/core/pipes/variable_multiplicity.py
index a30f3f429..2206af156 100644
--- a/pipelex/core/pipes/variable_multiplicity.py
+++ b/pipelex/core/pipes/variable_multiplicity.py
@@ -19,6 +19,8 @@ __all__ = [
"is_multiple_multiplicity",
"is_multiplicity_compatible",
"make_variable_multiplicity",
+ "multiplicity_from_bracket_content",
+ "normalize_variable_multiplicity",
"parse_concept_with_multiplicity",
"presence_from_symbol",
"presence_symbol",
@@ -33,6 +35,40 @@ VariableMultiplicity = bool | int
MULTIPLICITY_PATTERN = r"^([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)(?:\[(\d*)\])?([?!])?$"
+def normalize_variable_multiplicity(*, multiplicity: VariableMultiplicity | None) -> VariableMultiplicity | None:
+ """Collapse a fixed count of one onto the single form the language says it already is.
+
+ `Concept[1]` declares the same slot as `Concept` — a count of one is a way of spelling the count
+ out, not a distinct multiplicity, and nothing wraps such a value in a list. Applying that here, at
+ every site that builds a multiplicity from authored syntax or from caller arguments, is what makes
+ the value `1` unrepresentable downstream: no consumer has to remember the rule, and none of them
+ can re-derive it differently.
+
+ `True` is left alone. `bool` is a subclass of `int` and `True == 1`, so a variable-length `[]` would
+ otherwise collapse the way `[1]` does. An out-of-range count (`0`, from a caller that did not go
+ through the parser) is left alone too: it is invalid, and silently repairing it would hide that.
+ """
+ if multiplicity is None or isinstance(multiplicity, bool):
+ return multiplicity
+ return None if multiplicity == 1 else multiplicity
+
+
+def multiplicity_from_bracket_content(*, bracket_content: str | None) -> VariableMultiplicity | None:
+ """The multiplicity an io-ref's bracket suffix denotes, already normalized.
+
+ The three arms of the suffix grammar: no brackets is a single item, `[]` a variable-length list,
+ `[N]` a fixed count — and `[1]` the single form, per `normalize_variable_multiplicity`. This is the
+ only place bracket text becomes a multiplicity value; `parse_concept_with_multiplicity` layers the
+ `N >= 1` rule on top, and callers that have already matched `MULTIPLICITY_PATTERN` themselves use
+ this rather than re-deriving the arms.
+ """
+ if bracket_content is None:
+ return None
+ if bracket_content == "":
+ return True
+ return normalize_variable_multiplicity(multiplicity=int(bracket_content))
+
+
def presence_from_symbol(*, symbol: str | None) -> PresenceMarker:
"""The presence marker an io-ref suffix symbol denotes: nothing is `plain`, `?` optional, `!` force.
@@ -95,10 +131,12 @@ def make_variable_multiplicity(*, nb_items: int | None, multiple_items: bool | N
3
>>> make_variable_multiplicity(nb_items=None, multiple_items=True)
True
- >>> make_variable_multiplicity(nb_items=None, multiple_items=False)
+ >>> print(make_variable_multiplicity(nb_items=None, multiple_items=False))
None
>>> make_variable_multiplicity(nb_items=0, multiple_items=True)
True
+ >>> print(make_variable_multiplicity(nb_items=1, multiple_items=True)) # a count of one is the single form
+ None
"""
variable_multiplicity: VariableMultiplicity | None
@@ -108,7 +146,7 @@ def make_variable_multiplicity(*, nb_items: int | None, multiple_items: bool | N
variable_multiplicity = True
else:
variable_multiplicity = None
- return variable_multiplicity
+ return normalize_variable_multiplicity(multiplicity=variable_multiplicity)
def is_multiple_multiplicity(*, multiplicity: VariableMultiplicity | None) -> bool:
@@ -149,6 +187,7 @@ def parse_concept_with_multiplicity(concept_ref_or_code: str) -> MultiplicityPar
- "ConceptName" -> (ConceptName, None, plain)
- "ConceptName[]" -> (ConceptName, True, plain)
- "ConceptName[5]" -> (ConceptName, 5, plain)
+ - "ConceptName[1]" -> (ConceptName, None, plain) — a count of one IS the single form
- "ConceptName?" -> (ConceptName, None, optional)
- "ConceptName!" -> (ConceptName, None, force)
- "domain.ConceptName" and any of the suffixes above on a qualified ref
@@ -157,6 +196,11 @@ def parse_concept_with_multiplicity(concept_ref_or_code: str) -> MultiplicityPar
context (blueprint input vs output validation) can reject them with a precise, typed error; the
D1 v1 rule that markers are mutually exclusive with multiplicity is NOT enforced here.
+ A fixed count of one collapses to the single form here (see `normalize_variable_multiplicity`), so
+ the value `1` never leaves the parser and no consumer downstream can frame a `[1]` slot as a
+ one-item list. The collapse is canonicalizing, not lossy in meaning: re-rendering a parsed
+ "ConceptName[1]" yields "ConceptName", the other spelling of the same slot.
+
Args:
concept_ref_or_code: Concept specification string with optional multiplicity brackets
and optional presence marker (order fixed: multiplicity then presence)
@@ -183,19 +227,12 @@ def parse_concept_with_multiplicity(concept_ref_or_code: str) -> MultiplicityPar
bracket_content = match.group(2)
marker_symbol = match.group(3)
- multiplicity: int | bool | None
- if bracket_content is None:
- # No brackets - single item
- multiplicity = None
- elif bracket_content == "":
- # Empty brackets [] - variable list
- multiplicity = True
- else:
- # Number in brackets [N] - fixed count
- multiplicity = int(bracket_content)
- if multiplicity <= 0:
- msg = f"Invalid multiplicity value in '{concept_ref_or_code}': multiplicity must be at least 1. A pipe must produce at least one output."
- raise PipeVariableMultiplicityError(msg)
+ # Group 2 is `\d*`: None (no brackets), "" (`[]`), or digits (`[N]`). Only the digit arm can be out
+ # of range, and it is refused before the suffix is projected onto a multiplicity.
+ if bracket_content and int(bracket_content) <= 0:
+ msg = f"Invalid multiplicity value in '{concept_ref_or_code}': multiplicity must be at least 1. A pipe must produce at least one output."
+ raise PipeVariableMultiplicityError(msg)
+ multiplicity = multiplicity_from_bracket_content(bracket_content=bracket_content)
return MultiplicityParseResult(
concept_ref_or_code=extracted_concept,
@@ -212,9 +249,11 @@ def is_multiplicity_compatible(*, source_multiplicity: VariableMultiplicity | No
compatible with the sequence's declared output multiplicity (target).
Compatibility rules:
+ - A fixed count of one is normalized to the single form on both sides before any of the rules below
- If target is None (single item), source must also be None
- - If target is True (variable list), source can be True OR any positive integer
- (a fixed count is compatible with a variable-length expectation)
+ - If target is True (variable list), source can be True OR any integer N >= 2
+ (a fixed count is compatible with a variable-length expectation; a count of one is the
+ single form and does not fulfill a list expectation)
- If target is an integer N (fixed count), source must be exactly N
Args:
@@ -239,7 +278,18 @@ def is_multiplicity_compatible(*, source_multiplicity: VariableMultiplicity | No
False
>>> is_multiplicity_compatible(source_multiplicity=None, target_multiplicity=True) # Single cannot fulfill list expectation
False
+ >>> is_multiplicity_compatible(source_multiplicity=1, target_multiplicity=None) # `[1]` IS the single form
+ True
+ >>> is_multiplicity_compatible(source_multiplicity=1, target_multiplicity=True) # ...so it is not a list
+ False
"""
+ # `[1]` is the single form (`normalize_variable_multiplicity`), so it must compare as one on both
+ # sides: a `[1]` step output fulfills a bare single declaration, and vice versa. Normalizing here
+ # rather than trusting the parser keeps this helper's answer the same for a caller that built the
+ # value itself.
+ source_multiplicity = normalize_variable_multiplicity(multiplicity=source_multiplicity)
+ target_multiplicity = normalize_variable_multiplicity(multiplicity=target_multiplicity)
+
# Case 1: Target expects single item (None)
if target_multiplicity is None:
return source_multiplicity is None
diff --git a/pipelex/libraries/contract_match.py b/pipelex/libraries/contract_match.py
index 0070f0245..4366a65e0 100644
--- a/pipelex/libraries/contract_match.py
+++ b/pipelex/libraries/contract_match.py
@@ -16,7 +16,7 @@ import re
from pipelex.core.concepts.concept_factory import ConceptFactory
from pipelex.core.concepts.native.concept_native import NativeConceptCode
-from pipelex.core.pipes.variable_multiplicity import MULTIPLICITY_PATTERN
+from pipelex.core.pipes.variable_multiplicity import MULTIPLICITY_PATTERN, multiplicity_from_bracket_content
from pipelex.core.qualified_ref import QualifiedRef
from pipelex.pipe_machinery.pipe_blueprint import PipeBlueprint
@@ -24,11 +24,16 @@ from pipelex.pipe_machinery.pipe_blueprint import PipeBlueprint
def _canonical_concept_spec(spec: str, *, domain_code: str) -> str:
"""Normalize a raw concept spec to a canonical identity string.
- The multiplicity suffix is preserved *verbatim as text* (``""`` / ``"[]"`` / ``"[N]"``), so
- ``Brief[]`` (variable-length list) and ``Brief[1]`` (exactly one item) stay distinct. Comparing
- the *parsed* multiplicity instead would conflate them: ``parse_concept_with_multiplicity`` maps
- ``[]`` to ``True`` and ``[1]`` to ``int 1``, and Python evaluates ``True == 1`` as true. Keeping
- the suffix as text also means a ``[0]`` spec compares as a literal rather than raising.
+ The multiplicity suffix is compared *as text* (``""`` / ``"[]"`` / ``"[N]"``), so ``Brief[]`` (a
+ variable-length list) never conflates with a fixed count. Comparing the *parsed* multiplicity
+ instead would: ``parse_concept_with_multiplicity`` maps ``[]`` to ``True``, and Python evaluates
+ ``True == 1`` as true. Keeping the suffix as text also means a ``[0]`` spec compares as a literal
+ rather than raising.
+
+ The one collapse the text comparison must apply is ``[1]``, which denotes the same slot as the bare
+ spelling — so a header's ``Brief`` and a definition's ``Brief[1]`` are one contract, not a mismatch.
+ The suffix is projected through the shared multiplicity rule to decide that, rather than tested for
+ the literal ``"1"``, so this function cannot come to rule a count differently from the parser.
The presence marker (``"?"`` / ``"!"``) is likewise preserved verbatim, so ``Brief`` and
``Brief?`` denote different contracts (D5: method-boundary signatures are explicit about
@@ -51,6 +56,8 @@ def _canonical_concept_spec(spec: str, *, domain_code: str) -> str:
concept_ref_or_code = match.group(1)
bracket_content = match.group(2) # None -> no brackets; "" -> "[]"; digits -> "[N]"
marker_symbol = match.group(3) or "" # None -> no marker; "?" / "!" kept verbatim
+ if bracket_content is not None and multiplicity_from_bracket_content(bracket_content=bracket_content) is None:
+ bracket_content = None # the suffix collapsed: `[1]` IS the bare spelling
suffix = ("" if bracket_content is None else f"[{bracket_content}]") + marker_symbol
if NativeConceptCode.is_native_concept_ref_or_code(concept_ref_or_code):
diff --git a/pipelex/pipe_controllers/absence_taint.py b/pipelex/pipe_controllers/absence_taint.py
index 008cd221f..355dd299b 100644
--- a/pipelex/pipe_controllers/absence_taint.py
+++ b/pipelex/pipe_controllers/absence_taint.py
@@ -24,6 +24,7 @@ from pydantic.dataclasses import dataclass
from pipelex.core.pipes.inputs.input_stuff_specs import NamedStuffSpec
from pipelex.core.pipes.variable_multiplicity import PresenceMarker, VariableMultiplicity
from pipelex.pipe_machinery.pipe_abstract import PipeAbstract
+from pipelex.pipe_run.pipe_run_params import output_multiplicity_to_apply
@dataclass(frozen=True)
@@ -140,8 +141,17 @@ def is_plural_step_result(
) -> bool:
"""Whether a step's result slot is plural — a plural result is never tainted (D4:
a lifted plural output is the empty list; a batched step compacts).
+
+ Plurality is resolved exactly like the run path resolves it (declared multiplicity + the
+ step-level override), so the static promise matches what a lifted execution records: a count
+ of one — on either side — is the single form, not a one-item list.
"""
- return has_batch_params or step_output_multiplicity is not None or pipe.output.multiplicity is not None
+ if has_batch_params:
+ return True
+ return output_multiplicity_to_apply(
+ base_multiplicity=pipe.output.multiplicity,
+ override_multiplicity=step_output_multiplicity,
+ ).is_multiple_outputs_enabled
def effective_consumption_presence(*, pipe: PipeAbstract, named_stuff_spec: NamedStuffSpec) -> PresenceMarker:
diff --git a/pipelex/pipe_controllers/parallel/pipe_parallel.py b/pipelex/pipe_controllers/parallel/pipe_parallel.py
index 38a4ed78c..e3059dd60 100644
--- a/pipelex/pipe_controllers/parallel/pipe_parallel.py
+++ b/pipelex/pipe_controllers/parallel/pipe_parallel.py
@@ -34,7 +34,7 @@ from pipelex.pipe_controllers.absence_taint import (
from pipelex.pipe_controllers.pipe_controller import PipeController
from pipelex.pipe_controllers.sub_pipe import SubPipe
from pipelex.pipe_machinery.pipe_abstract import CompanionSlot
-from pipelex.pipe_run.pipe_run_params import PipeRunParams
+from pipelex.pipe_run.pipe_run_params import PipeRunParams, output_multiplicity_to_apply
from pipelex.system.job_metadata import JobMetadata
from pipelex.tools.misc.string_utils import get_root_from_dotted_path
from pipelex.validation_error_types import PipeValidationErrorType
@@ -371,7 +371,7 @@ class PipeParallel(PipeController):
Conservative by design: fields whose annotation is not a plain StuffContent
subclass (primitives from .mthds-generated structures, Optionals, unions) and
- list-producing branches are skipped rather than guessed at.
+ branches whose RESOLVED result is plural are skipped rather than guessed at.
"""
for sub_pipe in self.parallel_sub_pipes:
if not sub_pipe.output_name or sub_pipe.output_name not in structure_class.model_fields:
@@ -380,8 +380,14 @@ class PipeParallel(PipeController):
if not isinstance(field_annotation, type) or not issubclass(field_annotation, StuffContent):
continue
branch_pipe = get_required_pipe(pipe_code=sub_pipe.pipe_code)
- if branch_pipe.output.multiplicity is not None:
- # A list-producing branch combines as a ListContent, not as the item class.
+ if output_multiplicity_to_apply(
+ base_multiplicity=branch_pipe.output.multiplicity,
+ override_multiplicity=sub_pipe.output_multiplicity,
+ ).is_multiple_outputs_enabled:
+ # A list-producing branch combines as a ListContent, not as the item class. Plurality
+ # is the run path's answer (declaration + step override), not the declaration alone:
+ # a `nb_output = 1` step on a plural branch yields the single form, and reading only
+ # the declaration would skip a check the runtime then fails in `combine_stuffs`.
continue
try:
branch_structure_class = get_concept_library().get_structure_class(concept=branch_pipe.output.concept)
diff --git a/pipelex/pipe_controllers/sequence/pipe_sequence.py b/pipelex/pipe_controllers/sequence/pipe_sequence.py
index bcd721f43..b4f1bf273 100644
--- a/pipelex/pipe_controllers/sequence/pipe_sequence.py
+++ b/pipelex/pipe_controllers/sequence/pipe_sequence.py
@@ -10,7 +10,7 @@ from pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs
from pipelex.core.pipes.inputs.input_stuff_specs_factory import InputStuffSpecsFactory
from pipelex.core.pipes.pipe_output import PipeOutput
from pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec
-from pipelex.core.pipes.variable_multiplicity import PresenceMarker, is_multiplicity_compatible
+from pipelex.core.pipes.variable_multiplicity import PresenceMarker, VariableMultiplicity, is_multiplicity_compatible
from pipelex.core.qualified_ref import QualifiedRef
from pipelex.interpreter_hub import get_concept_library, get_optional_pipe, get_required_pipe
from pipelex.pipe_controllers.absence_taint import (
@@ -25,7 +25,7 @@ from pipelex.pipe_controllers.parallel.pipe_parallel import PipeParallel
from pipelex.pipe_controllers.pipe_controller import PipeController
from pipelex.pipe_controllers.sequence.exceptions import PipeSequenceValueError
from pipelex.pipe_controllers.sub_pipe import SubPipe
-from pipelex.pipe_run.pipe_run_params import PipeRunParams
+from pipelex.pipe_run.pipe_run_params import PipeRunParams, output_multiplicity_to_apply
from pipelex.system.job_metadata import JobMetadata
from pipelex.tools.misc.string_utils import get_root_from_dotted_path
from pipelex.validation_error_types import PipeValidationErrorType
@@ -76,21 +76,37 @@ class PipeSequence(PipeController):
return
last_step_pipe = get_required_pipe(pipe_code=last_step_pipe_code)
- effective_last_step_output_multiplicity = last_sub_pipe.output_multiplicity
- if not effective_last_step_output_multiplicity:
- effective_last_step_output_multiplicity = last_step_pipe.output.multiplicity
+ # The step's effective output, resolved exactly the way the run path resolves it (declared
+ # multiplicity + the step-level override), so this static promise cannot rule a count
+ # differently from the execution it describes. Reading the two apart — an override tested for
+ # truthiness, a declaration tested for `is None` — is what let a `nb_output = 1` step read as
+ # plural here while the runtime made it single.
+ multiplicity_resolution = output_multiplicity_to_apply(
+ base_multiplicity=last_step_pipe.output.multiplicity,
+ override_multiplicity=last_sub_pipe.output_multiplicity,
+ )
+ is_plural_last_step_output = multiplicity_resolution.is_multiple_outputs_enabled
+ # A declaration spells a singular slot with no suffix at all; `resolved_multiplicity` spells a
+ # forced single as `False`, which is override vocabulary and renders as nothing an author writes.
+ effective_last_step_output_multiplicity: VariableMultiplicity | None
+ if not is_plural_last_step_output:
+ effective_last_step_output_multiplicity = None
+ elif multiplicity_resolution.specific_output_count is not None:
+ effective_last_step_output_multiplicity = multiplicity_resolution.specific_output_count
+ else:
+ effective_last_step_output_multiplicity = True
taint_analysis = self.analyze_taint()
# The last step's effective output in bundle representation — what the sequence's declared
# output should be. This is the enriched semantic fact the fix planner needs, rendered the
- # way an author in the sequence's domain would write it, with the effective multiplicity
- # (sub-pipe override wins) and boundary presence. A singular sequence boundary remains
+ # way an author in the sequence's domain would write it, with the resolved multiplicity
+ # and boundary presence. A singular sequence boundary remains
# optional when its declaration, last step, or taint propagation says it may be absent.
# Plural outputs must stay plain because the grammar forbids combining multiplicity with
# a presence marker and represents an absent plural result as an empty list.
expected_output_presence = PresenceMarker.PLAIN
- if effective_last_step_output_multiplicity is None and (
+ if not is_plural_last_step_output and (
self.output.presence.is_optional or last_step_pipe.output.presence.is_optional or taint_analysis.output_taint is not None
):
expected_output_presence = PresenceMarker.OPTIONAL
diff --git a/pipelex/pipe_controllers/sub_pipe.py b/pipelex/pipe_controllers/sub_pipe.py
index 0505fbcc4..a3b36ff40 100644
--- a/pipelex/pipe_controllers/sub_pipe.py
+++ b/pipelex/pipe_controllers/sub_pipe.py
@@ -40,7 +40,11 @@ class SubPipe(BaseModel):
sub_pipe_run_params: PipeRunParams,
library_crate: "LibraryCrate | None" = None,
) -> PipeOutput:
- if self.output_multiplicity:
+ # `is not None`, not truthiness: `False` (force single) and `0` are overrides a step can
+ # carry, and dropping them here would let the run path inherit the caller's multiplicity
+ # while `is_plural_step_result` — which hands this same value to the shared resolution —
+ # promised the step's own answer.
+ if self.output_multiplicity is not None:
sub_pipe_run_params.output_multiplicity = self.output_multiplicity
sub_pipe = get_required_pipe(pipe_code=self.pipe_code)
diff --git a/pipelex/pipe_machinery/pipe_blueprint.py b/pipelex/pipe_machinery/pipe_blueprint.py
index 47fefe4a0..8238b8ba9 100644
--- a/pipelex/pipe_machinery/pipe_blueprint.py
+++ b/pipelex/pipe_machinery/pipe_blueprint.py
@@ -13,6 +13,8 @@ from pipelex.core.pipes.variable_multiplicity import (
MULTIPLICITY_PATTERN,
PipeVariableMultiplicityError,
is_force_presence,
+ is_multiple_multiplicity,
+ multiplicity_from_bracket_content,
parse_concept_with_multiplicity,
presence_from_symbol,
presence_symbol,
@@ -369,11 +371,19 @@ class PipeBlueprint(ABC, BaseModel):
)
raise ValueError(msg)
- # D1/D4: presence markers are mutually exclusive with multiplicity — a plural slot's
- # "nothing" is the empty list, so there is nothing for `?` or `!` to say.
bracket_content = match.group(2)
+ if bracket_content and int(bracket_content) <= 0:
+ msg = f"Invalid input '{input_name}': '{concept_spec}'. Multiplicity must be at least 1."
+ raise ValueError(msg)
+
+ # D1/D4: presence markers are mutually exclusive with multiplicity — a plural slot's
+ # "nothing" is the empty list, so there is nothing for `?` or `!` to say. A `[1]` slot
+ # is not plural: it is the single form with its count written out, so it takes a marker
+ # exactly as a bare ref does. Reading the projection rather than the bracket text is
+ # what keeps this in step with the output half, which parses before it decides.
presence = presence_from_symbol(symbol=match.group(3))
- if not presence.is_plain and bracket_content is not None:
+ multiplicity = multiplicity_from_bracket_content(bracket_content=bracket_content)
+ if not presence.is_plain and is_multiple_multiplicity(multiplicity=multiplicity):
msg = (
f"Invalid input '{input_name}': '{concept_spec}'. "
f"The presence marker '{presence_symbol(presence=presence)}' cannot be combined with multiplicity: "
diff --git a/pipelex/pipe_operators/img_gen/pipe_img_gen.py b/pipelex/pipe_operators/img_gen/pipe_img_gen.py
index ea0d5af2a..5506162c2 100644
--- a/pipelex/pipe_operators/img_gen/pipe_img_gen.py
+++ b/pipelex/pipe_operators/img_gen/pipe_img_gen.py
@@ -209,18 +209,17 @@ class PipeImgGen(PipeOperator[PipeImgGenOutput]):
log.verbose(f"Using img_gen handle: {img_gen_setting.model}")
nb_images: int
- if isinstance(applied_output_multiplicity, bool):
- if self.output_multiplicity is True:
- msg = "Cannot guess how many images to generate if multiplicity is just True."
- msg += f" Got PipeImgGen.output_multiplicity = {self.output_multiplicity},"
- msg += f" and pipe_run_params.output_multiplicity = {pipe_run_params.output_multiplicity}."
- msg += f" Tried to apply applied_output_multiplicity = {applied_output_multiplicity}."
- raise PipeRunParamsError(msg)
+ if applied_output_multiplicity is True:
+ # Only a RESOLVED "model decides" is unguessable — a forced-single resolution (False),
+ # e.g. from an override of 1, is one image even when the pipe declares `Image[]`.
+ msg = "Cannot guess how many images to generate if multiplicity is just True."
+ msg += f" Got PipeImgGen.output_multiplicity = {self.output_multiplicity},"
+ msg += f" and pipe_run_params.output_multiplicity = {pipe_run_params.output_multiplicity}."
+ raise PipeRunParamsError(msg)
+ if isinstance(applied_output_multiplicity, bool) or applied_output_multiplicity is None:
nb_images = 1
- elif isinstance(applied_output_multiplicity, int):
- nb_images = applied_output_multiplicity
else:
- nb_images = 1
+ nb_images = applied_output_multiplicity
# Resolved here rather than inside the kernel: turning a concept into a class is a library's
# business, and handing the class over is what spares the kernel a registry read.
diff --git a/pipelex/pipe_run/pipe_run_params.py b/pipelex/pipe_run/pipe_run_params.py
index 3184b95db..e5cd40111 100644
--- a/pipelex/pipe_run/pipe_run_params.py
+++ b/pipelex/pipe_run/pipe_run_params.py
@@ -7,7 +7,11 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
from pipelex import log
from pipelex.cogt.content_generation.cogt_run_params import CogtRunParams, check_mock_usage_requires_dry
from pipelex.core.memory.working_memory import BATCH_ITEM_STUFF_NAME, MAIN_STUFF_NAME
-from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity, VariableMultiplicityResolution
+from pipelex.core.pipes.variable_multiplicity import (
+ VariableMultiplicity,
+ VariableMultiplicityResolution,
+ normalize_variable_multiplicity,
+)
from pipelex.pipeline.exceptions import PipeStackOverflowError
from pipelex.system.pipe_run_mode import PipeRunMode
from pipelex.system.pipe_run_param_key import PipeRunParamKey
@@ -29,18 +33,19 @@ def output_multiplicity_to_apply(
Args:
base_multiplicity: Base multiplicity setting (from pipe definition).
- None: Single output (default)
+ - 1: Single output — a count of one is the single form, not a one-item list
- True: Multiple outputs (LLM decides count)
- int: Specific number of outputs
override_multiplicity: Override multiplicity setting (from runtime params).
- None: Use base value
- True: Enable multiple outputs
- False: Force single output (disable multiplicity)
- - int: Specific number of outputs
+ - int: Specific number of outputs (1 forces the single form, like False)
Returns:
- OutputMultiplicityResolution: Structured result containing:
+ VariableMultiplicityResolution: Structured result containing:
- resolved_multiplicity: The final multiplicity value to use
- - enable_multiple_outputs: True if multiple outputs should be generated
+ - is_multiple_outputs_enabled: True if multiple outputs should be generated
- specific_output_count: Exact number of outputs if specified, None otherwise
Resolution Logic:
@@ -48,19 +53,27 @@ def output_multiplicity_to_apply(
- If override is False: Force single output regardless of base
- If override is True: Enable multiple outputs, preserve base count if it's int
- If override is int: Use override count, enable multiple outputs
+ - If base or override is 1: the single form — a count of one is not a list
Examples:
>>> result = output_multiplicity_to_apply(base_multiplicity=None, override_multiplicity=None)
- >>> (result.resolved_multiplicity, result.enable_multiple_outputs, result.specific_output_count)
+ >>> (result.resolved_multiplicity, result.is_multiple_outputs_enabled, result.specific_output_count)
(None, False, None)
>>> result = output_multiplicity_to_apply(base_multiplicity=True, override_multiplicity=None)
- >>> (result.resolved_multiplicity, result.enable_multiple_outputs, result.specific_output_count)
+ >>> (result.resolved_multiplicity, result.is_multiple_outputs_enabled, result.specific_output_count)
(True, True, None)
>>> result = output_multiplicity_to_apply(base_multiplicity=3, override_multiplicity=None)
- >>> (result.resolved_multiplicity, result.enable_multiple_outputs, result.specific_output_count)
+ >>> (result.resolved_multiplicity, result.is_multiple_outputs_enabled, result.specific_output_count)
(3, True, 3)
"""
+ # `[1]` is the single form, so a base count of one is no multiplicity at all.
+ base_multiplicity = normalize_variable_multiplicity(multiplicity=base_multiplicity)
+ # A caller asking at run time for exactly one output is asking for that same single form — spelled
+ # `False` (force single) on this side, since `None` here means "no override" instead.
+ if override_multiplicity is not None and normalize_variable_multiplicity(multiplicity=override_multiplicity) is None:
+ override_multiplicity = False
+
# Case 1: No override provided - use base value as-is
if override_multiplicity is None:
if isinstance(base_multiplicity, bool):
diff --git a/pyproject.toml b/pyproject.toml
index ba8ea58ae..1ca4b9ef5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -31,7 +31,7 @@ dependencies = [
"json2html>=1.3.0",
"kajson==0.7.0",
"markdown>=3.6",
- "mthds>=0.11.0",
+ "mthds==0.11.0",
"networkx>=3.4.2",
"openai>=2.0.0",
"opentelemetry-api",
diff --git a/tests/integration/pipelex/pipeline/test_input_form.py b/tests/integration/pipelex/pipeline/test_input_form.py
index 4308754cc..a52c67dd8 100644
--- a/tests/integration/pipelex/pipeline/test_input_form.py
+++ b/tests/integration/pipelex/pipeline/test_input_form.py
@@ -25,10 +25,19 @@ from typing import TYPE_CHECKING, Any, cast
import pytest
from pydantic import Field
+from pipelex.core.memory.exceptions import ListWhereSingularError
+from pipelex.core.memory.input_shaper import InputShaper, PipelineInputs
+from pipelex.core.stuffs.list_content import ListContent
from pipelex.core.stuffs.structured_content import StructuredContent
-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_library
+from pipelex.interpreter_hub import (
+ clear_current_library,
+ get_concept_library,
+ get_current_library_id_or_none,
+ get_library_manager,
+ set_current_library,
+)
from pipelex.pipeline.input_form import FieldKind, InputFormField, build_input_form
-from pipelex.pipeline.pipe_io_contracts import build_pipe_io_contracts
+from pipelex.pipeline.pipe_io_contracts import IOMultiplicity, build_pipe_io_contracts
from pipelex.pipeline.validate_bundle import validate_bundle
from pipelex.system.registries.class_registry_access import get_class_registry
from tests.helpers.input_form import fields_by_name
@@ -540,6 +549,27 @@ prompt = \"\"\"
"""
+_ONE_SLOT_MTHDS = """
+domain = "one_slot"
+description = "A single `[1]` slot, for pinning that every surface rules it the same way"
+
+[concept.Gadget]
+description = "A gadget"
+
+[concept.Gadget.structure]
+name = { type = "text", description = "The gadget name", required = true }
+
+[pipe.take_one]
+type = "PipeLLM"
+description = "Take exactly one gadget"
+inputs = { one = "Gadget[1]" }
+output = "Text"
+prompt = \"\"\"
+@one
+\"\"\"
+"""
+
+
@pytest.mark.asyncio(loop_scope="class")
class TestKindAssignmentTable:
async def _derive_kind_table(self, load_empty_library: Callable[[], str]) -> dict[str, PipeInputFormDescriptor]:
@@ -584,6 +614,44 @@ class TestKindAssignmentTable:
assert one.required is True
assert one.gating is True
+ async def test_a_fixed_count_of_one_is_ruled_the_same_way_by_every_surface(self, load_empty_library: Callable[[], str]) -> None:
+ """The descriptor, the wire contract and the memory shaper agree that a `[1]` slot is single.
+
+ They once did not: the descriptor and the contract published `single` while the shaper framed
+ the payload as a one-item list, so a form rendered faithfully on the descriptor submitted a value
+ the shaper refused. Each surface pinned on its own can drift into that again and stay green,
+ which is why the agreement is asserted here in one place. The payload is exactly what the
+ descriptor node describes.
+ """
+ outer_library_id = load_empty_library()
+ try:
+ result = await validate_bundle(mthds_contents=[_ONE_SLOT_MTHDS])
+
+ descriptor_node = _field_by_name(build_input_form(result.pipes)["one_slot.take_one"], "one")
+ contract_input = build_pipe_io_contracts(result.pipes)["one_slot.take_one"].inputs["one"]
+ take_one_pipe = {pipe.pipe_ref: pipe for pipe in result.pipes}["one_slot.take_one"]
+
+ assert descriptor_node.kind == FieldKind.OBJECT, "the descriptor asks for one value"
+ assert contract_input.multiplicity == IOMultiplicity.SINGLE, "the contract publishes the single arm"
+ assert contract_input.item_count is None
+
+ # The shaper takes what those two describe: the object itself, with no list around it.
+ working_memory = InputShaper.shape(
+ {"one": {"name": "widget"}},
+ input_specs=take_one_pipe.inputs,
+ concept_provider=get_concept_library(),
+ )
+ content = working_memory.root["one"].content
+ assert not isinstance(content, ListContent), "the runtime frames a `[1]` slot as the item, never a one-item list"
+ assert content.model_dump() == {"name": "widget"}
+
+ # And it refuses a list there on the same grounds a bare declaration does.
+ list_payload = cast("PipelineInputs", {"one": [{"name": "widget"}]})
+ with pytest.raises(ListWhereSingularError):
+ InputShaper.shape(list_payload, input_specs=take_one_pipe.inputs, concept_provider=get_concept_library())
+ finally:
+ _teardown_validation_library(outer_library_id)
+
async def test_an_authored_but_empty_structure_table_is_an_object_with_no_fields(self, load_empty_library: Callable[[], str]) -> None:
"""The engine branches on `structure is not None` (`ConceptFactory`), so an empty `[concept.X.structure]`
table is backed by a field-less structured model whose schema is `{"type": "object", "properties": {}}`.
diff --git a/tests/integration/pipelex/pipeline/test_sequence_output_enrichment.py b/tests/integration/pipelex/pipeline/test_sequence_output_enrichment.py
index 037427ede..97b2ea12a 100644
--- a/tests/integration/pipelex/pipeline/test_sequence_output_enrichment.py
+++ b/tests/integration/pipelex/pipeline/test_sequence_output_enrichment.py
@@ -174,6 +174,30 @@ steps = [
]
"""
+_ONE_COUNT_STEP_ON_TAINTED_BOUNDARY_MTHDS = """
+domain = "seqfix_one_count_boundary"
+main_pipe = "make_summary"
+
+[concept]
+Summary = "A summary."
+
+[pipe.write_summary]
+type = "PipeLLM"
+description = "Summarize text."
+inputs = { text = "Text" }
+output = "Summary"
+prompt = "Summarize $text"
+
+[pipe.make_summary]
+type = "PipeSequence"
+description = "Lift over optional input, last step carrying a count of one, wrong output concept."
+inputs = { text = "Text?" }
+output = "Number?"
+steps = [
+ { pipe = "write_summary", result = "summary", nb_output = 1 },
+]
+"""
+
async def _enriched_error_data_for(
mthds_content: str,
@@ -269,3 +293,22 @@ class TestSequenceOutputEnrichment:
)
assert error_data.pipe_code == "make_ideas"
assert error_data.expected_output_ref == "Idea[3]"
+
+ async def test_a_one_count_step_keeps_the_optional_boundary_in_expected_ref(
+ self,
+ load_empty_library: Callable[[], str],
+ ) -> None:
+ """`nb_output = 1` is the single form, so the hint must read `Summary?`, never `Summary[1]`.
+
+ The count is resolved the way the run path resolves it, so this step is singular and its
+ boundary keeps the `?` the taint requires. Reading the override as plural — which testing it
+ for `is None` did — produced a `Summary[1]` the fix planner writes straight into the bundle
+ (`SetKeyOp` on `output`), dropping the marker and leaving the repaired bundle invalid.
+ """
+ load_empty_library()
+ error_data = await _enriched_error_data_for(
+ _ONE_COUNT_STEP_ON_TAINTED_BOUNDARY_MTHDS,
+ error_type=PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT,
+ )
+ assert error_data.pipe_code == "make_summary"
+ assert error_data.expected_output_ref == "Summary?"
diff --git a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_output_validation.py b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_output_validation.py
index b52b2ef4d..c67aeff4d 100644
--- a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_output_validation.py
+++ b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_output_validation.py
@@ -88,6 +88,47 @@ _CONCEPT_DESCRIPTION_ONLY = """
description = "A description-only concept (implicitly text-shaped)"
"""
+# A branch whose declared output is plural but whose step carries a count of one: the resolved
+# result is a single `PvAlt`, which the `tone_result` field (a `PvTone`) cannot hold. Reading the
+# declaration alone skipped this check and let the mismatch reach `combine_stuffs` at run time.
+_ONE_COUNT_PLURAL_BRANCH = """
+[concept.PvTone]
+description = "A tone reading"
+
+[concept.PvTone.structure]
+label = { type = "text", description = "The tone label", required = true }
+
+[concept.PvAlt]
+description = "Something a PvTone field cannot hold"
+
+[concept.PvAlt.structure]
+other = { type = "text", description = "An unrelated field", required = true }
+
+[concept.PvComboTyped]
+description = "Combined results whose fields are concept-typed"
+
+[concept.PvComboTyped.structure]
+tone_result = { type = "concept", concept_ref = "PvTone", description = "Tone", required = true }
+length_result = { type = "text", description = "Length", required = true }
+
+[pipe.pv_branch_plural_alt]
+type = "PipeLLM"
+description = "Branch declaring a plural output"
+inputs = { item = "PvItem" }
+output = "PvAlt[]"
+prompt = "Describe $item"
+
+[pipe.pv_parallel_one_count]
+type = "PipeParallel"
+description = "Parallel whose plural branch carries a count of one"
+inputs = { item = "PvItem" }
+output = "PvComboTyped"
+branches = [
+ { pipe = "pv_branch_plural_alt", result = "tone_result", nb_output = 1 },
+ { pipe = "pv_branch_length", result = "length_result" },
+]
+"""
+
def _bundle(*, output: str, extra_concepts: str = "") -> str:
return _BUNDLE_HEADER + extra_concepts + _PARALLEL_TEMPLATE.format(output=output)
@@ -136,3 +177,14 @@ class TestPipeParallelOutputValidation:
with pytest.raises(PipeValidationError) as exc_info:
acquire_library(library_id=f"pv_reject_{test_id}", mthds_contents=[mthds_content])
assert expected_fragment in str(exc_info.value)
+
+ def test_a_one_count_plural_branch_is_type_checked(self):
+ """A plural branch with `nb_output = 1` resolves to the single form, so its type IS checked.
+
+ Plurality is the run path's answer (declaration + step override). Skipping on the
+ declaration alone let an incompatible singular result pass `/validate` and fail later in
+ `StuffFactory.combine_stuffs`.
+ """
+ with pytest.raises(PipeValidationError) as exc_info:
+ acquire_library(library_id="pv_reject_one_count_plural_branch", mthds_contents=[_BUNDLE_HEADER + _ONE_COUNT_PLURAL_BRANCH])
+ assert "tone_result" in str(exc_info.value)
diff --git a/tests/integration/pipelex/pipes/operator/pipe_img_gen/test_pipe_img_gen_run.py b/tests/integration/pipelex/pipes/operator/pipe_img_gen/test_pipe_img_gen_run.py
index e023a1d5a..8b29271bd 100644
--- a/tests/integration/pipelex/pipes/operator/pipe_img_gen/test_pipe_img_gen_run.py
+++ b/tests/integration/pipelex/pipes/operator/pipe_img_gen/test_pipe_img_gen_run.py
@@ -4,11 +4,14 @@ import pytest
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.list_content import ListContent
from pipelex.core.stuffs.stuff_factory import StuffFactory
from pipelex.interpreter_hub import get_pipe_router
from pipelex.pipe_machinery.pipe_factory import PipeFactory
from pipelex.pipe_operators.img_gen.pipe_img_gen import PipeImgGen
from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint
+from pipelex.pipe_run.exceptions import PipeRunParamsError
from pipelex.pipe_run.pipe_job_factory import PipeJobFactory
from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory
from pipelex.system.job_metadata import JobMetadata
@@ -91,3 +94,65 @@ class TestPipeImgGenRun:
await get_pipe_router().run(
pipe_job=pipe_job,
)
+
+ async def test_pipe_img_gen_variable_output_single_override(
+ self,
+ job_metadata: JobMetadata,
+ pipe_run_mode: PipeRunMode,
+ img_gen_combo: ModelCombo,
+ load_empty_library: Callable[[], None],
+ ):
+ """An `Image[]` pipe run with `output_multiplicity=1` produces one image in the single form."""
+ load_empty_library()
+ pipe_img_gen_blueprint = PipeImgGenBlueprint(
+ description="Image generation test",
+ model=img_gen_combo.handle,
+ output=f"{NativeConceptCode.IMAGE}[]",
+ prompt="A lighthouse on a cliff at dusk",
+ )
+
+ pipe_job = PipeJobFactory.make_pipe_job(
+ pipe=PipeFactory[PipeImgGen].make_from_blueprint(
+ domain_code="generic",
+ pipe_code="adhoc_for_test_pipe_img_gen",
+ blueprint=pipe_img_gen_blueprint,
+ ),
+ pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode, output_multiplicity=1),
+ job_metadata=job_metadata,
+ )
+ pipe_output = await get_pipe_router().run(
+ pipe_job=pipe_job,
+ )
+ content = pipe_output.main_stuff.content
+ assert isinstance(content, ImageContent)
+ assert not isinstance(content, ListContent)
+
+ async def test_pipe_img_gen_variable_output_without_count_rejected(
+ self,
+ job_metadata: JobMetadata,
+ pipe_run_mode: PipeRunMode,
+ img_gen_combo: ModelCombo,
+ load_empty_library: Callable[[], None],
+ ):
+ """An `Image[]` pipe run with no count at all stays unguessable: the guard must hold."""
+ load_empty_library()
+ pipe_img_gen_blueprint = PipeImgGenBlueprint(
+ description="Image generation test",
+ model=img_gen_combo.handle,
+ output=f"{NativeConceptCode.IMAGE}[]",
+ prompt="A lighthouse on a cliff at dusk",
+ )
+
+ pipe_job = PipeJobFactory.make_pipe_job(
+ pipe=PipeFactory[PipeImgGen].make_from_blueprint(
+ domain_code="generic",
+ pipe_code="adhoc_for_test_pipe_img_gen",
+ blueprint=pipe_img_gen_blueprint,
+ ),
+ pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
+ job_metadata=job_metadata,
+ )
+ with pytest.raises(PipeRunParamsError, match="Cannot guess how many images"):
+ await get_pipe_router().run(
+ pipe_job=pipe_job,
+ )
diff --git a/tests/integration/pipelex/pipes/optionals/test_taint_sequence_validation.py b/tests/integration/pipelex/pipes/optionals/test_taint_sequence_validation.py
index 8f34052d4..45f9ec9bb 100644
--- a/tests/integration/pipelex/pipes/optionals/test_taint_sequence_validation.py
+++ b/tests/integration/pipelex/pipes/optionals/test_taint_sequence_validation.py
@@ -136,6 +136,41 @@ class TestSequenceTaintValidation:
assert "source" in str(error)
assert "?" in str(error)
+ def test_one_count_step_result_keeps_the_taint(self, load_empty_library: Callable[[], str]):
+ """`nb_output = 1` is the single form: the step's result is NOT plural, so the taint
+ must reach the boundary exactly as it does with no count at all.
+ """
+ load_empty_library()
+ _register_step_pipes()
+ sequence = _build_sequence(
+ output_ref="Text",
+ inputs={"source": "Text?"},
+ steps=[
+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),
+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out", nb_output=1),
+ ],
+ )
+
+ with pytest.raises(PipeValidationError) as exc_info:
+ sequence.validate_with_libraries()
+ error = exc_info.value
+ assert error.error_type == PipeValidationErrorType.OPTIONAL_NOT_HANDLED
+ assert error.variable_names == ["source"]
+
+ def test_plural_count_step_result_absorbs_the_taint(self, load_empty_library: Callable[[], str]):
+ """A genuine list result (`nb_output = 2`) is never tainted — its "nothing" is the empty list."""
+ load_empty_library()
+ _register_step_pipes()
+ sequence = _build_sequence(
+ output_ref="Text[2]",
+ inputs={"source": "Text?"},
+ steps=[
+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),
+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out", nb_output=2),
+ ],
+ )
+ sequence.validate_with_libraries()
+
def test_optional_sequence_output_accepts_the_taint(self, load_empty_library: Callable[[], str]):
load_empty_library()
_register_step_pipes()
diff --git a/tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py b/tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py
index 6e17a9921..249f20279 100644
--- a/tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py
+++ b/tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py
@@ -23,6 +23,12 @@ class TestPipeSpecPresenceMarkers:
spec = _make_spec(inputs={"the_var": input_spec})
assert spec.inputs == {"the_var": input_spec}
+ @pytest.mark.parametrize("input_spec", ["Text[1]?", "Text[1]!", "domain.Concept[1]?"])
+ def test_marker_on_count_of_one_input_accepted(self, input_spec: str):
+ """`[1]` is the single form with its count written out, so it takes a marker like a bare ref."""
+ spec = _make_spec(inputs={"the_var": input_spec})
+ assert spec.inputs == {"the_var": input_spec}
+
@pytest.mark.parametrize("output_spec", ["Text?", "domain.Concept?"])
def test_optional_output_accepted(self, output_spec: str):
spec = _make_spec(output=output_spec)
@@ -49,6 +55,11 @@ class TestPipeSpecPresenceMarkers:
with pytest.raises(ValidationError, match="not allowed on outputs"):
_make_spec(output=output_spec)
+ @pytest.mark.parametrize("input_spec", ["Text[0]", "Text[0]?", "Text[0]!", "domain.Concept[0]"])
+ def test_zero_count_input_rejected(self, input_spec: str):
+ with pytest.raises(ValidationError, match="at least 1"):
+ _make_spec(inputs={"the_var": input_spec})
+
@pytest.mark.parametrize("input_spec", ["Text??", "Text?[]"])
def test_malformed_marker_input_syntax_rejected(self, input_spec: str):
with pytest.raises(ValidationError, match="Invalid input syntax"):
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_errors.py b/tests/unit/pipelex/core/memory/input_shaper/test_errors.py
index 85622b322..5582b1351 100644
--- a/tests/unit/pipelex/core/memory/input_shaper/test_errors.py
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_errors.py
@@ -32,6 +32,10 @@ ERROR_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, type[InputSh
("null-top-level", "native.Text", None, None, NullInputError, "null"),
# D2 a list where a singular is declared is ambiguous.
("list-where-singular", "shaper_test.Question", None, ["a", "b"], ListWhereSingularError, "single"),
+ # `[1]` IS the singular declaration, so it refuses a list on the same grounds — including a
+ # one-item list, which would otherwise look like it "fits" the count.
+ ("list-where-fixed-count-one", "shaper_test.Question", 1, ["a", "b"], ListWhereSingularError, "single"),
+ ("one-item-list-where-fixed-count-one", "shaper_test.Question", 1, ["solo"], ListWhereSingularError, "single"),
# D2 fixed-count mismatch — too few, and a single value for [2].
("count-mismatch-list-too-few", "shaper_test.Question", 2, ["a"], MultiplicityCountMismatchError, "exactly 2"),
("count-mismatch-single-for-two", "shaper_test.Question", 2, "solo", MultiplicityCountMismatchError, "exactly 2"),
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_multiplicity.py b/tests/unit/pipelex/core/memory/input_shaper/test_multiplicity.py
index e28152d13..553e98719 100644
--- a/tests/unit/pipelex/core/memory/input_shaper/test_multiplicity.py
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_multiplicity.py
@@ -12,8 +12,8 @@ from pipelex.core.stuffs.text_content import TextContent
from pipelex.interpreter_hub import get_concept_library
from tests.unit.pipelex.core.memory.input_shaper.data import Deadline, Question, ShaperPerson, build_input_specs
-# (test_name, concept_ref, multiplicity, provided_value, expected_concept_ref, expected_list_content)
-MULTIPLICITY_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, str, ListContent[StuffContent]]] = [
+# (test_name, concept_ref, multiplicity, provided_value, expected_concept_ref, expected_content)
+MULTIPLICITY_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, str, StuffContent]] = [
# Variable list, element-wise shaping into ListContent[declared].
(
"variable-list-refining",
@@ -49,7 +49,7 @@ MULTIPLICITY_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, str,
"shaper_test.Question",
ListContent(items=[]),
),
- # Fixed count [N] validates the count; a single value satisfies [1].
+ # Fixed count [N] validates the count.
(
"fixed-count-two",
"shaper_test.Question",
@@ -58,13 +58,15 @@ MULTIPLICITY_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, str,
"shaper_test.Question",
ListContent(items=[Question(text="a"), Question(text="b")]),
),
+ # `[1]` is the single form, not a one-item list: the shaper builds the item itself, and a list
+ # payload is refused there exactly as it is under a bare declaration.
(
- "fixed-count-one-single",
+ "fixed-count-one-is-single",
"shaper_test.Question",
1,
"solo",
"shaper_test.Question",
- ListContent(items=[Question(text="solo")]),
+ Question(text="solo"),
),
# A list of dicts shapes element-wise into a structured list, no envelope.
(
@@ -91,7 +93,7 @@ MULTIPLICITY_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, str,
class TestInputShaperMultiplicity:
@pytest.mark.parametrize(
- ("test_name", "concept_ref", "multiplicity", "provided_value", "expected_concept_ref", "expected_list_content"),
+ ("test_name", "concept_ref", "multiplicity", "provided_value", "expected_concept_ref", "expected_content"),
MULTIPLICITY_CASES,
)
def test_multiplicity_case(
@@ -101,7 +103,7 @@ class TestInputShaperMultiplicity:
multiplicity: VariableMultiplicity | None,
provided_value: Any,
expected_concept_ref: str,
- expected_list_content: ListContent[StuffContent],
+ expected_content: StuffContent,
) -> None:
log.info(f"Testing multiplicity case: {test_name}")
input_specs = build_input_specs([("my_input", concept_ref, multiplicity)])
@@ -112,4 +114,4 @@ class TestInputShaperMultiplicity:
pretty_print(stuff, title=f"Result for {test_name}")
assert stuff.concept.concept_ref == expected_concept_ref, f"Wrong concept for {test_name}"
# Equality subsumes the type check: a ListContent never equals a non-ListContent content.
- assert stuff.content == expected_list_content, f"Wrong list content for {test_name}"
+ assert stuff.content == expected_content, f"Wrong content for {test_name}"
diff --git a/tests/unit/pipelex/core/pipes/data.py b/tests/unit/pipelex/core/pipes/data.py
index d62a71678..3afc12b50 100644
--- a/tests/unit/pipelex/core/pipes/data.py
+++ b/tests/unit/pipelex/core/pipes/data.py
@@ -6,7 +6,7 @@ MAKE_VARIABLE_MULTIPLICITY_TEST_CASES: list[tuple[int | None, bool | None, Varia
# Test cases where nb_output takes precedence
(3, None, 3, "nb_output=3, multiple_output=None -> returns 3"),
(5, False, 5, "nb_output=5, multiple_output=False -> returns 5 (nb_output takes precedence)"),
- (1, True, 1, "nb_output=1, multiple_output=True -> returns 1 (nb_output takes precedence)"),
+ (1, True, None, "nb_output=1, multiple_output=True -> returns None (a count of one is the single form)"),
(10, None, 10, "nb_output=10, multiple_output=None -> returns 10"),
# Test cases where multiple_output=True is used
(None, True, True, "nb_output=None, multiple_output=True -> returns True"),
@@ -73,7 +73,6 @@ EXPLICIT_DOMAIN_IN_STRING_TEST_CASES: list[tuple[str, str, str, int | bool | Non
# Format: (domain, requirement_str, expected_concept_ref, expected_multiplicity)
VARIOUS_FIXED_COUNTS_TEST_CASES: list[tuple[str, str, str, int]] = [
# Native domain with various counts
- ("native", "native.Image[1]", "native.Image", 1),
("native", "native.Image[2]", "native.Image", 2),
("native", "native.Image[10]", "native.Image", 10),
("native", "native.Image[100]", "native.Image", 100),
diff --git a/tests/unit/pipelex/core/pipes/test_concept_multiplicity_formatting.py b/tests/unit/pipelex/core/pipes/test_concept_multiplicity_formatting.py
index b17a3a108..d5931f425 100644
--- a/tests/unit/pipelex/core/pipes/test_concept_multiplicity_formatting.py
+++ b/tests/unit/pipelex/core/pipes/test_concept_multiplicity_formatting.py
@@ -77,3 +77,19 @@ class TestFormatConceptWithMultiplicity:
)
== spec
)
+
+ def test_a_fixed_count_of_one_round_trips_to_the_bare_spelling(self):
+ """`Text[1]` is canonicalized, not preserved: the parse collapses it and the format renders `Text`.
+
+ This is the one place the `[1]`-is-single ruling is visible to an author — a re-rendered ref
+ drops the count. The two spellings denote the same slot, so the canonical one is what survives.
+ """
+ parsed = parse_concept_with_multiplicity("Text[1]")
+ assert (
+ format_concept_with_multiplicity(
+ parsed.concept_ref_or_code,
+ multiplicity=parsed.multiplicity,
+ presence=parsed.presence,
+ )
+ == "Text"
+ )
diff --git a/tests/unit/pipelex/core/pipes/test_input_requirements_factory.py b/tests/unit/pipelex/core/pipes/test_input_requirements_factory.py
index 6e019058c..8eabbc268 100644
--- a/tests/unit/pipelex/core/pipes/test_input_requirements_factory.py
+++ b/tests/unit/pipelex/core/pipes/test_input_requirements_factory.py
@@ -93,6 +93,20 @@ class TestMakeInputRequirementsFromString:
assert result.multiplicity == expected_multiplicity, f"Failed for {stuff_spec_str}"
assert result.concept.concept_ref == expected_concept_ref
+ def test_fixed_count_of_one_is_the_single_form(self, load_empty_library: Callable[[], None]):
+ """`Concept[1]` builds a single-item spec, exactly as a bare `Concept` does.
+
+ This factory parses input specs with its own regex rather than the shared parser, so it is the
+ second place the `[1]`-is-single ruling has to hold — and the one the memory shaper reads.
+ """
+ load_empty_library()
+ result = InputStuffSpecsFactory.make_from_string(
+ domain_code="native", stuff_spec_str="native.Image[1]", concept_provider=get_concept_library()
+ )
+ assert result.concept.concept_ref == "native.Image"
+ assert result.multiplicity is None
+ assert result.is_multiple() is False
+
@pytest.mark.parametrize(
("domain_code", "stuff_spec_str", "expected_concept_ref"),
DIFFERENT_CONCEPT_CODES_TEST_CASES,
diff --git a/tests/unit/pipelex/core/pipes/test_is_multiplicity_compatible.py b/tests/unit/pipelex/core/pipes/test_is_multiplicity_compatible.py
index 13e5762fa..f6cc950f4 100644
--- a/tests/unit/pipelex/core/pipes/test_is_multiplicity_compatible.py
+++ b/tests/unit/pipelex/core/pipes/test_is_multiplicity_compatible.py
@@ -16,17 +16,18 @@ class TestIsMultiplicityCompatible:
# Case 2: Target expects variable-length list (True)
(True, True, True),
(3, True, True), # Fixed count fulfills variable expectation
- (1, True, True), # Even count of 1 is multiple items
+ (1, True, False), # `[1]` is the single form, and a single cannot fulfill a list expectation
(None, True, False), # Single cannot fulfill list expectation
# Case 3: Target expects fixed count (integer)
(3, 3, True),
(5, 5, True),
- (1, 1, True), # Fixed count of 1 matches itself
+ (1, 1, True), # Both collapse to the single form
+ (1, None, True), # `[1]` fulfills a bare single expectation - it is the same slot
(3, 5, False), # Different fixed counts are incompatible
(True, 3, False), # Variable cannot fulfill fixed expectation
- (True, 1, False), # Variable (True) cannot fulfill fixed count of 1 (edge case: True == 1 in Python)
+ (True, 1, False), # A variable list cannot fulfill the single form (and True == 1 must not conflate them)
(None, 3, False),
- (None, 1, False), # Single item cannot fulfill fixed count of 1
+ (None, 1, True), # A bare single fulfills `[1]` - it is the same slot
],
)
def test_multiplicity_compatibility(
diff --git a/tests/unit/pipelex/core/pipes/test_make_variable_multiplicity.py b/tests/unit/pipelex/core/pipes/test_make_variable_multiplicity.py
index 2b5005748..bc0e49d27 100644
--- a/tests/unit/pipelex/core/pipes/test_make_variable_multiplicity.py
+++ b/tests/unit/pipelex/core/pipes/test_make_variable_multiplicity.py
@@ -27,8 +27,9 @@ class TestMakeVariableMultiplicity:
result = make_variable_multiplicity(nb_items=3, multiple_items=True)
assert result == 3
+ # A count of one is the single form, so nb_items=1 yields no multiplicity at all
result = make_variable_multiplicity(nb_items=1, multiple_items=False)
- assert result == 1
+ assert result is None
# When nb_items is falsy (0), multiple_items should be used
result = make_variable_multiplicity(nb_items=0, multiple_items=True)
diff --git a/tests/unit/pipelex/core/pipes/test_multiplicity_helpers.py b/tests/unit/pipelex/core/pipes/test_multiplicity_helpers.py
index 2a52b8130..7b4ba8008 100644
--- a/tests/unit/pipelex/core/pipes/test_multiplicity_helpers.py
+++ b/tests/unit/pipelex/core/pipes/test_multiplicity_helpers.py
@@ -1,14 +1,20 @@
"""Unit tests for the multiplicity projection helpers.
-These two helpers are the normalization every consumer of `VariableMultiplicity | None`
-shares: list-or-not, and the exact count when (and only when) the multiplicity is a fixed
-count above one. The bool/int cases matter because `True == 1` in Python — the helpers must
-keep `[]` (True) and `[1]` (1) distinct.
+These helpers are the normalization every consumer of `VariableMultiplicity | None` shares:
+list-or-not, the exact count when (and only when) the multiplicity is a fixed count above one,
+and the collapse of a count of one onto the single form the language says it already is. The
+bool/int cases matter because `True == 1` in Python — a variable-length `[]` must never collapse
+the way a `[1]` does.
"""
import pytest
-from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity, fixed_item_count, is_multiple_multiplicity
+from pipelex.core.pipes.variable_multiplicity import (
+ VariableMultiplicity,
+ fixed_item_count,
+ is_multiple_multiplicity,
+ normalize_variable_multiplicity,
+)
class TestMultiplicityHelpers:
@@ -39,3 +45,30 @@ class TestMultiplicityHelpers:
)
def test_fixed_item_count(self, multiplicity: VariableMultiplicity | None, expected: int | None):
assert fixed_item_count(multiplicity=multiplicity) == expected
+
+ @pytest.mark.parametrize(
+ ("multiplicity", "expected"),
+ [
+ (None, None),
+ (True, True),
+ (False, False),
+ (1, None),
+ (2, 2),
+ (10, 10),
+ ],
+ )
+ def test_normalize(self, multiplicity: VariableMultiplicity | None, expected: VariableMultiplicity | None):
+ """The `[1]`-is-single ruling, applied wherever a multiplicity is built.
+
+ Every site that turns authored syntax or caller arguments into a `VariableMultiplicity` routes
+ through this, so the value `1` never reaches a consumer and none of them has to remember why.
+ """
+ assert normalize_variable_multiplicity(multiplicity=multiplicity) == expected
+
+ def test_normalize_leaves_a_variable_list_alone(self):
+ """`bool` is a subclass of `int` and `True == 1`, so `[]` must not collapse the way `[1]` does."""
+ assert normalize_variable_multiplicity(multiplicity=True) is True
+
+ def test_normalize_does_not_silently_repair_an_invalid_count(self):
+ """`[0]` is invalid syntax the parser refuses; collapsing it here would hide that."""
+ assert normalize_variable_multiplicity(multiplicity=0) == 0
diff --git a/tests/unit/pipelex/core/pipes/test_parse_concept_with_multiplicity.py b/tests/unit/pipelex/core/pipes/test_parse_concept_with_multiplicity.py
index d4d3a56fb..c6d184209 100644
--- a/tests/unit/pipelex/core/pipes/test_parse_concept_with_multiplicity.py
+++ b/tests/unit/pipelex/core/pipes/test_parse_concept_with_multiplicity.py
@@ -24,6 +24,24 @@ class TestParseConceptWithMultiplicity:
assert result.concept_ref_or_code == "Text"
assert result.multiplicity == 5
+ def test_fixed_count_of_one_is_the_single_form(self):
+ """`Concept[1]` declares the same slot as `Concept`, so the parser never yields the value 1.
+
+ The count is authored syntax, not a distinct multiplicity: collapsing it here is what makes
+ `1` unrepresentable downstream, so no consumer can frame a `[1]` slot as a one-item list.
+ """
+ result = parse_concept_with_multiplicity("Text[1]")
+ assert result.concept_ref_or_code == "Text"
+ assert result.multiplicity is None
+
+ assert parse_concept_with_multiplicity("domain.Concept[1]").multiplicity is None
+
+ def test_fixed_count_of_one_keeps_its_presence_marker(self):
+ """The count collapses; the marker beside it does not."""
+ result = parse_concept_with_multiplicity("Text[1]?")
+ assert result.multiplicity is None
+ assert result.presence == PresenceMarker.OPTIONAL
+
def test_valid_domain_qualified_concept(self):
"""Test parsing domain-qualified concepts."""
result = parse_concept_with_multiplicity("domain.Concept")
diff --git a/tests/unit/pipelex/libraries/test_contract_match.py b/tests/unit/pipelex/libraries/test_contract_match.py
index b8874195e..fd2c8b208 100644
--- a/tests/unit/pipelex/libraries/test_contract_match.py
+++ b/tests/unit/pipelex/libraries/test_contract_match.py
@@ -50,3 +50,19 @@ class TestContractsMatchPresenceMarkers:
existing = _make_blueprint(output="Brief[]")
incoming = _make_blueprint(output="Brief[1]")
assert not contracts_match(existing=existing, incoming=incoming, domain_code="thisdomain")
+
+ def test_a_fixed_count_of_one_matches_the_bare_spelling(self):
+ """`Brief[1]` and `Brief` denote the same slot, so a header and its definition may spell it either way.
+
+ The suffix is compared as text here rather than parsed (`True == 1` would conflate `[]` with a
+ count), so the `[1]`-is-single ruling has to be applied to the text too.
+ """
+ existing = _make_blueprint(output="Brief")
+ incoming = _make_blueprint(output="Brief[1]")
+ assert contracts_match(existing=existing, incoming=incoming, domain_code="thisdomain")
+
+ def test_a_fixed_count_of_one_keeps_its_marker_distinct(self):
+ """Collapsing the count must not swallow the presence marker beside it."""
+ existing = _make_blueprint(output="Brief[1]?")
+ incoming = _make_blueprint(output="Brief")
+ assert not contracts_match(existing=existing, incoming=incoming, domain_code="thisdomain")
diff --git a/tests/unit/pipelex/pipe_machinery/test_pipe_blueprint_presence_markers.py b/tests/unit/pipelex/pipe_machinery/test_pipe_blueprint_presence_markers.py
index 975e66aac..5619761c8 100644
--- a/tests/unit/pipelex/pipe_machinery/test_pipe_blueprint_presence_markers.py
+++ b/tests/unit/pipelex/pipe_machinery/test_pipe_blueprint_presence_markers.py
@@ -41,6 +41,12 @@ class TestPipeBlueprintPresenceMarkers:
blueprint = _make_blueprint(inputs={"the_var": input_spec})
assert blueprint.inputs == {"the_var": input_spec}
+ @pytest.mark.parametrize("input_spec", ["Text[1]?", "Text[1]!", "domain.Concept[1]?"])
+ def test_marker_on_count_of_one_input_accepted(self, input_spec: str):
+ """`[1]` is the single form with its count written out, so it takes a marker like a bare ref."""
+ blueprint = _make_blueprint(inputs={"the_var": input_spec})
+ assert blueprint.inputs == {"the_var": input_spec}
+
@pytest.mark.parametrize("output_spec", ["Text?", "domain.Concept?"])
def test_optional_output_accepted(self, output_spec: str):
blueprint = _make_blueprint(output=output_spec)
@@ -73,6 +79,11 @@ class TestPipeBlueprintPresenceMarkers:
# ---- rejected forms: plain syntax errors ----
+ @pytest.mark.parametrize("input_spec", ["Text[0]", "Text[0]?", "Text[0]!", "domain.Concept[0]"])
+ def test_zero_count_input_rejected(self, input_spec: str):
+ with pytest.raises(ValidationError, match="at least 1"):
+ _make_blueprint(inputs={"the_var": input_spec})
+
@pytest.mark.parametrize("input_spec", ["Text??", "Text?[]", "?Text"])
def test_malformed_marker_input_syntax_rejected(self, input_spec: str):
with pytest.raises(ValidationError, match="Invalid input syntax"):
diff --git a/tests/unit/pipelex/pipe_run/data.py b/tests/unit/pipelex/pipe_run/data.py
index aa7f406b7..884d7a8a8 100644
--- a/tests/unit/pipelex/pipe_run/data.py
+++ b/tests/unit/pipelex/pipe_run/data.py
@@ -126,8 +126,8 @@ OUTPUT_MULTIPLICITY_TO_APPLY_TEST_CASES: list[
(
5,
1,
- VariableMultiplicityResolution(resolved_multiplicity=1, is_multiple_outputs_enabled=True, specific_output_count=1),
- "base=5, override=1 - override takes precedence",
+ VariableMultiplicityResolution(resolved_multiplicity=False, is_multiple_outputs_enabled=False, specific_output_count=None),
+ "base=5, override=1 - a requested count of one is a request for the single form",
),
# Edge cases with negative numbers
(
diff --git a/tests/unit/pipelex/pipe_run/test_pipe_run_params.py b/tests/unit/pipelex/pipe_run/test_pipe_run_params.py
index 762824f9e..2bd6987bc 100644
--- a/tests/unit/pipelex/pipe_run/test_pipe_run_params.py
+++ b/tests/unit/pipelex/pipe_run/test_pipe_run_params.py
@@ -87,13 +87,20 @@ class TestOutputMultiplicityToApply:
assert result.is_multiple_outputs_enabled is True
assert result.specific_output_count is None
- # Base int -> preserve count, enable multiple
- for base_int in [1, 3, 5, 10]:
+ # Base count -> preserve count, enable multiple
+ for base_int in [3, 5, 10]:
result = output_multiplicity_to_apply(base_multiplicity=base_int, override_multiplicity=True)
assert result.resolved_multiplicity == base_int
assert result.is_multiple_outputs_enabled is True
assert result.specific_output_count == base_int
+ # Base [1] is the single form, so there is no count to preserve: the override enables a
+ # variable-length list and leaves the count to the model.
+ result = output_multiplicity_to_apply(base_multiplicity=1, override_multiplicity=True)
+ assert result.resolved_multiplicity is None
+ assert result.is_multiple_outputs_enabled is True
+ assert result.specific_output_count is None
+
def test_override_int_uses_override_count(self):
"""Test that override int uses the override count and enables multiple outputs."""
test_bases = [None, True, False, 2, 7]
@@ -211,3 +218,28 @@ class TestOutputMultiplicityToApply:
assert result.resolved_multiplicity == 4 # Preserves base count
assert result.is_multiple_outputs_enabled is True
assert result.specific_output_count == 4
+
+ def test_a_base_count_of_one_is_the_single_form(self):
+ """A pipe declaring `output = "Concept[1]"` produces one object, not a one-item list.
+
+ The parser collapses the count before it ever reaches here, so this pins the arm rather than
+ the path: handed the value 1 directly, the resolution must still be the single form.
+ """
+ result = output_multiplicity_to_apply(base_multiplicity=1, override_multiplicity=None)
+ assert result.resolved_multiplicity is None
+ assert result.is_multiple_outputs_enabled is False
+ assert result.specific_output_count is None
+
+ def test_a_requested_count_of_one_forces_the_single_form(self):
+ """A caller asking at run time for exactly one output is asking for the single form.
+
+ Unlike the base, an override genuinely arrives from outside (an SDK or API caller may pass
+ `output_multiplicity=1`), so this arm is reachable and must not enable a one-item list.
+ """
+ result = output_multiplicity_to_apply(base_multiplicity=True, override_multiplicity=1)
+ assert result.is_multiple_outputs_enabled is False
+ assert result.specific_output_count is None
+
+ result = output_multiplicity_to_apply(base_multiplicity=5, override_multiplicity=1)
+ assert result.is_multiple_outputs_enabled is False
+ assert result.specific_output_count is None
diff --git a/uv.lock b/uv.lock
index c884cddde..8788c967a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3472,7 +3472,7 @@ requires-dist = [
{ name = "mkdocs-meta-manager", marker = "extra == 'docs'", specifier = ">=1.1.0" },
{ name = "mkdocs-redirects", marker = "extra == 'docs'", specifier = "==1.2.2" },
{ name = "moto", extras = ["dynamodb", "s3"], marker = "extra == 'dev'", specifier = ">=5.0.0" },
- { name = "mthds", specifier = ">=0.11.0" },
+ { name = "mthds", specifier = "==0.11.0" },
{ name = "mypy", marker = "extra == 'dev'", specifier = "==1.19.1" },
{ name = "networkx", specifier = ">=3.4.2" },
{ name = "openai", specifier = ">=2.0.0" },
diff --git a/wip/enrich/deferred.md b/wip/enrich/deferred.md
index a84c5edb1..819831652 100644
--- a/wip/enrich/deferred.md
+++ b/wip/enrich/deferred.md
@@ -6,9 +6,19 @@ Items surfaced by the pre-landing review of PR #1149 that are real but not clear
`pipelex/pipeline/input_form.py` (`_with_reflected_constraints`) stamps `field_info.default` raw into the descriptor's `default_value: Any` slot. A registered hand-written class whose field default holds a non-JSON-serializable value turns a valid bundle's report dump into a `PydanticSerializationError` at serialization time, far from the offending class. Exposure is limited by `reflect_structure_class`'s annotation gating (only mappable annotations reach reflection at all). The candidate remedy is to coerce via `pydantic_core.to_jsonable_python` and drop the fact on failure, per the faithful-or-absent rule — but silently dropping an authored fact versus failing loudly is a design choice that deserves a ruling, not a speculative guard.
-## 2. `_peel_multiplicity` rules `[1]` the opposite way from the rest of the chain
+## 2. `_peel_multiplicity` rules `[1]` the opposite way from the rest of the chain — RULED, fixed
-`pipelex/core/memory/input_shaper.py` (`_peel_multiplicity`) treats a fixed count of 1 as a one-item **list**, while the S2 chain — `variable_multiplicity.py` helpers, the wire contract, the schema render, and `docs/under-the-hood/input-form-descriptor.md` — all rule `[1]` **single** (no list framing). So a `[1]` slot's published schema says single object while the runtime shaper frames the payload as a list. Pre-existing (the file is untouched by the branch), made visible by the new ruling; each side's docstring claims its ruling as universal. Cross-surface semantic decision: either the shaper adopts the `[1]`-is-single ruling or the divergence is documented as intentional at the memory boundary.
+`pipelex/core/memory/input_shaper.py` (`_peel_multiplicity`) treated a fixed count of 1 as a one-item **list**, while the S2 chain — `variable_multiplicity.py` helpers, the wire contract, the schema render, and `docs/under-the-hood/input-form-descriptor.md` — all ruled `[1]` **single** (no list framing). So a `[1]` slot's published schema said single object while the runtime shaper framed the payload as a list, and a consumer rendering a form on the descriptor would submit a value the shaper refused.
+
+The ruling went the way the standard already states it (`mthds/docs/language/multiplicity.md`, "A count of one is not a list"): `[1]` is the single form, and the shaper was the side that was wrong. Rather than correct that one function, the count now collapses to `None` at the sites that *build* a multiplicity — `parse_concept_with_multiplicity`, `InputStuffSpecsFactory.make_from_string`, `make_variable_multiplicity` — so the value `1` is unrepresentable downstream and no consumer has to remember the rule. `_peel_multiplicity` delegates to the shared projection helpers instead of re-deriving them, which is what let it drift in the first place. Fixing it surfaced three more sites re-deriving the same semantics from raw text: the blueprint's input-side marker check (which refused `Concept[1]?` while the output half accepted it), the contract-match canonicalizer (which read a header's `Brief` and a definition's `Brief[1]` as a mismatch), and the run-time output-multiplicity override.
+
+## 2b. The input-spec factory accepts `Concept[0]` where the io-ref parser refuses it — RULED at the validators
+
+Surfaced while ruling §2, then ruled in PR #1157's review round: `PipeBlueprint.generic_validate_inputs` and its spec-layer mirror (`PipeSpec.validate_inputs`) now refuse a non-positive bracket count with a plain `ValueError` ("Multiplicity must be at least 1") before the marker check, which matches how the output half surfaces the same rule through `parse_concept_with_multiplicity`. That closes the authoring paths — a `[0]` input is rejected at blueprint construction instead of detonating later in reference collection as an uncaught `PipeVariableMultiplicityError`. `InputStuffSpecsFactory.make_from_string` itself still matches `(\d*)` without the range check, but every route into it passes a validated blueprint first, so the residue is defense-in-depth, not a reachable hole.
+
+## 2c. The two input-side validators still hand-roll the ref grammar
+
+`generic_validate_inputs` and `PipeSpec.validate_inputs` each do `re.match(MULTIPLICITY_PATTERN, ...)` plus three group reads where a single `parse_concept_with_multiplicity` call would parse before deciding — which is what the blueprint's own comment says it wants, and what let §2/§2b drift in the first place. Folding them onto the parser means reconciling the error surfaces (the tests match on the validators' "Invalid input syntax for ..." prefix and the typed `OPTIONAL_MARKER_INVALID`); mechanical but not free, so it was left out of the round-1 fixes.
## 3. `_with_reflected_constraints` name/content drift
@@ -21,3 +31,35 @@ The function now stamps presence and default facts as well as constraints; the d
## 5. `rejected/` fixture corpus is mostly inert
Four of the pre-existing `tests/data/input_semantics/rejected/` fixtures (`default_on_concept_field`, `multiple_refines`, `non_string_choices`, `refines_plus_structure`) are loaded by no test — the directory grew as a documentation corpus with only `per_input_description` (and now the two S2 fixtures, wired on this branch) exercised through the parser. A parametrized parser-level harness sweeping the whole directory would keep fixtures from rotting, but each fixture must first be confirmed to actually fail today's parse (some may document aspirational rejections) — audit before wiring.
+
+## 6. The `[1]` collapse is enforced at the build sites, not at the type
+
+Surfaced by PR #1157's review round. The count collapses wherever a multiplicity is *built* from authored syntax, which is enough for every path that goes through a parser — but the invariant the changelog states ("the value `1` no longer exists downstream") is not structural, and three sites falsify it today:
+
+- `pipelex/pipe_operators/img_gen/pipe_img_gen_factory.py` sets `final_multiplicity = ... else 1`, so **every** bare `Image` output carries a literal `1` in `PipeImgGen.output_multiplicity`. Harmless — `output_multiplicity_to_apply` normalizes it at run time — but the comment beside it ("default to 1 if no brackets") now reads backwards, since no brackets is the single form.
+- `SubPipeFactory` assigns `blueprint.nb_output` verbatim, so an authored `nb_output = 1` lives as a raw `1` on `SubPipe.output_multiplicity`. Every consumer that resolves it through `output_multiplicity_to_apply` gets the right answer; the two that did not were fixed in `a61a9163d`.
+- `StuffSpec.multiplicity` is a plain pydantic field with no validator, and `format_concept_with_multiplicity(multiplicity=1)` renders `Text[1]`, which the parser reads back as `None`. So the documented parse/format inverse does not hold in one direction, and a `1` arriving by direct construction or `model_validate` is never collapsed.
+
+Making it structural is a `@field_validator` on `StuffSpec.multiplicity` plus a `normalize_variable_multiplicity` inside `format_concept_with_multiplicity`, after which the build-site calls become belt-and-braces rather than the whole enforcement. Deferred because `tests/unit/pipelex/core/pipes/test_concept_multiplicity_formatting.py` deliberately pins `("Image", 1, "Image[1]")`, so the emitter is currently an intentional non-collapsing site — changing it is a ruling, not a cleanup.
+
+## 7. The zero-count rule is enforced on the bracket spelling only
+
+`Concept[0]` is now refused at both authoring layers (§2b), but the same count spelled as a step field is not: `SubPipeBlueprint.nb_output` carries no `ge=1`, and `SubPipeFactory` tests it for truthiness, so `nb_output = 0` silently means "no override" and `nb_output = -2` validates green and reaches `PipeLLM` as `fixed_nb_output = -2`. One language rule, two answers depending on which surface the author used. A `Field(ge=1)` on `nb_output` closes it.
+
+Relatedly, there is no *upper* bound anywhere: `Text[100000000000]` is accepted by every validator this branch touched, and `WorkingMemoryFactory.make_mock_stuff` materializes the count (`native.Text[50000]` builds fifty thousand items in about five seconds) on the mock-inputs dry-run path, reachable from bundle text alone. The branch that established "the count is validated where it is written" added the floor and no ceiling.
+
+## 8. `make_mock_stuff` is the sibling of the bug §2 fixed
+
+`pipelex/core/memory/working_memory_factory.py` decides plurality by truthiness (`if not typed_named_stuff_spec.multiplicity:`) and then takes the count verbatim, so a multiplicity of `1` still builds a one-item `ListContent` — the exact framing §2 set out to eliminate, in the one builder that was not converted onto `is_multiple_multiplicity` / `fixed_item_count`. Latent only: reachable through the `1`-carrying sites in §6. The fix is the same two-line delegation `_peel_multiplicity` received.
+
+## 9. The `[0]` input errors are untyped, unlike every rule beside them
+
+`PipeBlueprint.generic_validate_inputs` and `PipeSpec.validate_inputs` raise a bare `ValueError` for a non-positive count, while the presence-marker rule nine lines below raises a typed `PipeValidationError(error_type=OPTIONAL_MARKER_INVALID, ...)` and the output side raises `PipeVariableMultiplicityError`. So `Text[0]` is the one input-grammar violation the categorizer and the fix planner cannot act on, and the identical rule is worded two ways depending on the side it was written. Per this workspace's rule that structured fields are the contract and prose is presentation, one rule should produce one structured verdict. Folds naturally into §2c, which has to reconcile the same error surfaces.
+
+## 10. `PipeRunParams.output_multiplicity` coerces a string count of one to `True`
+
+`VariableMultiplicity = bool | int`, and pydantic resolves the union bool-first, so `output_multiplicity="1"` and `output_multiplicity=1.0` both become `True` — "let the model decide" — while `"2"` correctly becomes `2`. Only the count of one inverts, and it inverts into the opposite meaning. The union order predates PR #1157, but that branch is what makes `output_multiplicity=1` a documented public knob, so the string form an HTTP or SDK caller sends is newly worth getting right. `StrictBool | int` on the field, or a validator, settles it. `output_multiplicity=0` is a second gap: it resolves to `(0, is_multiple=True, count=0)` and reaches `PipeImgGen` as `nb_images = 0`, which generates one image anyway.
+
+## 11. A top-level `output_multiplicity=1` still splits the static pass from the run path
+
+`PipeSequence` copies the caller's run params to every step, so a top-level `output_multiplicity=1` reaches steps that declare their own plural output. `is_plural_step_result` reads only the step's *own* override (`None` there), so it answers plural from the declaration, while the run path resolves the inherited `1` to the single form. A lifted step then records an absence where the taint pass promised an empty list. Narrow trigger and the fix is a design question — whether an inherited override should participate in the static promise at all — so it was not folded into `a61a9163d`, which fixed only the sites reading a step's own override.