Skip to content

Verified Template Runtime

wolfxl.Template compiles a reporting workbook once, executes isolated jobs into managed temporary artifacts, verifies each result, and publishes only after an explicit commit() call.

Use this API when a report must preserve the source workbook, validate typed input, and keep failed or unverified output away from caller destinations. Use workbook.reporter directly when the caller already owns the workbook lifecycle and does not need a verify-before-publish boundary.

Compile once

from wolfxl import Template

monthly = Template.compile(
    "monthly-report.xlsx",
    schema={
        "company": str,
        "period": str,
        "transactions": list[dict],
    },
    policy="strict",
)

Template.compile(...) reads the source into immutable owned bytes and records:

  • the source SHA-256
  • template language version
  • scalar, image, conditional, and repeated-block marker program
  • required and optional typed inputs
  • projected row-expansion limit
  • workbook feature manifest
  • deterministic schema and template fingerprints

Compilation does not mutate or execute workbook content. Strict compilation rejects malformed package input, unsafe relationship targets, malformed or unpaired markers, fields absent from the schema, structural collisions, expansion beyond the configured limit, and digitally signed packages. A signed package cannot remain valid after modification, so it is rejected rather than silently published with a broken signature.

The current template language version is "1". It reuses the reporting marker language:

{{ customer.name }}
{{#each orders}}
{{item.sku}}
{{/each}}
{{#if customer.active}}
...
{{/if}}
{{image customer.logo}}

The compiler accepts a mapping of field names to Python annotations or an annotated class. A field whose annotation accepts None is optional. Runtime input may be a mapping or a dataclass instance. Strict validation rejects missing required fields, extra fields, and values that do not match their annotations before a workbook is loaded.

Stage, verify, commit

from wolfxl import TemplateRenderOptions

run = monthly.render(
    {
        "company": "Acme",
        "period": "2026-Q3",
        "transactions": [
            {"account": "Subscriptions", "amount": 400},
            {"account": "Services", "amount": 100},
        ],
    },
    options=TemplateRenderOptions(
        calculate=True,
        recompute_pivots=True,
        produce_pdf=True,
    ),
)

verification = run.verify()
if verification.passed:
    result = run.commit(
        xlsx="monthly-report-output.xlsx",
        pdf="monthly-report-output.pdf",
    )
else:
    run.cleanup()

render(...) never accepts a destination. It clones the admitted source into a new workbook, then runs the existing reporting stages in fixed order:

  1. strict typed input and marker preflight
  2. row and nested-block expansion
  3. scalar and image population
  4. optional formula calculation
  5. optional native worksheet-backed pivot recomputation
  6. a second calculation pass when pivot output changed cells
  7. managed XLSX staging
  8. optional managed paginated PDF staging

The returned TemplateRun owns unique temporary paths. Those paths are private and removed by cleanup() or the context-manager protocol. A failure in any stage removes the job's managed directory and never changes a caller destination.

verify() checks the staged hashes, OOXML readability, worksheet order, remaining template markers, protected package content, requested calculation status, requested pivot status, and PDF render diagnostics. Protected package content includes VBA, external links, embedded and ActiveX objects, control properties, and custom XML. Verification returns a TemplateVerification; only passed=True creates a TemplateAttestation and moves the run to verified.

The attestation binds the source, schema, template program, engine build, XLSX hash, optional PDF hash, requested computation stages, and verification time. It contains no customer values or workbook bytes.

commit(...) is the only publication operation. It:

  • requires a verified run
  • refuses existing destinations
  • copies each staged artifact to a private sibling on the destination filesystem
  • verifies the sibling hash
  • publishes each artifact with an atomic no-replace hard link
  • removes every destination created by the call if a later publication step fails while the process is running

Each destination becomes visible atomically and is never overwritten. A multi-artifact commit is rollback-safe for in-process failures. Ordinary filesystems do not provide a crash-atomic transaction across two independent pathnames, so applications that require that stronger property should commit into an isolated output directory and publish the directory as their own transaction boundary.

A committed run no longer owns temporary artifacts. Cleanup never removes committed destinations.

Results and lifecycle

The standard wheel exports these types from both wolfxl and wolfxl.template:

  • Template, CompiledTemplate, TemplatePolicy, TemplateSchema, and TemplateSchemaField
  • TemplateRenderOptions, TemplateExecutionReport, TemplateRun, and TemplateRunState
  • TemplateVerification, TemplateVerificationFinding, and TemplateAttestation
  • TemplateCommitResult and TemplateBatchResult
  • TemplateError, TemplateCompileError, TemplateValidationError, and TemplateStateError

A run moves through this state machine:

staged -> verified -> committed
   |          |
   |          +-> discarded
   +-> rejected -> discarded
   +-> discarded

verify() is idempotent after success. A rejected, discarded, committed, or unverified run cannot be committed again.

Bounded batch execution

results = monthly.render_many(
    jobs,
    options=TemplateRenderOptions(calculate=True),
    max_concurrency=8,
    max_jobs=500,
)

for result in results:
    if result.succeeded:
        assert result.run is not None
        verification = result.run.verify()
        # Choose the destination from caller-owned job metadata, then commit.
    else:
        print(result.index, result.error_type, result.error_message)

render_many(...) materializes at most max_jobs inputs before starting work, uses at most max_concurrency isolated worker processes, and returns results in input order. One job's failure does not cancel or mutate a sibling job. Temporary directories are generated independently, so jobs do not share output paths.

Concurrent batch workers cannot execute a caller callback or share a thread-based cancellation token safely across process boundaries. Use max_concurrency=1 when progress or cancellation_token is set. Cancellation stops a serial batch before another job is scheduled.

Resource bounds:

  • max_concurrency: 1 through 64
  • max_jobs: 1 through 1,000
  • source size default: 256 MiB
  • staged output default: 512 MiB per artifact
  • expanded rows: never above Excel's 1,048,576-row limit

timeout_seconds defaults to 300 seconds and is a monotonic deadline checked between synchronous load, population, calculation, pivot, save, and render stages. It is not a preemptive interrupt: a native stage that is already running can finish after the deadline, after which the run fails and its managed temporary outputs are removed.

Preservation and unsupported boundaries

Macros and other admitted active package content are preserved as inert bytes; the runtime never executes VBA, refreshes Power Query, follows external links, or invokes an embedded object. Requested pivot recomputation is limited to supported worksheet-backed pivots. Requested PDF output must have no unsupported render diagnostics before publication.

Templates that rely on external or OLAP pivot refresh, signed package mutation, unsupported rendering fidelity, or another unverified boundary fail before publication. The original source and every caller destination remain unchanged.

Durable monthly operating-review jobs

wolfxl.report_factory adds a durable job boundary around the built-in monthly operating-review workflow:

from pathlib import Path

from wolfxl.doctor.passport import create_workbook_passport
from wolfxl.report_factory import (
    MonthlyOperatingReviewRequest,
    ReportFactoryStore,
    ReportJob,
    manifest_digest,
    run_monthly_operating_review,
)

request = MonthlyOperatingReviewRequest.from_dict(request_document)
passport = create_workbook_passport(
    Path(request.template_path),
    requested_operations=("set_cells", "set_formulas"),
)

# Present passport.to_dict() to an authorized reviewer. After acceptance,
# bind that exact Passport and template version to the job:
reviewed_passport_sha256 = manifest_digest(passport.to_dict())
outcome = run_monthly_operating_review(
    request,
    store=ReportFactoryStore("report-store"),
    reviewed_passport_sha256=reviewed_passport_sha256,
)

The store addresses immutable template registrations and job manifests by SHA-256. prepare_job_manifest(...) derives identity without claiming or executing a job. A successful execution records the accepted receipt and artifact lineage before it publishes the paired XLSX and PDF destinations.

Computing the digest is not a substitute for review. A host must present the exact Passport document when its decision is review_required and pass the digest only after acceptance. The digest binds acceptance to the current template bytes, so any template change invalidates it. A compatible Passport does not require a review digest; an unsupported Passport cannot execute.

Repeating the same logical request does not regenerate accepted artifacts. It returns replayed when both destinations already match lineage, republishes verified store artifacts when both destinations are absent, and rejects a partial or divergent destination pair. PublicationMode.DEFERRED records accepted artifacts without touching caller destinations.

The job event stream is audit evidence, not job truth. Recovery may remove only a torn final event record while retaining every valid prior record. Immutable lineage is the commit point; unlineaged receipt or artifact residue is discarded before a retry. Job claims use a crash-releasing process lock, so a terminated worker cannot permanently wedge a content-addressed job.

Durable production batches

wolfxl.runner executes bounded sets of Factory requests with one parent-owned journal and spawn-isolated workers:

from wolfxl.runner import BatchRequest, RunStore, execute_batch, resume_run

job = ReportJob.from_request(
    request,
    reviewed_passport_sha256=reviewed_passport_sha256,
)
store = RunStore("batch-runs")
batch = BatchRequest.from_dict(
    {
        "schema_version": 2,
        "policy": "per_job",
        "max_concurrency": 4,
        "items": [job.to_dict()],
    }
)
receipt = execute_batch(store, batch)
receipt = resume_run(store, receipt.run_id)

Run identity and item manifest hashes are derived by the local store and Factory; clients do not supply either as authority. The parent process is the only journal writer. Workers return immutable item outcomes, and every successful run receipt reconciles its artifact and receipt hashes with Factory lineage.

per_job publishes each accepted job independently. all_or_nothing stages every accepted job, preflights the complete publication set, and compensates a failure within the live commit process. It does not claim a crash-atomic transaction across independent filesystem paths. After interruption, resume_run(...) re-enters staged items through Factory replay or republish, settles every item, and then records the terminal run receipt.

Cancellation is an immutable request marker. It is observed before dispatch, between serial items, and after active workers return; it does not erase committed evidence or report unfinished work as success. A torn final journal event may be repaired without changing immutable job truth.

The installed CLI emits one canonical JSON document:

wolfxl-runner run batch.json --run-root batch-runs
wolfxl-runner resume RUN_ID --run-root batch-runs
wolfxl-runner cancel RUN_ID --run-root batch-runs
wolfxl-runner show RUN_ID --run-root batch-runs