TL;DR
- Deterministic code generation starts with a function that takes a validated specification and locked inputs, then returns an in-memory manifest of paths and bytes. Resolve packages, inspect the filesystem, and write outputs at the boundaries. Replaying the same inputs under the same toolchain should produce the same manifest.
- Normalize fields whose order has no meaning. Preserve the order of route rules, middleware, migrations, and any declarations where precedence matters. Treat templates, dependency content, the runtime, and the formatter as inputs. Two green runs on one laptop provide limited evidence of determinism.
- Check code generation at both the byte and behavior levels. Golden files catch accidental layout, import, and naming changes. Compilation and semantic tests catch regressions a blanket update of the golden files would otherwise approve. Publish a complete verified artifact when readers need a consistent tree.
Where stateful generators become hard to review
Consider a platform team maintaining a scaffold that generates API route metadata, authorization policies, and database wiring for dozens of services. A pull request adds one export. On the author’s machine, it changes one module. In continuous integration, it also reorders an unrelated route file, because an installed formatter version differs. A third run retrieves a newer package from a remote resolver and changes more files, despite using the same application spec. Review time goes into explaining differences between runs instead of examining the change that triggered them.
An imperative scaffolder is easy to start. Read a spec, walk some folders, inspect existing files, call a renderer, and write each file immediately. This works for creating a repository once. Repeated generation gives all of those activities a chance to influence output. A failed run may leave half of the generated tree replaced, or preserve files from an old spec silently. Retrying it can then observe the residue and produce yet another result. Renaming a module can look like a successful addition while the previous file still participates in a framework’s discovery step.
The boundary to define is the set of inputs that explains every output byte. If the operation consults the current time to add a header, the clock is an input. If the template scans a folder to find plugins, a directory listing is an input. If the CLI picks up a repository’s default formatter settings, the formatter configuration is an input. Giving those dependencies names makes it possible to lock, test, and review them. Remove incidental dependencies such as build time from emitted source unless the product needs them.
Decide when byte stability matters before designing the implementation. Generated code checked into client repositories needs stable diffs across many developer environments. A generated archive used only within a pinned build environment has a narrower requirement. A one-time bootstrap may accept manual editing and treat the generator’s initial output as disposable. The architecture below assumes repeated generation and a reviewable manifest.
Design a pure code generator around a file manifest
Resolve input, normalize a model, then emit bytes
Use three stages. An outer stage reads files, resolves dependency versions, and checks the lock. It records explicit inputs, including the generator and template versions. The compiler stage validates the spec and translates it into a domain model. A renderer translates that model to an ordered manifest of relative paths, bytes, and digests. The final boundary publishes the manifest and its files. During compiler and rendering tests, a developer can work entirely in memory.
A domain model is useful because it names the order of operations and the meaning of defaults. Specify whether a list of flags is a set, whether two route names are allowed to collide after normalization, and whether an omitted action has the same meaning as an explicit default. Sorting every list can make output stable while changing behavior. If literal presentation matters, keep both the source declaration order and a normalized representation so each renderer can use the one its contract requires.
Represent file paths with a single portable convention. Detect duplicate names before rendering, including case-fold collisions when contributors or consumers use case-insensitive filesystems. Keep user-generated names within a documented grammar. A relative path can be valid on one target and unsafe or reserved on another. Keep executable mode and metadata in the manifest when they affect deployment. The example below generates ordinary Python modules with ASCII names and lowercased identifiers, which narrows the portability problem.
Use ASTs for syntax and templates for stable layout
Use Python’s abstract syntax tree when constructing code from identifiers, data literals, or nested expressions. The tree API provides a syntax-aware representation, and compile() can reject malformed modules before publication. ast.unparse() outputs code intended to recreate an equivalent AST when parsed. It has no byte-stability contract across Python releases, and it does not preserve comments and formatting from source. Pin the runtime or formatter if its representation forms part of the generated artifact. Python AST documentation.
A template can be clearer for stable configuration and documentation shapes. Jinja renderers can set StrictUndefined, choose a newline sequence, and preserve the intended final newline. Keep the template context immutable from the compiler’s perspective and avoid implicit filesystem or network access in helpers. File type determines escaping. A template that inserts strings into SQL or Python needs a serialization or syntax-aware boundary appropriate to that target. Jinja environment options.
Implement a deterministic manifest and test it
Compile a small spec to Python modules
This Python 3.12 example produces one generated policy module per service. A checked-in project can replace the minimal release label with its real lock identity. The example treats scopes as a set with duplicates rejected, guaranteeing a canonical order for equivalent inputs. Error messages identify invalid identifiers or duplicate service declarations before any output is written.
# generator.py — run within the same locked Python 3.12.x release
import ast
import hashlib
import keyword
import re
from dataclasses import dataclass
@dataclass(frozen=True)
class Policy:
service: str
scopes: tuple[str, ...]
@dataclass(frozen=True)
class OutputFile:
path: str
data: bytes
sha256: str
def generate(policies: tuple[Policy, ...], *, lock_digest: str) -> tuple[OutputFile, ...]:
if not re.fullmatch(r"[0-9a-f]{64}", lock_digest):
raise ValueError("expected lowercase SHA-256 lock digest")
files: list[OutputFile] = []
names: set[str] = set()
for policy in sorted(policies, key=lambda entry: entry.service):
name = policy.service
if not re.fullmatch(r"[a-z][a-z0-9_]{0,47}", name) or keyword.iskeyword(name):
raise ValueError(f"invalid service module name: {name!r}")
if name in names:
raise ValueError(f"duplicate service: {name}")
names.add(name)
if len(set(policy.scopes)) != len(policy.scopes):
raise ValueError(f"duplicate scope for {name}")
if any(not re.fullmatch(r"[a-z0-9:_-]{1,80}", scope) for scope in policy.scopes):
raise ValueError(f"invalid scope for {name}")
# Build a literal AST so scope values never become Python syntax.
tree = ast.Module(
body=[ast.Assign(
targets=[ast.Name(id="SCOPES", ctx=ast.Store())],
value=ast.Tuple(
elts=[ast.Constant(scope) for scope in sorted(policy.scopes)],
ctx=ast.Load(),
),
)],
type_ignores=[],
)
path = f"policy_{name}.py"
compile(ast.fix_missing_locations(tree), path, "exec")
header = f"# Generated from lock {lock_digest}\n"
data = (header + ast.unparse(tree) + "\n").encode("utf-8")
files.append(OutputFile(path, data, hashlib.sha256(data).hexdigest()))
return tuple(files)
The input boundary can parse JSON or YAML into Policy and reject unknown keys, wrong types, and duplicate keys before calling generate. The renderer’s small validation layer checks domain constraints as defense against callers bypassing that parser. Treat the lock digest as provenance. Passing a string into this function does not verify packages or templates on disk. The resolver must compute the digest from the approved lock bytes and independently verify materialized content.
Use a golden file and a semantic test
A useful test changes input ordering and also confirms that the output compiles and the policy manifest retains its intended values. The small golden fixture below lives inline to make whitespace and the digest header visible. In a larger generator, store expected outputs as fixture files and require actual product tests to pass before updating them.
# tests/test_generator.py — run python -m pytest from the project root
import ast
import hashlib
import pytest
from generator import Policy, generate
LOCK = "a" * 64
def test_generation_is_stable_and_preserves_policy():
specs = (
Policy("reporting", ("reports:write", "reports:read")),
Policy("billing", ("invoices:read",)),
)
modified_order = (
specs[1],
Policy("reporting", tuple(reversed(specs[0].scopes))),
)
output = generate(specs, lock_digest=LOCK)
assert output == generate(modified_order, lock_digest=LOCK)
assert [entry.path for entry in output] == ["policy_billing.py", "policy_reporting.py"]
expected = f"# Generated from lock {LOCK}\nSCOPES = ('reports:read', 'reports:write')\n"
assert output[1].data == expected.encode("utf-8")
assert output[1].sha256 == hashlib.sha256(output[1].data).hexdigest()
tree = ast.parse(output[1].data)
assert ast.literal_eval(tree.body[0].value) == ("reports:read", "reports:write")
def test_duplicate_service_is_an_error():
policy = Policy("reporting", ("reports:read",))
with pytest.raises(ValueError, match="duplicate service"):
generate((policy, policy), lock_digest=LOCK)
The sample generator has no third-party runtime dependency. The project configuration below sets the interpreter range and test dependencies for the example. A deployed generator should also pin the full Python patch release or container digest and freeze dependencies through its resolver. Run the same fixture with different hash seeds, zones, working directories, and fresh checkouts. Changing only the process environment shouldn’t alter a manifest whose inputs were held fixed.
[project]
name = "policy-generator"
version = "0.1.0"
requires-python = "==3.12.*"
[project.optional-dependencies]
test = ["pytest==8.3.5"]
[tool.pytest.ini_options]
addopts = "-ra"
testpaths = ["tests"]
Once a manifest passes validation, write it to a private staging directory and verify file counts and digests. A single file replacement can be atomic on a supported filesystem when the source and destination share that filesystem. Replacing a tree one file at a time gives readers a chance to see a mixture of generations. Use an immutable release directory and switch a single publication reference if consistent hot reads matter. Keep earlier generations until outstanding readers finish, then prune with an ownership check. Python atomic replacement documentation.
Failure modes worth testing before publishing
An output collision silently overwrites a generated module
Two entities can normalize to the same slug, especially during an API rename or when a downstream filesystem ignores case. The symptom appears as a missing handler or a duplicate-looking commit depending on the write order. Validate portable paths and track ownership before emission. Make the conflict list both source entities so the author knows what to change.
Perfectly stable sorting changes behavior
A compiler sorts middleware entries or routing rules to reduce diffs. Generated bytes remain stable, but a broad catch-all rule shadows a more specific rule. Document whether each list is ordered by design. Generate from source order for precedence-sensitive constructs and add behavioral tests where two declarations overlap. Reserve lexicographic order for fields with set semantics.
A pinned package version changes its resolved content
The resolver finds a different platform artifact or a template directory contains uncommitted changes. A version label alone cannot account for identical output. Verify checksums for resolved artifacts and pin the platform where binary dependencies influence formatting or code emission. If build dates are required in packaging, derive them from an explicit input such as the revision metadata. Reproducible Builds guidance on stable timestamps.
A removed declaration leaves an old module on disk
The emitter writes new files in place but never removes previously generated ones. Your runtime discovery code still finds the deleted policy. Compare a new manifest with the old owned manifest, and distinguish manual files from generated files before deleting anything. Publishing a fresh tree under the output root keeps ownership clear, while source-controlled code generation may need an explicit diff and a deletion plan.
Compare pure generation with other approaches
One-time templating suits bootstrap workflows where a team takes ownership immediately after creation. The initially generated project can be reformatted and edited freely. If multiple teams need a breaking shared update later, migrations or package updates may be easier to reason about than reapplying the scaffold.
In-place syntax transformations are appropriate when edits to existing handwritten code need to survive. A concrete syntax tree can preserve comments and whitespace more accurately than parsing and unparsing with the built-in AST. The tradeoff is a larger input contract that includes the exact source files, formatting decisions, and conflict behavior.
Runtime configuration removes generated source altogether for capabilities that can be expressed as validated data consumed by one library. Choose it when deployment, auditing, and latency requirements allow that dependency. Generate static files when artifacts need to be reviewed, packaged, or consumed by separate tools without a shared runtime.
Size the manifest and separate render time from write time
Suppose a hypothetical generator emits 600 files averaging 3 KiB each. Raw output is about 1.76 MiB before metadata and object overhead. Keeping that manifest in memory is reasonable for many build workers, and it is cheap enough to diff several candidate versions. The same design at 100,000 files averaging 40 KiB emits about 3.81 GiB, which may exceed the worker’s memory budget. Preserve the generator boundary at that scale by rendering to a content-addressed staging store with a bounded working set and an ordered manifest of digests.
Benchmark parsing, rendering, hashing, and writing separately. Measure the warm and cold cases with the same spec and lock. Reusing a local cache can make a second run look faster while bypassing the code path that introduced nondeterminism. Add a clean-run comparison to CI and decide which artifact changes require reviewer approval.
Frequently asked questions
What makes a code generator deterministic?
A deterministic code generator produces the same paths and bytes when the validated spec, dependency content, templates, and toolchain are equivalent under a defined contract. A pure rendering function makes that property easier to test. Treat clocks, filesystem enumeration, and network results as explicit inputs when they legitimately affect output.
Should I use an abstract syntax tree or a template for code generation?
Use an abstract syntax tree when you build identifiers, expressions, or data literals from a spec and need syntax-aware construction. Use a template when the shape is mostly stable and readers benefit from a visible skeleton. Teams often combine them. Pin formatting behavior and validate generated syntax whichever rendering approach you use.
Do golden tests prove a code generator is safe to update?
Golden tests prove that selected fixture outputs match expectations byte for byte. Pair them with compilation, invariant checks, and tests for representative input permutations. For anything consumed by another process, also test partial failures and ensure readers can recover or continue from the previous release if publication is interrupted.
Further reading
- Alembic migrations with compatible deployment stages
- PostgreSQL double-entry ledger invariants
- Python 3.12 abstract syntax tree reference
Review your generator contract
If you’re standardizing deterministic code generation across multiple repositories, talk to our engineering team about spec design, reproducible CI, or a staged replacement for an existing scaffolder.
