Skip to content

solvi.experimental.experience

Finite joint alternatives, bounded acquisition, external outcomes and scalar programs with empirical or finite-domain admission. Read executable experience before using the environment and recovery interfaces.

Finite reasoning and externally checked executable experience (experimental).

BudgetStop

Bases: RuntimeError

Stopped between two steps: what is left of the budget would not cover the next one (a slow path's next round, a refinement's next round, a generator's next request).

WorkBudget

WorkBudget(limit: int, *, on_charge: Callable[[dict], None] | None = None)

Integer work units shared by reasoning, observations, search and execution.

The host declares the units, including observation prices. Counts retain the category vector; they are not dollars or a promise about wall time. A sink runs after debit and before its caller executes the paid operation. A durable host can bind this sink to KnowledgeStore.note. Sink failure stops the caller; recovery must reconcile the recorded ledger, never reset it.

CompetenceRegistry

CompetenceRegistry(grammar: Grammar, *, store=None, allowed_sources=('environment', 'human', 'audit'))

propose_program

propose_program(program: Program, proposal_examples, budget)

Register a host-proposed AST after paid proposal validation, without dependencies.

derive

derive(program: Program, proposal_examples, dependencies, budget)

Host-proposed immutable AST composition; not autonomous discovery.

Every named dependency must occur as an exact expanded AST subtree. Execution charges all expanded nodes through ordinary Program.evaluate.

SQLiteEnvironment

SQLiteEnvironment(path, cases=None, *, identity='environment')

Durable Environment protocol adapter with process-safe attempt replay.

cases is required only when creating a new environment. On reopen, supplied cases must match the normalized original configuration. The parent directory must already exist. Each operation uses its own connection.

FiniteEnvironment

FiniteEnvironment(cases: dict[str, dict], *, identity='environment')

Two tiny executable families with idempotent external attempts.

Cases accept family, x, y, mechanism (v1/v2), announced_version, threshold (default 4), and noise (0/1). Resource cases require x >= y. The resource v2 interaction charges one extra unit when x reaches threshold. Workflow v1 stages run in parallel; v2 stages run sequentially.

state property

state

Detached private host audit state; not learner input.

restore classmethod

restore(snapshot, *, identity=None, cases=None)

Validate history with pure transitions; never execute external work.

Optional identity/cases pin the expected host configuration on reopen.

Environment

Bases: Protocol

Trusted host adapter; identity is not network authentication.

execute must be idempotent by attempt ID, or reconcile must settle whether its effect happened. Unknown outcomes must not be retried blindly. A serializable receipt is not proof of truth against a hostile host.

observe payload: {"probe": name, "field": field}; receipt value: {"field": field, "value": measured_value}. act payload: {"answer": value}; receipt value: {"answer": independently_observed_correct_answer, "ok": bool, ...}.

ExperienceJournal

ExperienceJournal(store: KnowledgeStore, cycle_id: str, config: dict)

debit

debit(ledger_snapshot: dict)

Durable budget event for a trusted interval of pure computation.

Cost is independent of journal length when the known head is unchanged (ledger validation/copying still scales with its cost-category count). The host MUST use ordinary append/checkpoint before an external effect. This deliberately postpones history validation to that boundary.

verify

verify()

Return True after full validation; raise ValueError on corruption.

ExperienceRunner

ExperienceRunner(environment, journal, budget, registry=None, *, mode='active', seed=0, horizon=2, checked_domains=None, checked_store_policy='deny')

replay

replay()

Pure fold of durable state; no environment calls or new writes.

run

run(task_ids=None, max_steps=1000)

Run or resume a durable finite queue; max_steps yields without reset.

Supply the same queue to resume, no argument after restore, or a fresh disjoint queue after completion. Each terminal result and cursor advance share one checkpoint. An unresolved host outcome blocks automatic resume.

learn

learn(proposal, admission, min_examples=4)

Durably reserve an externally supplied learning transaction.

An interrupted transaction blocks the runner rather than silently reusing its candidate or admission set. The registry's on_reserved callback persists all reservations before any candidate execution.

finish_committed_learning

finish_committed_learning()

Settle a durably committed admission without repeating its oracle reads.

discard_interrupted_learning

discard_interrupted_learning()

Discard interrupted learning, retaining spent work and durable data.

Before reservation no admission program has executed, so those inputs remain unused. After reservation registry IDs stay consumed forever. Proposal data remain in the learning/discard journal records in both cases.

RefinementSession

RefinementSession(grammar, domain, oracle, options, budget, *, session_id, initial=(), mode='active', seed=0, max_rounds=6, committee_size=3, max_observations=3, journal=None, active_work_limit=1024)

Repeated proposal, optional paid observation, finite check and refinement.

Use step/run, then inspect result. A verified result is not a registry entry. Registry.admit_checked must independently authorize later checked application. Reopen with restore(journal=..., grammar=..., domain=..., oracle=..., options=...). Ambiguous reads require host oracle.reconcile(request_id); they are never retried.

reconcile

reconcile()

Settle an ambiguous read without reissuing it or resetting its debit.

CommitteeSearchResult dataclass

CommitteeSearchResult(candidates: tuple[Program, ...], tried: int, reason: str, continuation_spent: int)

Distinct proposal matches in enumeration order, including partial results.

TabularEnvironment

TabularEnvironment(path, csv_path=None, *, identity='tabular', source_revision='v1')

Initialize from CSV task_id,family and family input columns (other cells empty).

The CSV remains pinned on reopen and on each operation. Effects and receipts commit in one SQLite transaction; a successful task gets one effect marker.

TabularOracle

TabularOracle(family, *, source_id=None)

Read-only finite rule SQL adapter, independent of tasks and learner code.

PackedStratifiedSampler

PackedStratifiedSampler(frame, pilot, budget, *, strategy='round_robin', cut_mode='all', max_steps=8)

Fixed pilot cuts, bounded queues, and true caller-supplied feedback.

to_dict

to_dict()

Native IO snapshot; serialized lists are accepted by restore.

VerifiedComputation

VerifiedComputation(plan, operators, budget, *, journal=None, inputs=None)

Finite DAG session; only independently accepted values enter values.

With N nodes, E dependency ports and G goals, setup costs 2+(N+E)*(1+G). Each unfinished step pays 1+G+sum(2+ports+alternatives) over relevant nodes. An attempt reserves producer + verifier + two record units atomically. Updates pay N+E+invalidated entries+2; observations add their reader price. Live guards pay guarded entries+N+E+2 on every value access or step. Recovery pays sum(cached verifier prices)+2 before exposing cached values. These declared work prices apply equally without a durable journal. Exhausted alternatives terminate as rejected; ordinary callback exceptions are recorded rejections, whereas BaseException leaves a stopped session.

OperationCatalog

OperationCatalog(registry: CompetenceRegistry, *, max_templates=16, max_samples=32)

restore classmethod

restore(snapshot, *, registry, budget)

Recompile existing checked evidence; never perform or grant admission.

Registry restoration validates its proof transcript first. This method checks catalog bindings against that registry's public snapshot. No registry writes or oracle calls occur. Persist the shared ledger after rebuilding, before reopening graph execution.

record_session

record_session(session, node_programs: Mapping[str, Program], budget, *, scope, mechanism, schema, task_prefix)

Extract accepted DAG traces, with host-declared Program/callback tags.

Grammar inputs bind positionally to each node's dependency ports. The declared AST is checked against accepted outputs; opaque callbacks are not authenticated. Independent domain admission is still mandatory. Duplicate bindings with identical typed outputs are paid, then skipped.

record

record(program: Program, example, budget)

Record a proposal example asserted by the host to be an accepted trace.

acquire

acquire(key, admission_examples, domain, oracle, budget, *, min_examples=2)

Compile, then independently check every declared finite-domain point.

operation

operation(key, *, verify, verify_revision, budget, verify_cost=8)

Return a domain/revision-bound live operator with an independent verifier.

The caller declares verifier cost. Direct invocation of callbacks is an internal prepaid interface: use VerifiedComputation to debit execution work. Rebuild the operator if unrelated registry admissions increase its size.

WorldSet

WorldSet(worlds: Iterable[Mapping], *, version: str = '1', max_worlds: int = 4096)

Explicit joint states, not independent marginal distributions.

The host supplies the alternatives and pure callbacks. An invariant answer is conditional on this model containing the real state. Empty alternatives mean contradiction. Constraints are materialized over the full finite base, so withdrawing one can restore states without rerunning arbitrary callbacks. Snapshots retain the base, evidence and dependencies, not Python callables.

constrain

constrain(evidence_id: str, predicate: Callable, budget: WorkBudget, *, depends_on=())

A pure finite constraint; repeated identical evidence is idempotent.

Predicate evaluation is paid over the full base, preserving its meaning if another restriction is subsequently withdrawn. The evidence must be supplied by the trusted host, not an answer proposed by this module.

CooperativeAuthority

CooperativeAuthority()

Host-owned monotonic checkpoint and live ledger; never trust snapshot data.

export_trusted_state

export_trusted_state()

Persist via a trusted host channel, separately from the snapshot.

FiniteProblem

FiniteProblem(assignments: Mapping, constraints: Mapping[str, Callable], objective: Callable, *, revision: str, budget: WorkBudget)

Immutable finite assignments, named feasibility predicates, integer cost.

Evidence dataclass

Evidence(id: str, source: str, revision: str, kind: str, targets: tuple[str, ...] = (), value: object = None, dependencies: tuple[str, ...] = ())

A claim; dependencies name previously accepted active claims.

ConstraintSolver

ConstraintSolver(problem, source='constraints')

Check one surviving candidate against the host constraints per call.

ObjectiveSolver

ObjectiveSolver(problem, source='objective')

Order residual candidates by cost and propose a checked feasible incumbent.

CooperativeSearch

CooperativeSearch(problem: FiniteProblem, budget: WorkBudget, *, authority=None)

Independent finite checker and versioned evidence journal.

No solver result is trusted. Each accepted exclusion is checked against the original host predicate; bounds are recomputed across the original domain.

certify

certify()

Pay for independent exhaustive optimality check; never infer proof from silence.

TeachingSession

TeachingSession(grammar, hypotheses, query_domain, *, budget, input_types=None, result_type='bool', max_items=256, authority=None)

Learn from scalar examples in a host supplied bounded program library.

All calls share one WorkBudget; exhaustion raises BudgetStop. Failed admission never installs a concept. Versions are immutable, including after retraction; dependents become unusable transitively.

teach

teach(inputs, value, *, exception=False)

Add an ordinary example or explicit exception; contradictions persist.

question

question()

Return the largest committee split over the finite query domain.

admit

admit(name, version, domain, oracle, *, source_id, source_revision)

Independently check the unique remaining proposal; never auto-select.

compose

compose(name, version, template, bindings, domain, oracle, *, source_id, source_revision)

Inline immutable accepted programs into template input terminals.

restore classmethod

restore(snapshot, *, budget, authority)

Authenticated paid replay; does not call an oracle or trust plain hashes.

TeachingAuthority

TeachingAuthority(secret=None)

Host-owned authentication capability for saved admission evidence.

Retain this object, including its monotonic epoch registry, across trusted restores. A fresh authority cannot validate another authority's snapshots. This authenticates provenance, not truthfulness of the host oracle.

export_trusted_state

export_trusted_state(*, budget)

Export a secret host checkpoint; never attach this to user snapshots.

from_trusted_state classmethod

from_trusted_state(state, *, budget)

Import explicit host-owned state, not data submitted by a teacher.

The host must preserve the newest checkpoint atomically with snapshots. Restoring an older host checkpoint is outside this trust boundary.

PreferenceAuthority

PreferenceAuthority()

Host capability; persist trusted state separately from untrusted snapshots.

PreferenceSession

PreferenceSession(alternatives, weights, *, requirements=(), budget, host_revision='v1', authority=None)

At most 64 alternatives, 256 utilities, 16 requirements, 128 answer IDs.

Answers explicitly assert strict, weak, or tie relations. Every exhaustive step is debited before execution; BudgetStop never returns a partial proof.

answers property

answers

Detached immutable event history; edits cannot bypass revision tracking.

DecisionLearner

DecisionLearner(budget, *, authority=None)

Explicit finite validation gate. Admission is local empirical evidence only.

restore classmethod

restore(snapshot, budget, *, authority)

Host supplies the current authority capability; a hash is not authority.

Restore with the SAME restored ledger, not a fresh allocation. Validation outcomes are retained host assertions; no external oracle is called.

DecisionAuthority

DecisionAuthority()

Host-owned current checkpoint/epoch; persist outside untrusted snapshots.

One authority belongs to one learner. It is not a remote authentication service. Losing this trust anchor cannot restore active admission safely.

export_trusted_state

export_trusted_state()

Store this anchor in a trusted host channel, separately from payloads.

from_trusted_state classmethod

from_trusted_state(state, *, budget)

The host, not a self-reported snapshot, authorizes this trust anchor.

select_probe

select_probe(worlds: WorldSet, question: Callable, probes: Sequence[Probe], budget: WorkBudget, *, horizon: int = 2) -> ProbeChoice

Find the cheapest worst-case resolving tree within a bounded horizon.

This plans only over the supplied finite alternatives and pure read models. All label/probe evaluations and branch expansions are paid. Predictions are not observations. If no tree is found, a deterministic fallback splits the remaining worlds; this is incomplete planning, not a guarantee of optimality.

check_program

check_program(domain, program, grammar, oracle, budget, *, request_prefix, on_event=None)

An exhaustive finite-list verdict; a DTO cannot authorize registration.

select_observation

select_observation(programs, options, grammar, budget)

Choose the first maximal typed separated-pairs / declared read cost.

Read prices are compared but never debited: this function does not read the environment. It charges planning, AST visits, outputs and pair comparisons. Invalid AST execution has one separate marker, never an invented label. At most 32 programs and 256 distinct named options are accepted; all reads and subsequent planning use the caller's existing shared budget.

select_observation_bounded

select_observation_bounded(models, options, budget, *, predict, max_work=1024, reserve=0, result_type=None)

Choose a paid typed disagreement/price row, retaining completed work.

predict(model, inputs, paid_budget) must be pure, charge its own work before execution, and have no access to labels or an oracle. It may wrap Program.evaluate or an external backend. The optional strict bool/int result contract is a host promise, not authentication of the callback. Without a contract, ValueError becomes one shared invalid marker.

All selector and prediction debits share the parent's ledger and the max_work window, while preserving reserve. A cap returns selected_partial when a fully scored, still affordable row exists. Prices are never paid here. Metadata and a final affordable-row pass are paid before processing; input copies are made only for visited options. Schema and input bounds belong to the caller's backend wrapper. At most 32 models / 256 options are copied, including when the supplied iterables are unbounded.

synthesize

synthesize(examples, grammar: Grammar, budget: WorkBudget, *, exclude=()) -> SearchResult

Find first exact proposal match; never certifies generalization.

Inputs have a fixed name schema and consistent per-name types across rows. Generated candidates (including rejected ones), comparison work, and every primitive/terminal evaluation and cached child read are debited before work. Paid child output vectors are reused; public Program evaluation is unchanged. Search is bounded and incomplete. Reasons: found, no_examples, exhausted, candidate_limit, budget_exhausted. Invalid proposal data raises ValueError after its validation debit.

synthesize_committee

synthesize_committee(examples, grammar: Grammar, budget: WorkBudget, *, size=3, max_additional_work=None, reserve=0, on_first_match=None) -> CommitteeSearchResult

Find up to size distinct exact matches in one paid enumeration.

The first match uses the full parent budget. After it, additional work debits the same ledger and must leave reserve units available. The optional continuation limit counts only those later debits. A stopped search retains all previously found matches. None of them is a domain proof. When supplied, on_first_match(program) runs once after the first match, before any continuation debit or single-candidate return. It may persist that program and the current ledger. It must not spend the parent budget. A checkpoint exception propagates to the caller.

plan_stratified_observations

plan_stratified_observations(examples, options, budget, *, limit=8, candidate_limit=64)

Plan unread rows from a bounded ordered pool without reading an oracle.

Every phase is prepaid on the parent's ledger. Any debit or sink exception propagates unchanged; no partially completed plan is a successful result. Candidate metadata is checked throughout the pool, but only the bounded prefix has its inputs decoded. The host independently shuffles that pool.

finite_reference

finite_reference(problem, budget)

Exhaustive host oracle: return (integer cost, assignment ID), or None.

check_regret_certificate

check_regret_certificate(session, certificate, *, budget)

Independent arithmetic enumeration; never calls the producer's solver.

fit_decision_policy

fit_decision_policy(feedback, budget, *, objective=_DEFAULT_OBJECTIVE, loss='decision', epochs=4, steps=(2, 1))

Paid deterministic coordinate descent for an integer linear reward ranker.

decision minimizes empirical downstream regret; prediction minimizes squared reward error, using the same model class. Neither is an SPO+ implementation. There is no automatic validation, promotion or generalization guarantee.

decision_regret

decision_regret(policy, feedback, budget)

Actual finite decision loss, not prediction error. No feasible action -> None.

evaluate_logged_policy

evaluate_logged_policy(feedback, target, budget, *, objective=_DEFAULT_OBJECTIVE, reward_model=None, minimum_ess=2)

IPS/SNIPS/DR for host-supplied fixed context→action distributions.

No clipping or invented propensities. Positivity is checked per recorded context; that is not evidence of population coverage or no confounding. DR requires an independently fitted/fixed reward model; using logged labels to fit it in this function is forbidden. Estimates are not confidence bounds.

acquisition

Bounded minimax choice of a distinguishing observation on finite alternatives.

select_probe

select_probe(worlds: WorldSet, question: Callable, probes: Sequence[Probe], budget: WorkBudget, *, horizon: int = 2) -> ProbeChoice

Find the cheapest worst-case resolving tree within a bounded horizon.

This plans only over the supplied finite alternatives and pure read models. All label/probe evaluations and branch expansions are paid. Predictions are not observations. If no tree is found, a deterministic fallback splits the remaining worlds; this is incomplete planning, not a guarantee of optimality.

competences

Empirically admitted finite scalar programs, never a probability guarantee.

Sources are host assertions, not authentication or proof of truth. Inputs and intermediate integers obey Grammar.max_abs. Admission is finite evidence only. The host must checkpoint this state together with its shared WorkBudget ledger. For checked admission, allowed_sources must include both independent example sources (for example "environment") and each domain oracle's source_id. Checked store evidence uses source="outcome", by=domain.source_id, so KnowledgeStore source retraction revokes its usability; source_revision stays bound in the body.

CompetenceRegistry

CompetenceRegistry(grammar: Grammar, *, store=None, allowed_sources=('environment', 'human', 'audit'))

propose_program

propose_program(program: Program, proposal_examples, budget)

Register a host-proposed AST after paid proposal validation, without dependencies.

derive

derive(program: Program, proposal_examples, dependencies, budget)

Host-proposed immutable AST composition; not autonomous discovery.

Every named dependency must occur as an exact expanded AST subtree. Execution charges all expanded nodes through ordinary Program.evaluate.

curriculum

Finite host curriculum: future roles, external labels and bounded learning.

Controller records share ExperienceJournal but never use runner checkpoints or its reserved state key. An interrupted learning packet is burned, not retried. An ambiguous environment effect still requires the host's reconcile protocol.

durable

SQLite persistence for the finite host example, not learner-accessible IO.

Effects here are finite state transitions stored in SQLite. Their receipts and state commit together. This does not make unrelated remote effects atomic. Private snapshots expose ground truth to the trusted host; digests and source names are integrity checks, not cryptographic owner authentication.

SQLiteEnvironment

SQLiteEnvironment(path, cases=None, *, identity='environment')

Durable Environment protocol adapter with process-safe attempt replay.

cases is required only when creating a new environment. On reopen, supplied cases must match the normalized original configuration. The parent directory must already exist. Each operation uses its own connection.

domain_checks

Paid exhaustive checks of a host-declared finite domain, never activation.

check_program

check_program(domain, program, grammar, oracle, budget, *, request_prefix, on_event=None)

An exhaustive finite-list verdict; a DTO cannot authorize registration.

tabular

Three bounded CSV-backed SQL mechanisms; private truth never evaluates a Program.

TabularOracle

TabularOracle(family, *, source_id=None)

Read-only finite rule SQL adapter, independent of tasks and learner code.

TabularEnvironment

TabularEnvironment(path, csv_path=None, *, identity='tabular', source_revision='v1')

Initialize from CSV task_id,family and family input columns (other cells empty).

The CSV remains pinned on reopen and on each operation. Effects and receipts commit in one SQLite transaction; a successful task gets one effect marker.

environments

Finite host-owned mechanisms; no learned program participates in truth.

Snapshots contain private cases and belong to the host, never to the learner. Digests detect corruption, not malicious rewriting by a trusted host.

FiniteEnvironment

FiniteEnvironment(cases: dict[str, dict], *, identity='environment')

Two tiny executable families with idempotent external attempts.

Cases accept family, x, y, mechanism (v1/v2), announced_version, threshold (default 4), and noise (0/1). Resource cases require x >= y. The resource v2 interaction charges one extra unit when x reaches threshold. Workflow v1 stages run in parallel; v2 stages run sequentially.

state property

state

Detached private host audit state; not learner input.

restore classmethod

restore(snapshot, *, identity=None, cases=None)

Validate history with pure transitions; never execute external work.

Optional identity/cases pin the expected host configuration on reopen.

interfaces

Host-owned finite environment protocol. Receipts are evidence, not model output.

Environment

Bases: Protocol

Trusted host adapter; identity is not network authentication.

execute must be idempotent by attempt ID, or reconcile must settle whether its effect happened. Unknown outcomes must not be retried blindly. A serializable receipt is not proof of truth against a hostile host.

observe payload: {"probe": name, "field": field}; receipt value: {"field": field, "value": measured_value}. act payload: {"answer": value}; receipt value: {"answer": independently_observed_correct_answer, "ok": bool, ...}.

journal

Experience notes on KnowledgeStore's chain; never executes an environment.

Ordinary append/checkpoint fingerprint the checked prefix and fully verify any new suffix. debit() is reserved for trusted pure computation: it only checks the last known head/count, then durably writes the ledger without scanning history. It can temporarily miss old payload mutations; the next ordinary event, checkpoint, records, latest or verify validates the entire fast suffix before the host may cause an external effect. Unexpected growth also verifies fully. This assumes no out-of-band backend writes between full checks; a head-only guard cannot detect edits to old in-memory payloads. A checkpoint is not an external anchor against a fully rewritten source chain. Hosts must serialize writers sharing a cycle/store.

ExperienceJournal

ExperienceJournal(store: KnowledgeStore, cycle_id: str, config: dict)

debit

debit(ledger_snapshot: dict)

Durable budget event for a trusted interval of pure computation.

Cost is independent of journal length when the known head is unchanged (ledger validation/copying still scales with its cost-category count). The host MUST use ordinary append/checkpoint before an external effect. This deliberately postpones history validation to that boundary.

verify

verify()

Return True after full validation; raise ValueError on corruption.

loop

Finite host-driven experience loop with durable intent and fail-closed recovery.

Replay is pure. Recovery never repeats an ambiguous external effect. Interrupted learning is retained and blocked; admission reservations are checkpointed before candidate execution. Host recovery must settle that transaction. If execute has an unknown outcome and reconcile cannot settle it, automatic execution remains blocked: there is no exactly-once claim for a host without reconciliation.

ExperienceRunner

ExperienceRunner(environment, journal, budget, registry=None, *, mode='active', seed=0, horizon=2, checked_domains=None, checked_store_policy='deny')

replay

replay()

Pure fold of durable state; no environment calls or new writes.

run

run(task_ids=None, max_steps=1000)

Run or resume a durable finite queue; max_steps yields without reset.

Supply the same queue to resume, no argument after restore, or a fresh disjoint queue after completion. Each terminal result and cursor advance share one checkpoint. An unresolved host outcome blocks automatic resume.

learn

learn(proposal, admission, min_examples=4)

Durably reserve an externally supplied learning transaction.

An interrupted transaction blocks the runner rather than silently reusing its candidate or admission set. The registry's on_reserved callback persists all reservations before any candidate execution.

finish_committed_learning

finish_committed_learning()

Settle a durably committed admission without repeating its oracle reads.

discard_interrupted_learning

discard_interrupted_learning()

Discard interrupted learning, retaining spent work and durable data.

Before reservation no admission program has executed, so those inputs remain unused. After reservation registry IDs stay consumed forever. Proposal data remain in the learning/discard journal records in both cases.

programs

Finite, typed scalar programs and a deterministic proposal-only enumerator.

Observational deduplication is incomplete: expressions agreeing on proposal rows may disagree elsewhere (or have different depth/overflow behaviour). A found program requires independent admission by the caller. if is eager: all three children are evaluated, typed and charged, including the unused arm.

CommitteeSearchResult dataclass

CommitteeSearchResult(candidates: tuple[Program, ...], tried: int, reason: str, continuation_spent: int)

Distinct proposal matches in enumeration order, including partial results.

synthesize

synthesize(examples, grammar: Grammar, budget: WorkBudget, *, exclude=()) -> SearchResult

Find first exact proposal match; never certifies generalization.

Inputs have a fixed name schema and consistent per-name types across rows. Generated candidates (including rejected ones), comparison work, and every primitive/terminal evaluation and cached child read are debited before work. Paid child output vectors are reused; public Program evaluation is unchanged. Search is bounded and incomplete. Reasons: found, no_examples, exhausted, candidate_limit, budget_exhausted. Invalid proposal data raises ValueError after its validation debit.

synthesize_committee

synthesize_committee(examples, grammar: Grammar, budget: WorkBudget, *, size=3, max_additional_work=None, reserve=0, on_first_match=None) -> CommitteeSearchResult

Find up to size distinct exact matches in one paid enumeration.

The first match uses the full parent budget. After it, additional work debits the same ledger and must leave reserve units available. The optional continuation limit counts only those later debits. A stopped search retains all previously found matches. None of them is a domain proof. When supplied, on_first_match(program) runs once after the first match, before any continuation debit or single-candidate return. It may persist that program and the current ledger. It must not spend the parent budget. A checkpoint exception propagates to the caller.

worlds

Finite joint alternatives and retractable observations, without invented probabilities.

WorldSet

WorldSet(worlds: Iterable[Mapping], *, version: str = '1', max_worlds: int = 4096)

Explicit joint states, not independent marginal distributions.

The host supplies the alternatives and pure callbacks. An invariant answer is conditional on this model containing the real state. Empty alternatives mean contradiction. Constraints are materialized over the full finite base, so withdrawing one can restore states without rerunning arbitrary callbacks. Snapshots retain the base, evidence and dependencies, not Python callables.

constrain

constrain(evidence_id: str, predicate: Callable, budget: WorkBudget, *, depends_on=())

A pure finite constraint; repeated identical evidence is idempotent.

Predicate evaluation is paid over the full base, preserving its meaning if another restriction is subsequently withdrawn. The evidence must be supplied by the trusted host, not an answer proposed by this module.

observations

Paid disagreement-per-price heuristic over a bounded host observation pool.

Only candidate predictions are inspected. No oracle or labels are accepted. A bounded committee need not contain the true program; this heuristic promises neither globally optimal information nor a correct prediction.

select_observation

select_observation(programs, options, grammar, budget)

Choose the first maximal typed separated-pairs / declared read cost.

Read prices are compared but never debited: this function does not read the environment. It charges planning, AST visits, outputs and pair comparisons. Invalid AST execution has one separate marker, never an invented label. At most 32 programs and 256 distinct named options are accepted; all reads and subsequent planning use the caller's existing shared budget.

select_observation_bounded

select_observation_bounded(models, options, budget, *, predict, max_work=1024, reserve=0, result_type=None)

Choose a paid typed disagreement/price row, retaining completed work.

predict(model, inputs, paid_budget) must be pure, charge its own work before execution, and have no access to labels or an oracle. It may wrap Program.evaluate or an external backend. The optional strict bool/int result contract is a host promise, not authentication of the callback. Without a contract, ValueError becomes one shared invalid marker.

All selector and prediction debits share the parent's ledger and the max_work window, while preserving reserve. A cap returns selected_partial when a fully scored, still affordable row exists. Prices are never paid here. Metadata and a final affordable-row pass are paid before processing; input copies are made only for visited options. Schema and input bounds belong to the caller's backend wrapper. At most 32 models / 256 options are copied, including when the supplied iterables are unbounded.

refinement

Bounded counterexample-guided learning; certificates cover only the declared domain.

The host owns the oracle and allowed observation inputs. Transfer inputs/labels must stay outside both. A finite committee is an incomplete heuristic. Durable sessions require ExperienceJournal; journal=None is explicitly volatile.

RefinementSession

RefinementSession(grammar, domain, oracle, options, budget, *, session_id, initial=(), mode='active', seed=0, max_rounds=6, committee_size=3, max_observations=3, journal=None, active_work_limit=1024)

Repeated proposal, optional paid observation, finite check and refinement.

Use step/run, then inspect result. A verified result is not a registry entry. Registry.admit_checked must independently authorize later checked application. Reopen with restore(journal=..., grammar=..., domain=..., oracle=..., options=...). Ambiguous reads require host oracle.reconcile(request_id); they are never retried.

reconcile

reconcile()

Settle an ambiguous read without reissuing it or resetting its debit.

stratified

Paid label-aware proposal sampling; host labels confer no authority.

plan_stratified_observations

plan_stratified_observations(examples, options, budget, *, limit=8, candidate_limit=64)

Plan unread rows from a bounded ordered pool without reading an oracle.

Every phase is prepaid on the parent's ledger. Any debit or sink exception propagates unchanged; no partially completed plan is a successful result. Candidate metadata is checked throughout the pool, but only the bounded prefix has its inputs decoded. The host independently shuffles that pool.

packed

Bounded packed observations and paid, feedback-driven stratification.

Snapshots bind ordinary host data, not authenticated observations. No oracle is called and no label is acquired by these objects.

PackedStratifiedSampler

PackedStratifiedSampler(frame, pilot, budget, *, strategy='round_robin', cut_mode='all', max_steps=8)

Fixed pilot cuts, bounded queues, and true caller-supplied feedback.

to_dict

to_dict()

Native IO snapshot; serialized lists are accepted by restore.

computation

Bounded, verified dependency computation on a declared integer work ledger.

Callbacks and their revision labels are host trusted, not authenticated. A separate verifier is a protocol obligation, not proof of arbitrary Python code. The ledger is a declared work bound, not a runtime quota. Journal writers must be serialized on one host; recovery never repeats an unknown pending callback. One operator revision binds both producer and verifier implementations.

VerifiedComputation

VerifiedComputation(plan, operators, budget, *, journal=None, inputs=None)

Finite DAG session; only independently accepted values enter values.

With N nodes, E dependency ports and G goals, setup costs 2+(N+E)*(1+G). Each unfinished step pays 1+G+sum(2+ports+alternatives) over relevant nodes. An attempt reserves producer + verifier + two record units atomically. Updates pay N+E+invalidated entries+2; observations add their reader price. Live guards pay guarded entries+N+E+2 on every value access or step. Recovery pays sum(cached verifier prices)+2 before exposing cached values. These declared work prices apply equally without a durable journal. Exhausted alternatives terminate as rejected; ordinary callback exceptions are recorded rejections, whereas BaseException leaves a stopped session.

operation_learning

Bounded reuse of whole parameterized Programs from host-verified traces.

ExternalExample is a trusted host assertion, not trace authentication. Two distinct accepted input bindings discover a template; exhaustive independent finite-domain admission remains mandatory. This does not invent an algorithm. The DAG prepays the returned operator's static costs before its callbacks. Compilation removes recursive AST dispatch, never charges fewer primitives.

Snapshots bind registry evidence; restore recompiles paid pure instructions. Callables are never serialized; hosts supply versioned live verifiers again.

OperationCatalog

OperationCatalog(registry: CompetenceRegistry, *, max_templates=16, max_samples=32)

restore classmethod

restore(snapshot, *, registry, budget)

Recompile existing checked evidence; never perform or grant admission.

Registry restoration validates its proof transcript first. This method checks catalog bindings against that registry's public snapshot. No registry writes or oracle calls occur. Persist the shared ledger after rebuilding, before reopening graph execution.

record_session

record_session(session, node_programs: Mapping[str, Program], budget, *, scope, mechanism, schema, task_prefix)

Extract accepted DAG traces, with host-declared Program/callback tags.

Grammar inputs bind positionally to each node's dependency ports. The declared AST is checked against accepted outputs; opaque callbacks are not authenticated. Independent domain admission is still mandatory. Duplicate bindings with identical typed outputs are paid, then skipped.

record

record(program: Program, example, budget)

Record a proposal example asserted by the host to be an accepted trace.

acquire

acquire(key, admission_examples, domain, oracle, budget, *, min_examples=2)

Compile, then independently check every declared finite-domain point.

operation

operation(key, *, verify, verify_revision, budget, verify_cost=8)

Return a domain/revision-bound live operator with an independent verifier.

The caller declares verifier cost. Direct invocation of callbacks is an internal prepaid interface: use VerifiedComputation to debit execution work. Rebuild the operator if unrelated registry admissions increase its size.

cooperation

Checked cooperation on a finite, host-defined constraint optimization task.

Callbacks are trusted host capabilities. Evidence and snapshots are untrusted portable data; neither can supply a checker or executable code.

FiniteProblem

FiniteProblem(assignments: Mapping, constraints: Mapping[str, Callable], objective: Callable, *, revision: str, budget: WorkBudget)

Immutable finite assignments, named feasibility predicates, integer cost.

Evidence dataclass

Evidence(id: str, source: str, revision: str, kind: str, targets: tuple[str, ...] = (), value: object = None, dependencies: tuple[str, ...] = ())

A claim; dependencies name previously accepted active claims.

ConstraintSolver

ConstraintSolver(problem, source='constraints')

Check one surviving candidate against the host constraints per call.

ObjectiveSolver

ObjectiveSolver(problem, source='objective')

Order residual candidates by cost and propose a checked feasible incumbent.

CooperativeAuthority

CooperativeAuthority()

Host-owned monotonic checkpoint and live ledger; never trust snapshot data.

export_trusted_state

export_trusted_state()

Persist via a trusted host channel, separately from the snapshot.

CooperativeSearch

CooperativeSearch(problem: FiniteProblem, budget: WorkBudget, *, authority=None)

Independent finite checker and versioned evidence journal.

No solver result is trusted. Each accepted exclusion is checked against the original host predicate; bounds are recomputed across the original domain.

certify

certify()

Pay for independent exhaustive optimality check; never infer proof from silence.

finite_reference

finite_reference(problem, budget)

Exhaustive host oracle: return (integer cost, assignment ID), or None.

teaching

Interactive finite program teaching with host-authenticated domain admission.

A committee is a proposal, never a proof. Verification covers only the separately checked finite domain. The authority is a host capability, not serialized data.

TeachingAuthority

TeachingAuthority(secret=None)

Host-owned authentication capability for saved admission evidence.

Retain this object, including its monotonic epoch registry, across trusted restores. A fresh authority cannot validate another authority's snapshots. This authenticates provenance, not truthfulness of the host oracle.

export_trusted_state

export_trusted_state(*, budget)

Export a secret host checkpoint; never attach this to user snapshots.

from_trusted_state classmethod

from_trusted_state(state, *, budget)

Import explicit host-owned state, not data submitted by a teacher.

The host must preserve the newest checkpoint atomically with snapshots. Restoring an older host checkpoint is outside this trust boundary.

TeachingSession

TeachingSession(grammar, hypotheses, query_domain, *, budget, input_types=None, result_type='bool', max_items=256, authority=None)

Learn from scalar examples in a host supplied bounded program library.

All calls share one WorkBudget; exhaustion raises BudgetStop. Failed admission never installs a concept. Versions are immutable, including after retraction; dependents become unusable transitively.

teach

teach(inputs, value, *, exception=False)

Add an ordinary example or explicit exception; contradictions persist.

question

question()

Return the largest committee split over the finite query domain.

admit

admit(name, version, domain, oracle, *, source_id, source_revision)

Independently check the unique remaining proposal; never auto-select.

compose

compose(name, version, template, bindings, domain, oracle, *, source_id, source_revision)

Inline immutable accepted programs into template input terminals.

restore classmethod

restore(snapshot, *, budget, authority)

Authenticated paid replay; does not call an oracle or trust plain hashes.

preferences

Bounded, single-author finite utility elicitation with exact certificates.

PreferenceAuthority

PreferenceAuthority()

Host capability; persist trusted state separately from untrusted snapshots.

PreferenceSession

PreferenceSession(alternatives, weights, *, requirements=(), budget, host_revision='v1', authority=None)

At most 64 alternatives, 256 utilities, 16 requirements, 128 answer IDs.

Answers explicitly assert strict, weak, or tie relations. Every exhaustive step is debited before execution; BudgetStop never returns a partial proof.

answers property

answers

Detached immutable event history; edits cannot bypass revision tracking.

check_regret_certificate

check_regret_certificate(session, certificate, *, budget)

Independent arithmetic enumeration; never calls the producer's solver.

decision_learning

Finite decision-loss learning and explicitly supported one-step policy evaluation.

The small integer linear ranker is not a System One checkpoint. Outcome values and logging propensities are host evidence, not inferred causal facts. Training never grants permission: separate validation and explicit activation are required.

DecisionAuthority

DecisionAuthority()

Host-owned current checkpoint/epoch; persist outside untrusted snapshots.

One authority belongs to one learner. It is not a remote authentication service. Losing this trust anchor cannot restore active admission safely.

export_trusted_state

export_trusted_state()

Store this anchor in a trusted host channel, separately from payloads.

from_trusted_state classmethod

from_trusted_state(state, *, budget)

The host, not a self-reported snapshot, authorizes this trust anchor.

DecisionLearner

DecisionLearner(budget, *, authority=None)

Explicit finite validation gate. Admission is local empirical evidence only.

restore classmethod

restore(snapshot, budget, *, authority)

Host supplies the current authority capability; a hash is not authority.

Restore with the SAME restored ledger, not a fresh allocation. Validation outcomes are retained host assertions; no external oracle is called.

decision_regret

decision_regret(policy, feedback, budget)

Actual finite decision loss, not prediction error. No feasible action -> None.

fit_decision_policy

fit_decision_policy(feedback, budget, *, objective=_DEFAULT_OBJECTIVE, loss='decision', epochs=4, steps=(2, 1))

Paid deterministic coordinate descent for an integer linear reward ranker.

decision minimizes empirical downstream regret; prediction minimizes squared reward error, using the same model class. Neither is an SPO+ implementation. There is no automatic validation, promotion or generalization guarantee.

evaluate_logged_policy

evaluate_logged_policy(feedback, target, budget, *, objective=_DEFAULT_OBJECTIVE, reward_model=None, minimum_ess=2)

IPS/SNIPS/DR for host-supplied fixed context→action distributions.

No clipping or invented propensities. Positivity is checked per recorded context; that is not evidence of population coverage or no confounding. DR requires an independently fitted/fixed reward model; using logged labels to fit it in this function is forbidden. Estimates are not confidence bounds.