Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,26 @@
What changed in PACT, newest first. Each entry says what an author can now write, or what now
holds that did not; the commits are listed under it for whoever wants the detail.

## 2026-11 — a growing `each` joins by its teamwork, and a `stop` undoes what it stopped (22 November)

An `each` with `keeps-taking: yes` read none of its `teamwork:`: it waited for every item whatever
`waits-for:` said, and an item that failed ended the run even under `if-someone-fails: carry-on`.
And `does: stop` cancelled a run a `call` started without waiting for it, but nothing undid what
that run had done, where the schema's `stops:` says "what it did is undone as its own `undone-by:`
says".

### What holds now

- **A growing `each` is joined as any other.** `_Run.taking` settles each finished item through the
same step as `_Run.branches` (`_Run.joined`, `_JoinRule`): `if-someone-fails: carry-on` records a
failed item as `{"failed": ...}` and goes on taking, `stop-the-others` (the default) stops the run,
and once `waits-for:` is met (`anyone`, `the-first-good-answer`, `enough-of-them`) the items still
running are cancelled and nothing more is taken
(`tests/test_forks_stops_and_a_growing_each.py`).
- **A `stop` undoes the run it stopped.** A detached run (`RunRef`) carries its call's way back, the
stage's `undone-by:` or the action's, and the inputs it was called with; `does: stop` cancels the
run, waits for the cancellation to land, then calls that undo with those inputs.

## 2026-11 — a member a rule stopped says what it had already done (21 November)

A team member whose run a rule stopped (`stop-the-run`) reached its lead as
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1001,11 +1001,11 @@ framework is an extra.
|---|---|
| **Design** | Thesis, 29 binding decisions, FRD (120 requirements), 60-row refusal ledger — complete |
| **Research** | 14 source-grounded studies, ~15,750 lines, over 140 repos (~15 GB) + 57 papers |
| **Code** | Loader, diagnostics, schema engine, CLI, harness, resolver, evals, SLO — **5394 tests (1733 Rust + 3661 adapter), clippy clean, TypeScript type-checked** |
| **Code** | Loader, diagnostics, schema engine, CLI, harness, resolver, evals, SLO — **5398 tests (1733 Rust + 3665 adapter), clippy clean, TypeScript type-checked** |
| **Adapters** | **All 7 named targets**, proven against one shared conformance suite |

```bash
./scripts/test-all.sh # 5394 tests, Rust + 7 adapters, fully offline
./scripts/test-all.sh # 5398 tests, Rust + 7 adapters, fully offline
```

**What is still owed** is not hidden — it lives in
Expand Down
147 changes: 103 additions & 44 deletions adapters/python/src/pact_adapters/workflow_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,10 @@ class RunRef:

id: str
task: "asyncio.Task[Any]"
#: The call's way back (`undone-by:`, the stage's or the action's), which
#: a `stop` runs once it has stopped the run, with the call's inputs.
undo: str = ""
inputs: dict[str, Any] = field(default_factory=dict)

def stop(self) -> bool:
return self.task.cancel()
Expand Down Expand Up @@ -320,6 +324,30 @@ def child(self, **changes: Any) -> "_Scope":
)


@dataclass(frozen=True)
class _JoinRule:
"""How an `each` or a `together` joins what it runs side by side: its
`teamwork:`'s `waits-for:`, `enough-is:` and `if-someone-fails:`."""

waits: str
enough: int
on_failure: str

@staticmethod
def of(stage: StageSpec) -> "_JoinRule":
return _JoinRule(
waits=str(stage.teamwork.get("waits-for") or "everyone").strip(),
enough=int(stage.teamwork.get("enough-is") or 0),
on_failure=str(stage.teamwork.get("if-someone-fails") or "stop-the-others").strip(),
)

def met(self, good: int) -> bool:
"""Whether `good` answers end the join before everything has ended."""
if self.waits in ("anyone", "the-first-good-answer"):
return good >= 1
return self.waits == "enough-of-them" and bool(self.enough) and good >= self.enough


