Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
6f38d93
perf(engine): a presence is keyed only by the dimensions it is sparse…
claude Nov 28, 2026
81e82ed
test(engine): a presence is held to the dimensions it is sparse along
claude Nov 28, 2026
b078e39
docs(changelog): a cases: region over fewer dimensions than its terms…
claude Nov 28, 2026
e5caa88
perf(engine): a cases: region keeps the rows it claims rather than it…
claude Nov 28, 2026
6ac934a
docs(changelog): a cases: region over every dimension of its terms bu…
claude Nov 28, 2026
e534752
perf(engine): work several entries share is done once per build
claude Nov 28, 2026
8c3f72f
docs(changelog): perf(engine): work several entries share is done onc…
claude Nov 28, 2026
9683b53
chore(engine): the shared-work caches are named for what they hold
claude Nov 28, 2026
54f1094
docs(changelog): a case whose when: reads fewer dimensions than its e…
claude Nov 28, 2026
c9e30c9
chore(engine): a presence's complement is written out by name
claude Nov 28, 2026
4717a1d
Merge remote-tracking branch 'origin/claude/funny-thompson-fc33p4-unc…
claude Nov 28, 2026
39d1782
Merge origin/main into claude/funny-thompson-fc33p4
claude Dec 3, 2026
2773326
Merge claude/funny-thompson-fc33p4 into claude/funny-thompson-fc33p4-…
claude Dec 3, 2026
b417aab
Merge claude/funny-thompson-fc33p4-unclaimed into claude/funny-thomps…
claude Dec 3, 2026
43507ab
Merge main into claude/funny-thompson-fc33p4
claude Dec 4, 2026
23dc127
Merge claude/funny-thompson-fc33p4 into claude/funny-thompson-fc33p4-…
claude Dec 4, 2026
4caf75e
Merge claude/funny-thompson-fc33p4-unclaimed into claude/funny-thomps…
claude Dec 4, 2026
6e57a2d
Merge main into claude/funny-thompson-fc33p4
claude Dec 4, 2026
6a40617
Merge claude/funny-thompson-fc33p4 into claude/funny-thompson-fc33p4-…
claude Dec 4, 2026
b858e9a
Merge claude/funny-thompson-fc33p4-unclaimed into claude/funny-thomps…
claude Dec 4, 2026
19195c5
Merge remote-tracking branch 'origin/main' into claude/funny-thompson…
claude Dec 5, 2026
b501493
Merge remote-tracking branch 'origin/main' into HEAD
claude Dec 5, 2026
23a756e
test(engine): a named expression held in memory has the tables it was…
claude Dec 6, 2026
11cccfc
Merge remote-tracking branch 'origin/main' into claude/funny-thompson…
claude Dec 6, 2026
f40262c
perf(engine): a named expression held in memory keeps the presence it…
claude Dec 6, 2026
1dbb0fe
Merge remote-tracking branch 'origin/main' into claude/funny-thompson…
claude Dec 6, 2026
8c00c38
Merge branch 'main' into claude/funny-thompson-fc33p4-shared
FBumann Dec 6, 2026
33e204c
chore(engine): one cache per fact a build reads once, and a presence …
claude Dec 6, 2026
d6b3f45
test(engine): a variable read twice narrows by one presence however i…
claude Dec 6, 2026
998ac03
Merge remote-tracking branch 'origin/main' into chore/engine-build-ca…
claude Dec 6, 2026
1b73ccb
perf(engine): a constraint that reads one sparse parameter twice narr…
claude Dec 6, 2026
68143f9
Merge origin/main: the engine's renames and the build's one assembly
claude Dec 6, 2026
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
16 changes: 8 additions & 8 deletions src/specsolve/_engine/assembly.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from specsolve._answer.result import Diagnostics
from specsolve._collect import collected, in_memory
from specsolve._engine import coverage, indices
from specsolve._engine.queries import QueryBuilder
from specsolve._engine.queries import QueryBuilder, shared_expressions
from specsolve._engine.scope import Scope, join_on
from specsolve._engine.specialize import is_empty, specialized_on
from specsolve._engine.terms import Term, presences_of
Expand Down Expand Up @@ -171,13 +171,13 @@ def __init__(self, attached: AttachedSources, measured: Measured, lap: Lap) -> N
self.variables: dict[str, indices.Indexed] = {}
self.constraints: dict[str, indices.Indexed] = {}
self.scope = Scope(self.program, attached, self.variables)
self.builder = QueryBuilder(self.scope, builds=True)
self.builder = QueryBuilder(self.scope, builds=True, shared=shared_expressions(self.program))
self.n_cols = 0
self.n_rows = 0
#: How many special-ordered sets have been numbered, contiguous ``0..n-1`` across the model.
self.n_sets = 0
self._empty_tables = {}
self._where_coordinates: dict[tuple[tuple[str, ...], Mask], pl.DataFrame] = {}
self._admitted: dict[tuple[tuple[str, ...], Mask], pl.DataFrame] = {}

