Chapter 2 – The Deterministic Sandwich
Chapter 1 used a deterministic renderer because the transformation was fully specified: reproduce an extracted inventory exactly. Replacing that renderer with a model would add variance without adding judgment—an expensive renderer with a creative streak.
This chapter keeps the renderer and adds one bounded editorial
choice. The Map gains a short Usage block. Deterministic
Prep supplies the exact signatures, several pinned behavioral cases, the
explanatory objective, and the permitted edit region. The model may
select and arrange one example that shows the two functions interacting;
it may not rewrite the inventory or invent behavior.
Suppose the pinned tests establish four observations, forming two eligible example pairs:
normalize_country(" is ") == "IS"
calculate_tax(100, "IS", 0.24) == 24
normalize_country(" us ") == "US"
calculate_tax(64, "US", 0.25) == 16
The first model attempt selects the Iceland case but writes
24 where the supplied rate is 0.24. The
example is syntactically plausible and stays inside the permitted block.
Execution against the pinned source produces 2400, not
24, so deterministic Validation rejects it with an
EXAMPLE_ASSERTION_FAILED finding.
The second attempt composes the first pair of pinned observations:
country = normalize_country(" is ")
tax = calculate_tax(100, country, 0.24)
assert country == "IS"
assert tax == 24Validation confirms that the example uses the extracted signatures,
executes against the pinned source, derives its claims from the selected
tests, and changes only the permitted block. Proposal closure ends the
run complete with a supported proposal, and the runtime
seals the Run Record. A separate Adoption event rechecks the current Map
state and makes the exact candidate authoritative. Any earlier staging
remains non-authoritative.
This extends the Chapter 1 loop without surrendering its deterministic work. The exact inventory remains mechanically rendered; only the judgment-bearing example becomes probabilistic. Once the extended Mission is activated, its intent, scope, evidence requirements, routing, Run Record sealing, and separate Adoption remain fixed across both attempts. The Validator is still decisive because each evidence class has one declared destination.
The checks establish grounding, execution, and scope. They do not establish that the example is the clearest possible explanation. Choosing among several supported cases and arranging one compact explanation remains judgment-bearing work. If policy fully specifies that choice as well, a deterministic renderer is again the better tool. The result is the pattern in miniature: one probabilistic choice pinned between deterministic stages.
The loop can propose a diff and stop on PASS/FAIL. Its
authority and effect limits remain unchanged when it gains a
probabilistic step. Deterministic Prep and Validation make input
construction and output evaluation repeatable; they reject outputs that
violate the declared contract. Large language models (LLMs) vary: the
same task can produce a different diff on another attempt. In
production, regressions hide in that variance.
Longer instructions alone are not the fix. The architectural fix is
structure: Prep -> Model ->
Validation. That structure is the Deterministic
Sandwich.
The Deterministic Sandwich: Prep, Model, Validation
The Deterministic Sandwich places one probabilistic invocation between reproducible input preparation and deterministic output validation. The larger workflow supplies the authority and effect boundary. In this teaching case, one model call inside the Effector sits between the two deterministic layers:
One probabilistic invocation
The Deterministic Sandwich
Deterministic preparation constructs the request. One probabilistic step proposes a candidate within named limits. Validation outside candidate authority parses and checks the result.
Read the activated work contract, select a bounded Context Packet, and construct the required input shape.
A model, agent, harness, CLI, service, or child workflow returns one candidate output.
Parse strictly, check the Mission's properties and effects, and emit structured findings.
Intent, authority, input contract, output schema, checks, budgets, and stopping rules.
The candidate produced by the probabilistic step and the findings returned about it.
A Validator result is evidence for routing. It is not Admission or Adoption, and a retry policy belongs to the enclosing workflow.
Prep: A deterministic setup layer. It normalizes the request, builds a bounded context slice, and keeps untrusted evidence separate from actual instructions. It takes structured data and produces a structured model request.
Model: The single bounded model call. In this minimal sandwich, it is the only unpredictable step, so its surface area remains small.
Validation: A deterministic gate. It strictly parses the model output and runs Validators. It accepts the output only if it matches the declared rules.
The pattern resembles a reliable wrapper around a flaky external service. Prep controls what enters the service, Validation controls how its output is interpreted, and anything that breaks the contract is rejected.
Prep and Validation are both deterministic,
but they guard different boundaries. Prep controls inputs;
Validation controls outputs. The model remains one bounded
Effector between them.
Deterministic execution does not imply a complete specification. A Validator can return the same answer every time and still check the wrong rule or miss an important case. Chapter 3 owns that problem; here the requirement is simply that the model cannot bypass the checks that exist.
1. Prep: Build the request deterministically
Prep reads the fixed work contract—formalized in Chapter
7 as an activated Mission Object—and builds the same request shape from
the same inputs. It tags repository content, tickets, logs, chat, and
prior findings as provenance-bearing evidence rather than instructions.
Mixing those channels lets hostile or accidental prose compete with the
actual rules.
For this extension of the Chapter 1 doc sync, Prep needs
only the extracted signatures, selected behavioral cases, bounded
explanatory objective, permitted Usage block, and any
normalized Validator finding. The deterministic renderer handles the
signature inventory before the model runs. Structural facts remain
mechanical; the model receives only the evidence needed to choose and
arrange an example.
The failure mode is Map Contamination: invented structure or behavior enters a Map, then later runs consume the invention as fact. Validation therefore compares referenced signatures with a fresh extraction, executes the example against the pinned source, compares its claims with the selected cases, and fails on any mismatch.
2. Model: The probabilistic step in the minimal sandwich
Within this minimal sandwich, selecting and arranging the usage example is the only probabilistic step. The request requires a declared shape, such as a unified diff or strict JSON, and the result remains an untrusted candidate. Fully specified transformations stay outside the model call.
That is a property of this teaching pattern, not a rule that larger workflows contain only one probabilistic step. A larger workflow may arrange several such steps sequentially, conditionally, or in parallel.
3. Validation: The hard gate
Validation parses the output strictly, checks its schema and semantics, and rejects the whole candidate on any failure. No regex repair or partial application. A stable finding identifies the governed property, the affected surface or location when available, a machine-readable reason, and the evidence supporting it. Chapter 3 owns that finding contract; Chapter 5 owns retry and stopping policy.
The failed first attempt in this trace shows why the finding must name the assertion failure without changing target or scope. A later attempt may receive that finding as evidence, but Chapter 5 owns the retry and stopping policy.
Beyond One Model Call
To extend the Sandwich to larger systems, distinguish a workflow from a loop. A workflow is the finite governed graph of steps. A loop is the declared repetition of a step, a subsequence, or the complete workflow. Continuous operation is therefore a sequence of finite runs with fixed authority, terminal outcomes, and sealed Run Records, not one immortal run whose state and rules drift indefinitely.
The same pattern can wrap a larger worker exposed through a command-line interface (CLI) or application programming interface (API). From the enclosing workflow’s viewpoint, that worker remains one bounded component with declared inputs, effects, budget, output, and evidence. This book calls a worker that manages model-and-tool use inside that boundary an agent harness; a component with its own finite governed lifecycle is a child workflow. Part III develops the contracts that make such components reusable; Chapter 14 develops nesting and local acceptance.
The Admission Horizon is the property-specific boundary at which an exact candidate becomes effective in Terrain. Recursive composition can push that boundary outward for a selected Terrain property by keeping supported child outputs provisional as parent inputs. This can concentrate human attention on a later, higher-consequence Admission. Admission remains an authority event and need not be manual: adopted policy may authorize lower-risk Admissions without a new human decision.
That deferral applies only while the intermediate output remains provisional for the relevant Terrain property. A staging deployment, publication, shared-state mutation, resource use, data access, network call, notification, or other external action is already an effect. It must be authorized and enforced at its declared effect boundary. A later Admission cannot relabel an earlier effect as provisional.
When Slicing Goes Wrong
The previous example assumed good context. Here’s what it looks like when the slice is bad.
If Prep includes the whole source tree and document, the
model may update the right block and rewrite adjacent material. The
scope Validator makes the slicing error visible by reporting that the
candidate touched both the permitted interface block and an undeclared
notes section.
The diagnosis is not “bad model behavior.” The slice included adjacent material that looked like instructions or editable scope even though the task did not authorize changes there. The correction is a new Context Packet under the Mission’s fixed bindings, limited to the extracted skeleton and allowed edit region. If those bindings cannot produce the required packet, the run must stop. Further work requires a new Mission. Chapter 6 names the broader context-quality objective and develops the full method.
When the Pattern Is Worth It
The Sandwich is worthwhile when work repeats, persists, has material blast radius, crosses team boundaries, or can be judged by an actionable invariant. A temporary artifact with a cheap and direct acceptance signal may need only generation and inspection. A persistent capability with hidden obligations needs stronger boundaries.
A practical starting point is one bounded Effector and one gate. Structured findings support retries. A Mission supplies stable authority across tasks or operators. Templates address request drift once it becomes a real failure mode. Generated scaffolding is cheaper than it used to be; ownership, calibration, and false positives still cost engineering time.
AI is especially useful when mature libraries or services already contain the difficult implementation logic and stable interfaces constrain the connecting work. Direct checks can grade the declared composition. The probabilistic step does not need to reproduce every internal detail; it needs to connect the components within their contracts and the workflow’s effect boundary.
The reusable asset is the control surface. New workflows can replace the extractor and Validator while preserving the output contract, evidence shape, and stopping policy. Tooling may differ by stack; the boundary does not.
The Sandwich is therefore more than a safe model wrapper. Its stable contracts let it become a dependable step in a larger workflow. A malformed output or out-of-scope effect must fail before application; only the candidate may vary while the surrounding authority, acceptance protocol, and evidence contract remain fixed.
The organizational consequence is that candidate volume can increase without giving every candidate a direct path to production. The surrounding process, rather than the probabilistic step, continues to determine what evidence is required and what may advance.