class _Run:
def __init__(
self,
Expand Down Expand Up @@ -460,16 +488,22 @@ async def stage(self, stage: StageSpec, scope: _Scope, where: str) -> tuple[str,
if does == "answer":
return "answered", self.inputs(stage, scope)
if does == "stop":
return "answered", self.stop(stage, scope)
return "answered", await self.stop(stage, scope)
raise Stopped(f"{stage.name!r} does {does!r}, which a workflow does not run")

def stop(self, stage: StageSpec, scope: _Scope) -> dict[str, Any]:
"""`does: stop`: cancel a run a `call` started without waiting for it."""
async def stop(self, stage: StageSpec, scope: _Scope) -> dict[str, Any]:
"""`does: stop`: cancel a run a `call` started without waiting for it,
then undo what it did as the call's own `undone-by:` says (`stops:`)."""
ref = scope.read(stage.stops)
if not isinstance(ref, RunRef):
raise Stopped(f"{stage.name!r} stops {stage.stops!r}, which is not a run this one started")
stopped = ref.stop()
self.result.detached.pop(ref.id, None)
if stopped:
# Let the cancellation land before the undo runs.
await asyncio.gather(ref.task, return_exceptions=True)
if ref.undo:
await self.invoke(ref.undo, ref.inputs)
return {"stopped": stopped}

def inputs(self, stage: StageSpec, scope: _Scope) -> dict[str, Any]:
Expand Down Expand Up @@ -528,7 +562,12 @@ async def call(self, stage: StageSpec, scope: _Scope, where: str) -> tuple[str,
name = await self.target(stage, scope)
inputs = self.inputs(stage, scope)
if not stage.waits_for_result:
ref = RunRef(id=uuid.uuid4().hex, task=asyncio.ensure_future(self.invoke(name, inputs)))
ref = RunRef(
id=uuid.uuid4().hex,
task=asyncio.ensure_future(self.invoke(name, inputs)),
undo=stage.undone_by or self._action_undo(name),
inputs=inputs,
)
self.result.detached[ref.id] = ref
return "answered", {"run": ref}
attempts = max(1, stage.at_most or 1)
Expand Down Expand Up @@ -1092,30 +1131,49 @@ async def taking(
Each time an item finishes the `over:` list is read again, and anything
new is started. It ends once the list has stopped growing and nothing it
started is still running — the join over a growing set (docs/97 §2.5).
`items-at-most:` still bounds it, counted over everything it took."""
`items-at-most:` still bounds it, counted over everything it took. The
items are joined by the stage's `teamwork:` as `branches` joins them: a
failed item is handled as `if-someone-fails:` says, and once
`waits-for:` is met the items still running are stopped and nothing
more is taken."""
def key(it: Any) -> Any:
if stage.identified_by and isinstance(it, Mapping):
return tuple(str(it.get(f)) for f in stage.identified_by)
return repr(it)

rule = _JoinRule.of(stage)
taken = {key(it) for it in items}
running = {asyncio.ensure_future(one(it)) for it in items}
answers: list[Any] = []
while running:
done, running = await asyncio.wait(running, return_when=asyncio.FIRST_COMPLETED)
for t in done:
answers.append(t.result())
now = scope.read(stage.over)
for it in now if isinstance(now, (list, tuple)) else ():
if key(it) in taken:
continue
if ceiling is not None and len(taken) >= ceiling:
raise Stopped(
f"{stage.name!r} has taken {ceiling} items, all its `items-at-most:` allows",
"reached-a-limit",
)
taken.add(key(it))
running.add(asyncio.ensure_future(one(it)))
good = 0
try:
while running:
done, running = await asyncio.wait(running, return_when=asyncio.FIRST_COMPLETED)
for t in done:
joined = self.joined(stage, t, rule)
if joined is None:
continue
answered, answer = joined
answers.append(answer)
good += answered
if rule.met(good):
break
now = scope.read(stage.over)
for it in now if isinstance(now, (list, tuple)) else ():
if key(it) in taken:
continue
if ceiling is not None and len(taken) >= ceiling:
raise Stopped(
f"{stage.name!r} has taken {ceiling} items, all its `items-at-most:` allows",
"reached-a-limit",
)
taken.add(key(it))
running.add(asyncio.ensure_future(one(it)))
finally:
for t in running:
t.cancel()
if running:
await asyncio.gather(*running, return_exceptions=True)
return answers

async def together(self, stage: StageSpec, scope: _Scope, where: str) -> dict[str, Any]:
Expand All @@ -1131,9 +1189,7 @@ async def branch(s: StageSpec) -> dict[str, Any]:

async def branches(self, stage: StageSpec, work: list[Awaitable[dict[str, Any]]]) -> list[Any]:
"""Run branches side by side and join them by `teamwork.waits-for`."""
waits = str(stage.teamwork.get("waits-for") or "everyone").strip()
enough = int(stage.teamwork.get("enough-is") or 0)
on_failure = str(stage.teamwork.get("if-someone-fails") or "stop-the-others").strip()
rule = _JoinRule.of(stage)
tasks = [asyncio.ensure_future(w) for w in work]
got: list[Any] = [ABSENT] * len(tasks)
good = 0
Expand All @@ -1142,28 +1198,12 @@ async def branches(self, stage: StageSpec, work: list[Awaitable[dict[str, Any]]]
while pending:
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for t in done:
i = tasks.index(t)
if t.cancelled():
continue
err = t.exception()
if err is not None:
# The RUN was ended, not this branch: no `carry-on`
# carries on past it.
if isinstance(err, Cancelled):
raise err
if isinstance(err, (Stopped, Parked)) and on_failure != "carry-on":
raise err
got[i] = {"failed": str(err)}
if on_failure == "stop-the-others":
raise Stopped(
f"a branch of {stage.name!r} failed: {err}", "a-call-failed"
)
joined = self.joined(stage, t, rule)
if joined is None:
continue
got[i] = t.result()
good += 1
if waits in ("anyone", "the-first-good-answer") and good >= 1:
break
if waits == "enough-of-them" and enough and good >= enough:
answered, got[tasks.index(t)] = joined
good += answered
if rule.met(good):
break
finally:
for t in pending:
Expand All @@ -1172,6 +1212,25 @@ async def branches(self, stage: StageSpec, work: list[Awaitable[dict[str, Any]]]
await asyncio.gather(*pending, return_exceptions=True)
return [g for g in got if g is not ABSENT]

def joined(self, stage: StageSpec, t: "asyncio.Future[Any]", rule: "_JoinRule") -> tuple[bool, Any] | None:
"""One finished item or branch, as its join takes it: `(True, answer)`,
`(False, {"failed": ...})` when `if-someone-fails: carry-on` carries on
past it, or `None` when it was cancelled. A failure the join does not
carry on past is raised."""
if t.cancelled():
return None
err = t.exception()
if err is None:
return True, t.result()
# The RUN was ended, not this branch: no `carry-on` carries on past it.
if isinstance(err, Cancelled):
raise err
if isinstance(err, (Stopped, Parked)) and rule.on_failure != "carry-on":
raise err
if rule.on_failure == "stop-the-others":
raise Stopped(f"a branch of {stage.name!r} failed: {err}", "a-call-failed")
return False, {"failed": str(err)}

def combined(self, stage: StageSpec, answers: list[Any]) -> dict[str, Any]:
"""Each field of the answers made one by its `combines-by:` rule; a field
no rule names keeps every answer's value, in order."""
Expand Down
91 changes: 91 additions & 0 deletions adapters/python/tests/test_forks_stops_and_a_growing_each.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,94 @@ def tool(tool: str, action: str, inputs: dict) -> dict:
)
out = asyncio.run(run_workflow(spec, {"tasks": tasks}, Callers(tool=tool)))
assert out.halted == "stopped" and "items-at-most" in out.said, out


def _growing(teamwork: dict[str, Any], fails: tuple[str, ...] = ()) -> tuple[list[dict[str, str]], list[str], WorkflowSpec, Callers]:
"""t1 and t2 to start with; working t1 adds t3. `fails` names tasks whose call raises."""
tasks = [{"id": "t1"}, {"id": "t2"}]
done: list[str] = []

async def tool(tool: str, action: str, inputs: dict) -> dict:
task = inputs["task"]
done.append(task)
if task == "t1":
tasks.append({"id": "t3"})
await asyncio.sleep(0)
if task in fails:
raise RuntimeError(f"{task} broke")
return {"did": task}

spec = _flow(
{
"work": {
"does": "each",
"over": "input.tasks",
"keeps-taking": "yes",
"identified-by": ["id"],
"teamwork": teamwork,
"limits": {"items-at-most": 10, "at-once-at-most": 1, "when-it-runs-out": "stop-and-say-so"},
"starts-at": "do",
"steps": {"do": {"does": "call", "call": "q/run", "bind": {"task": "item.id"}}},
"then": {"answered": "reply"},
},
"reply": {"does": "answer", "bind": {"items": "steps.work.items"}},
},
"work",
)
return tasks, done, spec, Callers(tool=tool)


def test_a_growing_each_stops_taking_once_its_teamwork_rule_is_met() -> None:
tasks, done, spec, callers = _growing({"waits-for": "anyone"})
out = asyncio.run(run_workflow(spec, {"tasks": tasks}, callers))
assert out.halted == "final", out.said
# t1 and t2 run side by side under the gate, so both may have answered when the join reads the first; t3, which
# t1 added, is never taken.
assert out.steps["work"]["items"] and all(item.get("did") in ("t1", "t2") for item in out.steps["work"]["items"]), out.steps["work"]
assert "t3" not in done, "nothing is taken once the rule is met"


def test_a_growing_each_carries_on_past_a_failed_item_when_its_teamwork_says_so() -> None:
tasks, done, spec, callers = _growing({"if-someone-fails": "carry-on"}, fails=("t2",))
out = asyncio.run(run_workflow(spec, {"tasks": tasks}, callers))
assert out.halted == "final", out.said
assert sorted(done) == ["t1", "t2", "t3"], done
assert [item for item in out.steps["work"]["items"] if "failed" in item] != [], out.steps["work"]
assert {"did": "t3"} in out.steps["work"]["items"], out.steps["work"]


def test_a_growing_each_stops_at_a_failed_item_by_default() -> None:
tasks, done, spec, callers = _growing({}, fails=("t1",))
out = asyncio.run(run_workflow(spec, {"tasks": tasks}, callers))
# t2 may answer, and t3 be taken, before t1's failure ends the join; the run stops either way.
assert out.halted == "stopped" and "t1 broke" in out.said, out


def test_a_stop_undoes_what_the_stopped_run_did() -> None:
calls: list[tuple[str, dict]] = []

async def tool(tool: str, action: str, inputs: dict) -> dict:
calls.append((action, dict(inputs)))
if action == "print":
await asyncio.sleep(5)
return {}

spec = _flow(
{
"start": {
"does": "call",
"call": "printer/print",
"waits-for-result": "no",
"undone-by": "printer/cancel",
"bind": {"doc": "input.doc"},
"then": {"answered": "halt"},
},
"halt": {"does": "stop", "stops": "steps.start.run", "then": {"answered": "reply"}},
"reply": {"does": "answer"},
},
"start",
)
out = asyncio.run(run_workflow(spec, {"doc": "a"}, Callers(tool=tool)))
assert out.halted == "final", out.said
assert out.steps["halt"] == {"stopped": True}
assert calls[-1] == ("cancel", {"doc": "a"}), calls
2 changes: 1 addition & 1 deletion docs/90-REVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ them and changes nothing.
|---|---|
| Schema | **43 groups, 262 field entries, 207 distinct field names** (core 123, expert 69, both 15), 40 closed enums, 27 cross-reference constraints, **0 fields missing `tier:` or `surface:`** |
| Rust | 5 crates, **1733 tests**, `unsafe_code = forbid`, clippy-deny, edition 2024 |
| Python | **47 modules** (`find adapters/python/src -name "*.py" \| wc -l`), **3661 tests**, **nine transports** — seven model-bound (`anthropic`, `autogen`, `langchain`, `langgraph`, `ollama`, `openai_agents`, `pydantic_ai`), one bound to a remote *agent* (`a2a`), one deterministic mock; `_metering.py`, `_summarise.py` and `_tool_choice.py` are shared code the transports import, which is what the `_` says — offline by default |
| Python | **47 modules** (`find adapters/python/src -name "*.py" \| wc -l`), **3665 tests**, **nine transports** — seven model-bound (`anthropic`, `autogen`, `langchain`, `langgraph`, `ollama`, `openai_agents`, `pydantic_ai`), one bound to a remote *agent* (`a2a`), one deterministic mock; `_metering.py`, `_summarise.py` and `_tool_choice.py` are shared code the transports import, which is what the `_` says — offline by default |
| TypeScript | 5 modules, 2,305 lines, a second port of **the stepping, the ceilings and the stage path** (`harness.ts:15-21`: *"AC-5.3's bar is the stage path"*) — **not** of the loop entire: no interceptor chain, no durable suspension record, no ledger (`notDoneHere`; a park returns `halted: "suspended"` and writes nothing down). This row is load-bearing for the Phase 3 pricing below (E4) |
| CLI | **6 verbs**: `check`, `show`, `waits`, `discover`, `card`, `help` |
| Worked example | 42 files, 1128 lines, **132 distinct authored keys**, `pact check` → OK (498 settings) |
Expand Down
Loading