def run(self) -> BuiltModel:
"""Build every entry, then freeze what they produced.
Expand Down Expand Up @@ -416,12 +416,12 @@ def _build_sos(self, s: program.Sos, v: program.Variable) -> pl.DataFrame:
self.n_sets = built.item(-1, 'set') + 1
return built

def _where_rows(self, dims: tuple[str, ...], where: program.Mask, start: int) -> pl.DataFrame:
def _admitted_rows(self, dims: tuple[str, ...], where: program.Mask, start: int) -> pl.DataFrame:
"""The coordinates over *dims* that *where* keeps, numbered from *start*, read once per build however many constraints share it."""
key = (dims, where)
if key not in self._where_coordinates:
self._where_coordinates[key] = indices.table(self.scope, dims, where, ROW, 0)
rows = self._where_coordinates[key]
if key not in self._admitted:
self._admitted[key] = indices.table(self.scope, dims, where, ROW, 0)
rows = self._admitted[key]
return rows.with_columns((pl.col(ROW) + start).set_sorted()) if start else rows

def _build_constraint(self, name: str, c: program.Constraint) -> _ConstraintShare:
Expand All @@ -437,7 +437,7 @@ def _build_constraint(self, name: str, c: program.Constraint) -> _ConstraintShar
start = self.n_rows
if is_empty(c, self.attached):
return self._without_a_row(name, c, self._empty_table(c.dims, ROW), start)
admitted = None if c.where is None else self._where_rows(c.dims, c.where, start)
admitted = None if c.where is None else self._admitted_rows(c.dims, c.where, start)
if admitted is not None and not admitted.height:
return self._without_a_row(name, c, admitted, start)
linear, quadratic, constant = self._terms(name, c)
Expand Down
121 changes: 56 additions & 65 deletions src/specsolve/_engine/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
from specsolve.errors import SpecsolveError

if TYPE_CHECKING:
from collections.abc import Callable, Collection, Mapping, Sequence
from collections.abc import Callable, Mapping, Sequence

from specsolve._engine.indices import Indexed

Expand All @@ -73,34 +73,37 @@ def _totalled(p: Term) -> pl.LazyFrame:
return p.table.group_by(p.dims).agg(total) if p.dims else p.table.select(total)


def _collected(terms: ExpressionTerms, kept: Collection[pl.LazyFrame]) -> ExpressionTerms:
def _held_in_memory(terms: ExpressionTerms) -> ExpressionTerms:
"""*terms* with every table they read collected in one pass: their own, their presences' and those presences' claims.

A table two places share is collected once and stays shared, and one in
*kept*, a variable's presence, stays as it is, since
[`Presence.identity`][specsolve._engine.terms.Presence.identity] tells two
presences apart by the table they hold.
A table two places share is collected once and stays shared. A presence
keeps its [`identity`][specsolve._engine.terms.Presence.identity], which
a collected table changes only for one compared by its table object.
"""
skipped = {id(t) for t in kept}
tables: dict[int, pl.LazyFrame] = {}
for p in (*terms.linear, *terms.constant, *terms.quadratic):
tables.setdefault(id(p.table), p.table)
for x in p.presences:
if id(x.table) not in skipped:
tables.setdefault(id(x.table), x.table)
tables.setdefault(id(x.table), x.table)
for u in x.unclaimed:
tables.setdefault(id(u.table), u.table)
held = dict(zip(tables, (frame.lazy() for frame in collected_all(list(tables.values()))), strict=True))

def presence(x: Presence) -> Presence:
unclaimed = tuple(replace(u, table=held[id(u.table)]) for u in x.unclaimed)
return replace(x, table=held.get(id(x.table), x.table), unclaimed=unclaimed)
return replace(x, table=held[id(x.table)], unclaimed=unclaimed)

return map_terms(
terms, lambda p: replace(p, table=held[id(p.table)], presences=tuple(presence(x) for x in p.presences))
)


def shared_expressions(compiled: program.Program) -> frozenset[str]:
"""The named expressions *compiled* reads more than once, over every entry and nested reads included."""
counts = Counter(n.name for n in walk(*compiled.roots) if isinstance(n, program.ExpressionReference))
return frozenset(name for name, count in counts.items() if count > 1)


def _one_coefficient(terms: tuple[Term, ...]) -> tuple[Term, ...]:
"""Constant *terms* over one set of dimensions added up to one term ([`_totalled`][]), else *terms* as they are.

Expand Down Expand Up @@ -145,21 +148,19 @@ class QueryBuilder:
on the builder of a build and on no other: a build places each term on an
entry's rows by the term's own dimensions, so a term that holds nothing
can be left out, where a read takes its dimensions from the terms it is given.
``shared`` names the expressions a build holds in memory once built
([`shared_expressions`][]).
"""

scope: Scope
solution: Solution | None = None
builds: bool = False
_presence_keys: dict[str, tuple[str, ...]] = field(default_factory=dict, compare=False, repr=False)
_variable_keys: dict[str, pl.DataFrame] = field(default_factory=dict, compare=False, repr=False)
_read_counts: dict[str, int] = field(default_factory=dict, compare=False, repr=False)
_named: dict[str, ExpressionTerms] = field(default_factory=dict, compare=False, repr=False)
_claims: dict[tuple[program.Mask, tuple[str, ...]], pl.DataFrame] = field(
default_factory=dict, compare=False, repr=False
)
_variable_presence: dict[tuple[str, tuple[str, ...]], Presence] = field(
shared: frozenset[str] = frozenset()
_sparse_dims: dict[str, tuple[str, ...]] = field(default_factory=dict, compare=False, repr=False)
_held_coordinates: dict[tuple[program.Mask, tuple[str, ...]], pl.DataFrame] = field(
default_factory=dict, compare=False, repr=False
)
_held_terms: dict[str, ExpressionTerms] = field(default_factory=dict, compare=False, repr=False)

# ------------------------------------------------------------------
# bounds
Expand Down Expand Up @@ -236,14 +237,19 @@ def expression(
return _ExpressionWalk(self, context, admits_quadratic, reported).terms(expr)

def _parameter_term(self, name: str) -> Term:
"""A parameter as a constant term, keyed by its declared dimensions, present only at its rows under ``missing: absent``."""
"""A parameter as a constant term, keyed by its declared dimensions, present only at its rows under ``missing: absent``.

Its presence is named by the parameter, so any two reads of it are one
to [`Presence.identity`][specsolve._engine.terms.Presence.identity].
"""
dims = self.scope.program.parameters[name].dims
table = self.scope.attached.parameters[name].select(*dims, pl.col(VALUE).cast(pl.Float64).alias(CONSTANT))
present = table.select(*dims) if dims else table.select(pl.col(CONSTANT).is_not_null().alias(PRESENT))
presences = ()
if self.scope.absent(name):
keys = self._sparse_along(name, dims, present) if dims else dims
presences = (Presence(present if keys == dims else present.select(*keys).unique(), keys),)
rows = present if keys == dims else present.select(*keys).unique()
presences = (Presence(rows, keys, of=('parameter', name)),)
return Term(dims, table, 'constant', presences=presences, parameters=frozenset({name}))

def _sparse_along(self, name: str, dims: tuple[str, ...], present: pl.LazyFrame) -> tuple[str, ...]:
Expand All @@ -255,8 +261,8 @@ def _sparse_along(self, name: str, dims: tuple[str, ...], present: pl.LazyFrame)
held twice, so rows that number the distinct keys of the other
dimensions times the size of one cover that one completely.
"""
if name in self._presence_keys:
return self._presence_keys[name]
if name in self._sparse_dims:
return self._sparse_dims[name]
keys, rows = list(dims), self.scope.attached.parameter_rows[name]
for d in reversed(dims):
rest = [k for k in keys if k != d]
Expand All @@ -265,69 +271,54 @@ def _sparse_along(self, name: str, dims: tuple[str, ...], present: pl.LazyFrame)
distinct = present.select(rest).unique().select(pl.len()).pipe(collected).item()
if distinct * self.scope.attached.dimensions[d].size == rows:
keys, rows = rest, distinct
self._presence_keys[name] = tuple(keys)
self._sparse_dims[name] = tuple(keys)
return tuple(keys)

def _named_terms(self, name: str, build: Callable[[], ExpressionTerms]) -> ExpressionTerms:
"""The terms of the named expression *name*, built once per build where the program reads it more than once.
def _shared_terms(self, name: str, build: Callable[[], ExpressionTerms]) -> ExpressionTerms:
"""The terms of the named expression *name*, built once and held in memory where it is [`shared`][].

A term is a query, so two entries reading one expression run it twice.
Where its read count is two or more, its tables, the tables that say
where its terms exist and the coordinates its cases claim are collected
once, together, and each reader joins what is in memory. Read once, it stays
a query, so the entry's own joins still push down into it. A read is
built every time: it reads at a solution.
A shared one's tables, the tables that say where its terms exist and
the coordinates its cases claim are collected once, together, and each
reader joins what is in memory. Read once, it stays a query, so the
entry's own joins still push down into it.
"""
if not self.builds or self.solution is not None:
return build()
if not self._read_counts:
counts = Counter(
n.name for n in walk(*self.scope.program.roots) if isinstance(n, program.ExpressionReference)
)
self._read_counts.update(counts)
if self._read_counts[name] < 2:
if name not in self.shared:
return build()
if name not in self._named:
self._named[name] = _collected(build(), [x.table for x in self._variable_presence.values()])
return self._named[name]
if name not in self._held_terms:
self._held_terms[name] = _held_in_memory(build())
return self._held_terms[name]

def _claimed(self, when: program.Mask, on: tuple[str, ...]) -> pl.DataFrame:
"""The coordinates over *on* where *when* holds, read once per build however many regions ask."""
def _coordinates(self, when: program.Mask, on: tuple[str, ...]) -> pl.DataFrame:
"""The coordinates over *on* where *when* holds, read once per build however many regions and variables ask."""
key = (when, on)
if key not in self._claims:
self._claims[key] = narrowed(self.scope, on, when).select(*on).pipe(collected)
return self._claims[key]
if key not in self._held_coordinates:
self._held_coordinates[key] = narrowed(self.scope, on, when).select(*on).pipe(collected)
return self._held_coordinates[key]

def _variable_term(self, name: str) -> Term:
"""A variable as a linear term with unit coefficients."""
held = self.scope.variables[name]
table = held.table.select(*held.dims, COL, pl.lit(1.0, dtype=pl.Float64).alias(COEFF))
return Term(held.dims, table, 'linear', presences=self._variable_presences(name, held.dims))
return Term(held.dims, table, 'linear', presences=self._variable_presences(name))

def _variable_presences(self, name: str, dims: tuple[str, ...]) -> tuple[Presence, ...]:
def _variable_presences(self, name: str) -> tuple[Presence, ...]:
"""Presence only for a variable with a condition under ``missing: absent``, keyed explicitly as [`Presence`][] requires.

A variable is its condition crossed with every dimension the condition
does not read, so its presence is keyed by the dimensions it reads.
Keyed by all of them, a ``cases:`` region over fewer widens it to
their full product. Built on the first reference over *dims* and
handed back on every later one, so that a presence two terms share
is the same object, which [`Presence.identity`][specsolve._engine.terms.Presence.identity] compares.
their full product. Named by the variable, so any two of its
presences are one to [`Presence.identity`][specsolve._engine.terms.Presence.identity].
"""
entry = self.scope.program.variables[name]
if entry.where is None or entry.missing != 'absent':
return ()
if (name, dims) not in self._variable_presence:
self._variable_presence[name, dims] = self._built_presence(name, dims, entry.where)
return (self._variable_presence[name, dims],)

def _built_presence(self, name: str, dims: tuple[str, ...], where: program.Mask) -> Presence:
read = tuple(d for d in dims if d in where.dims)
dims = entry.dims
read = tuple(d for d in self.scope.program.dimensions if d in dims and d in entry.where.dims)
if read and len(read) < len(dims):
if name not in self._variable_keys:
self._variable_keys[name] = narrowed(self.scope, read, where).select(*read).pipe(collected)
return Presence(self._variable_keys[name].lazy(), read)
return Presence(self.scope.variables[name].coordinates(), dims)
return (Presence(self._coordinates(entry.where, read).lazy(), read, of=('variable', name)),)
return (Presence(self.scope.variables[name].coordinates(), dims, of=('variable', name)),)

def _solved_term(self, name: str) -> Term:
"""A variable at its primal — the constant term a read turns it into, carrying the presence its linear term would.
Expand All @@ -345,7 +336,7 @@ def _solved_term(self, name: str) -> Term:
rows = join_on(everywhere, rows, keys, 'left').with_columns(
pl.col(CONSTANT).fill_null(float(entry.missing))
)
return Term(dims, rows.select(*dims, CONSTANT), 'constant', presences=self._variable_presences(name, dims))
return Term(dims, rows.select(*dims, CONSTANT), 'constant', presences=self._variable_presences(name))

def _dual_term(self, name: str) -> Term:
"""``dual(name)`` at the solve's row duals — one value per row the constraint built, and present exactly there.
Expand Down Expand Up @@ -655,7 +646,7 @@ def terms(self, e: program.Expression) -> ExpressionTerms:
if isinstance(e, program.Cases):
return self._cases(e)
if isinstance(e, program.ExpressionReference):
return self.builder._named_terms(e.name, lambda: self.terms(e.body))
return self.builder._shared_terms(e.name, lambda: self.terms(e.body))
assert_never(e)

def _product(self, a: ExpressionTerms, b: ExpressionTerms) -> ExpressionTerms:
Expand Down Expand Up @@ -775,7 +766,7 @@ def _region(self, r: program.Region) -> ExpressionTerms:
one over a dimension.
"""
on = tuple(d for d in self.scope.program.dimensions if d in r.when.dims)
truth = self.builder._claimed(r.when, on) if on else None
truth = self.builder._coordinates(r.when, on) if on else None
if truth is not None and not truth.height and self.builder.builds:
return ExpressionTerms((), ())
claimed = truth.lazy() if truth is not None else None
Expand Down Expand Up @@ -815,7 +806,7 @@ def _relaxed(
"""
keys = x.keys(dims)
if claimed is not None and on and keys:
return Presence(x.table, keys, (*x.unclaimed, Unclaimed(claimed, on)))
return replace(x, joined_on=keys, unclaimed=(*x.unclaimed, Unclaimed(claimed, on, when)))
x = x.written_out(self.scope, dims)
have = x.join_columns(dims)
join_columns = tuple(dict.fromkeys((*have, *on)))
Expand Down
22 changes: 18 additions & 4 deletions src/specsolve/_engine/terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,14 @@ class Unclaimed:
A condition reads a missing row as false under a negation too
([`falsy_if_null`][specsolve._engine.conditions.falsy_if_null]), so the
coordinates outside *table* are exactly the complement. One row per
coordinate, as the left join that reads it requires.
coordinate, as the left join that reads it requires. *when* is the
condition that claims them, so two regions under one condition claim the
same coordinates whatever table object holds them.
"""

table: pl.LazyFrame
on: tuple[str, ...]
when: program.Mask


@dataclass(frozen=True)
Expand All @@ -67,12 +70,16 @@ class Presence:
dimensions, implied columns that stay right as downstream operators rewrite
them. A shift or window edge states narrower ones. A coordinate is also
present outside each region in ``unclaimed``; a presence with one always
spells out ``joined_on``.
spells out ``joined_on``. ``of`` names the variable whose condition, or
the parameter whose rows, *table* holds, where that is all it holds: any
two presences of one of them hold the same coordinates. Every other
presence is itself only.
"""

table: pl.LazyFrame
joined_on: tuple[str, ...] | None = None
unclaimed: tuple[Unclaimed, ...] = ()
of: tuple[Literal['variable', 'parameter'], str] | None = None

def keys(self, term_dims: tuple[str, ...]) -> tuple[str, ...]:
"""The columns *table* is keyed by, for a term over *term_dims*."""
Expand All @@ -84,8 +91,15 @@ def join_columns(self, term_dims: tuple[str, ...]) -> tuple[str, ...]:
return tuple(dict.fromkeys((*keys, *(d for u in self.unclaimed for d in u.on))))

def identity(self, term_dims: tuple[str, ...]) -> tuple[object, ...]:
"""What two presences that narrow a term over *term_dims* alike share: the same tables on the same columns."""
return (id(self.table), self.keys(term_dims), tuple((id(u.table), u.on) for u in self.unclaimed))
"""What two presences that narrow a term over *term_dims* alike share: one variable's or parameter's, or one table, on the same columns, outside the same regions.

Never equal for two presences that admit different rows: a presence
names what it is [`of`][specsolve._engine.terms.Presence] only where its
table holds that and nothing else, and a region is named by the
condition that claims it.
"""
held = self.of if self.of is not None else id(self.table)
return (held, self.keys(term_dims), tuple((u.when, u.on) for u in self.unclaimed))

def keyed(self, term_dims: tuple[str, ...]) -> Presence:
"""This presence with its keys spelled out, for a term that leaves *term_dims* behind."""
Expand Down
Loading
Loading