A Query Planner for the Whole Application
Full-stack semantic invalidation can do less work than naive fine-grained reactivity.
Foldkit Plus45 min read
- metakit
- incremental-computation
- reactivity
- query-planning
- compilers
On this page
Suppose you have $1,200 in checking and $3,800 in savings.
You transfer $500 from checking to savings.
What's your new total balance?
Now suppose I hadn't told you how much you transferred. Could you still tell me what happened to the total?
What if I hadn't told you the individual balances, either?
You'd still know that whatever the original total was, it hasn't changed.
Assuming a fee-free transfer between the two accounts, there's something peculiar about how you arrived at that conclusion. You didn't calculate the new balances, add them together, and compare the result against the previous total. You understood something about the relationship between the operation and the quantity I was asking about.
How might a computer arrive at the same conclusion?
The computation you didn't perform
Consider a banking application with a million accounts. Somewhere in the application, we maintain their combined balance.
const total = (accounts: ReadonlyArray<Account>) =>
accounts.reduce(
(sum, account) => sum + account.balance,
0n
)When two accounts participate in a transfer, a straightforward reactive implementation notices that their balances have changed, reevaluates total, and discovers that its result remains the same.
A million additions to establish something we knew without looking at a single account.
We could improve on this by maintaining the total incrementally. Whenever an account balance changes, add the difference to the cached total. For a transfer, this gives us:
total -= amount
total += amountWhy execute either instruction?
| Strategy | Work required to maintain the total |
|---|---|
| Recompute | Visit a million accounts |
| Maintain incrementally | Process two balance changes |
| Establish preservation | Nothing |
The transfer itself still needs to happen. We're only concerned with maintaining its derived consequences.
Consider another operation that deposits the same amount into both accounts. From the perspective of a dependency graph, the two operations look identical: both affect checking and savings.
Their consequences for the total, however, are different.
| Operation | Checking | Savings | Total |
|---|---|---|---|
| Transfer | −x | +x | 0 |
| Deposit into both | +x | +x | +2x |
Dependency tells us which inputs a computation reads. What we're interested in here is its sensitivity: how the computation responds to a particular transformation of those inputs.
A dependency graph can tell us that the total might change. The semantics of an operation can tell us whether it does, and sometimes even by how much.
Teaching a computer about change
Here is our original computation, reduced to two accounts.
const total = (state: Accounts) =>
state.checking + state.savingsA compiler analyzing the source code could examine the addition. An application-level reactive runtime typically encounters this function through its inputs and outputs. We could give it more information by representing the computation itself as data.
const total = {
_tag: "Add",
left: { _tag: "Field", name: "checking" },
right: { _tag: "Field", name: "savings" }
}We've exchanged a convenient little function for a cumbersome object. But the object lets us manipulate the structure of the computation. We could evaluate it, extract its dependencies, translate it into SQL, or construct another computation describing how its result changes.
Let's give ourselves a more pleasant way of authoring these objects. Throughout this article, we'll use a small, illustrative TypeScript library with an Effect-inspired API.
const Accounts = Model.make("accounts", {
checking: Schema.BigInt,
savings: Schema.BigInt
})
const Total = Derived.make("total", Accounts, $ =>
Expr.add($.checking, $.savings)
)The callback receives typed symbolic references to the model's fields. It constructs the expression tree we just saw.
We can describe a transfer in much the same way:
const Transfer = Operation.make("transfer", Accounts, {
input: Schema.BigInt,
changes: ($, amount) => ({
checking: Expr.negate(amount),
savings: amount
})
})Each entry describes an amount to add to the corresponding field. For our examples, assume exact integer arithmetic, pure derived computations, and admitted, atomic operations whose change expressions read the same pre-operation state.
Now we have two descriptions:
total = checking + savings
Δchecking = -amount
Δsavings = +amountSince the total is a sum, its change is the sum of the changes in its operands.
Δtotal = Δchecking + Δsavings
= -amount + amount
= 0That reasoning suggests a general algorithm. To construct an expression describing the change in an addition, construct expressions describing the changes in its operands and add them together.
case "Add":
return Expr.add(
differentiate(expr.left, changes),
differentiate(expr.right, changes)
)Constants produce zero. Field references look up their declared changes.
Multiplication is a little more interesting. Imagine a rectangle with width a and height b. Increase its width by da and its height by db.
a da
┌──────────────────────┬──────────┐
│ │ │
b │ ab │ b·da │
│ │ │
├──────────────────────┼──────────┤
db │ a·db │ da·db │
└──────────────────────┴──────────┘The original rectangle represents the product we already had. The three added regions constitute its change:
Δ(ab) = a·db + b·da + da·dbThe algebraic identity also holds for negative changes. Implement this rule alongside the addition rule, and we can derive exact incremental expressions for combinations of additions and multiplications.
This is a form of discrete differentiation.
Apply it to the transfer:
const delta = Expr.differentiate(Total, Transfer)
// Add(Negate(Input), Input)An algebraic simplifier recognizes the opposing terms.
Expr.simplify(delta)
// Lit(0n)Neither the differentiator nor the simplifier knows anything about bank accounts. The conservation property emerges from the combination of general algebraic rules and the semantics of the operation.
There is an important catch. Try the same reasoning with JavaScript's ordinary floating-point numbers:
const checking = 0.1
const savings = 0.2
const amount = 0.05
checking + savings
// 0.30000000000000004
(checking - amount) + (savings + amount)
// 0.3Our conservation property doesn't hold exactly in this representation. We were relying on mathematical laws that the underlying number type doesn't fully obey.
The compiler's ability to perform a transformation depends on what it knows about the computational domain. That's one reason to keep types, refinements, and laws alongside the expressions themselves.
For our exact-integer language, however, the transformation is valid. And since the declarations are known ahead of time, we can perform the analysis before the application handles a request.
const Banking = Domain.make("banking", {
models: [Accounts],
operations: [Transfer],
observations: [Total]
})
const plan = Compiler.make({
domain: Banking,
operation: Transfer,
observe: [Total]
})The compiler constructs a maintenance program containing the required state writes and whatever derived updates survive differentiation and simplification.
Original observation checking + savings
Differentiate -amount + amount
Simplify 0
Emit derived maintenance []Inspect the complete operation plan:
checking -= amount
savings += amountThe total isn't there.
When changes interact
Give our banking application a simplified lending policy. A customer's borrowing capacity is three times their net assets, and their available credit is that capacity minus the credit they've already used.
We extend the model with debt and credit usage, preserving the identities of its existing fields and observations.
const Finances = Accounts.extend({
debt: Schema.BigInt,
creditUsed: Schema.BigInt
})
const NetAssets = Derived.make("netAssets", Finances, $ =>
Expr.sub(Total.ref, $.debt)
)
const BorrowingCapacity = Derived.make(
"borrowingCapacity",
Finances,
$ => Expr.mul(NetAssets.ref, Expr.lit(3n))
)
const AvailableCredit = Derived.make(
"availableCredit",
Finances,
$ => Expr.sub(BorrowingCapacity.ref, $.creditUsed)
)A deposit of $100 affects every computation in this chain. Follow their changes:
Checking + $100
│
Total assets + $100
│
Net assets + $100
│
Borrowing capacity + $300
│
Available credit + $300If a screen only observes available credit, and nothing else requires the intermediate values to stay materialized, the compiler can collapse those computations into a direct update.
checking += amount
availableCredit += 3n * amountThe new savings balance, debt, and existing credit usage are irrelevant to that maintenance program.
For a chain of a hundred affine transformations with static coefficients, differentiation and normalization can produce the same shape of program:
Δy₁ = a₁ × Δx
Δy₂ = a₂ × a₁ × Δx
...
Δy₁₀₀ = (a₁₀₀ × ... × a₁) × ΔxThe expression in parentheses is known ahead of time.
output += coefficient * inputDeltaThe original application contained a hundred derived computations. Its specialized maintenance program contains one multiplication and one addition.
Not every computational chain admits such a compact formula, and the cost of exact integer arithmetic grows with operand size. But the number of maintenance steps needn't grow with the number of declared dependencies.
A graph that describes the relationships between computations is starting to look quite different from the program responsible for executing them.
Something went wrong
Suppose we have two derived values:
const intermediate = x
const output = intermediate * zInitially, x = 1n and z = 0n, and both derived values are cached.
Increment x. The change in output is z, which happens to be zero. The delta doesn't even read intermediate, so the compiler might omit its maintenance.
Now increment z.
| Initially | After x + 1 | After z + 1 | |
|---|---|---|---|
x | 1 | 2 | 2 |
z | 0 | 0 | 1 |
| Cached intermediate | 1 | 1 | 1 |
| Calculated output | 0 | 0 | 1 |
| Correct output | 0 | 0 | 2 |
Both incremental formulas were correct. The compiler's decision about which values to maintain was wrong.
There are several ways to fix it. Maintain intermediate whenever x changes, substitute its definition into the second operation's delta, or reconstruct it lazily when required.
Each strategy produces the same required result with different computational and storage costs. The compiler needs to consider the complete family of operations, rather than optimize each one independently.
We've encountered our first materialization decision: which information should exist in the running application?
Following relationships
Return to our million accounts. Each account belongs to a customer, each customer belongs to a branch, and each branch belongs to a region.
Suppose Alice transfers money to another customer in her branch. Which aggregate balances change?
Account balances changes
│
Customer balances changes
│
Branch balances preserved
│
Regional balances preserved
│
Bank-wide balance preservedMove the transfer between branches in the same region and cancellation occurs one level later. Move it between two accounts belonging to the same customer and cancellation occurs earlier.
We can make the relationships available to the compiler through the same semantic language.
const Branch = Entity.make("Branch", {
id: Schema.String,
region: Relation.belongsTo(Region)
})
const Customer = Entity.make("Customer", {
id: Schema.String,
branch: Relation.belongsTo(Branch)
})
const Account = Entity.make("Account", {
id: Schema.String,
owner: Relation.belongsTo(Customer),
balance: Schema.BigInt
})Models and entities describe what exists, relationships describe how those things connect, operations describe how they change, and observations describe computations over them. All participate in a shared, typed semantic environment.
For example, a customer's total balance is an observation over a collection of related entities:
const CustomerBalance = Query.make(
"customerBalance",
Account,
$ => Query.groupBy($.owner.id).pipe(
Query.sum($.balance)
)
)A transfer between two accounts contributes two changes to that observation:
[
{ key: from.owner.id, delta: -amount },
{ key: to.owner.id, delta: amount }
]Combine changes belonging to the same key, discarding entries that sum to zero.
const combine = (changes: ReadonlyArray<KeyedChange>) => {
const result = new Map<string, bigint>()
for (const { key, delta } of changes) {
const next = (result.get(key) ?? 0n) + delta
if (next === 0n) result.delete(key)
else result.set(key, next)
}
return result
}If the two accounts belong to the same customer, the resulting map is empty. Otherwise, it contains two entries. Following the customers' branch relationships lets us perform the same operation on branch balances.
The same cancellation principle works over related collections.
The compiler needn't know the particular account identities or their owners ahead of time. It knows the relationships to follow and the computations to perform. Given suitable indexes, it can generate a parameterized maintenance program that visits the relevant entities without traversing the whole collection.
This is familiar territory in database research: incremental view maintenance. It becomes especially useful when combined with the other forms of incremental computation we've been developing.
Where two changes meet
Suppose the bank classifies customers with at least $100,000 in combined assets as platinum customers. Each branch maintains a count of its platinum customers.
Alice has $100,200. Bob has $99,800. Both belong to the same branch.
Alice transfers $100 to Bob. Neither crosses the classification threshold, so the branch count remains unchanged.
Try $500. Alice loses her platinum status, but Bob gains his. The branch count still doesn't change.
What if she transfers exactly $200?
| Transfer | Alice | Bob | Change in platinum count |
|---|---|---|---|
| $100 | $100,100 | $99,900 | 0 |
| $200 | $100,000 | $100,000 | +1 |
| $500 | $99,700 | $100,300 | 0 |
At exactly $200, both qualify.
Alice remains platinum: amount ≤ 200
Bob becomes platinum: amount ≥ 200Those conditions overlap at a single point.
For these initial balances, every other valid nonnegative transfer preserves the branch count. A maintenance program specialized to those balances could therefore become:
const branchCountDelta = (amount: bigint) =>
amount === 200n ? 1n : 0nAn entire chain of arithmetic, classification, and aggregation has collapsed into one comparison.
For arbitrary starting balances, the compiler would retain a parameterized expression:
const branchCountDelta = (
a: bigint,
b: bigint,
amount: bigint
) =>
BigInt(a - amount >= 100_000n) +
BigInt(b + amount >= 100_000n) -
BigInt(a >= 100_000n) -
BigInt(b >= 100_000n)The compiler could specialize this further when it has established additional facts about the participating customers.
The individual balances and classifications may still require maintenance elsewhere. But for an observer interested only in the branch count, the calculation can be substantially smaller.
Unlike the original transfer, where cancellation occurred immediately, the consequences here travel through different pieces of business logic before meeting and canceling farther downstream.
Deriving an algorithm that doesn't exist yet
Consider a business that sells industrial equipment.
Customers have draft quotes containing products and quantities. The value of those quotes contributes to each customer's financial exposure, which determines whether additional purchases require approval.
A product changes price.
Thousands of quote lines might reference it, although only live-priced draft lines follow the catalog price. Fixed-price lines use a locked unit price, and finalized quotes preserve their agreed prices.
Let's describe those relationships.
const Product = Entity.make("Product", {
id: Schema.String,
price: Schema.BigInt
})
const Quote = Entity.make("Quote", {
id: Schema.String,
customer: Relation.belongsTo(Customer),
status: Schema.Literals(["draft", "finalized"])
})
const QuoteLine = Entity.make("QuoteLine", {
id: Schema.String,
quote: Relation.belongsTo(Quote),
product: Relation.belongsTo(Product),
quantity: Schema.BigInt,
pricing: Schema.Literals(["live", "fixed"]),
lockedUnitPrice: Schema.BigInt
})We assume a simplified pricing domain without taxes or rounding. Finalizing a quote atomically locks its live prices before it leaves the draft state.
A customer's exposure is the sum of the relevant line totals:
const CustomerExposure = Query.make(
"customerExposure",
QuoteLine,
$ => Query.where(
Expr.eq($.quote.status, Expr.lit("draft"))
).pipe(
Query.groupBy($.quote.customer.id),
Query.sum(
Expr.mul(
$.quantity,
Expr.if(
Expr.eq($.pricing, Expr.lit("live")),
$.product.price,
$.lockedUnitPrice
)
)
)
)
)The relationship between a quote line and a product tells us that their computations may be connected. The pricing rule tells us whether that connection matters for a price-change operation.
const ChangePrice = Operation.make(
"changePrice",
Product,
{
input: Schema.BigInt,
changes: ($, amount) => ({
price: amount
})
}
)The operation targets a particular product, whose identity is supplied at runtime.
Suppose that product increases in price from $10 to $12. Here are four affected quote lines:
| Customer | Quote | Quantity | Change in line total |
|---|---|---|---|
| Alice | Q1 | 3 | +$6 |
| Alice | Q1 | 7 | +$14 |
| Alice | Q2 | 5 | +$10 |
| Bob | Q3 | 8 | +$16 |
Following the application graph, we might maintain four line totals, three quote totals, and two customer exposure values.
Instead, differentiate the exposure observation directly.
For Alice, the resulting expression is:
Δexposure = 3 × Δprice
+ 7 × Δprice
+ 5 × ΔpriceAll three terms share the same price change.
Δexposure = (3 + 7 + 5) × ΔpriceThe expression in parentheses has an interesting property: it doesn't depend on the product's price.
We could calculate it before the price changes.
In the general case, the compiler has transformed the observation into:
ΔcustomerExposure =
Δprice × sum(eligible quantities)The second term represents a relational query: group eligible lines by product and customer, then sum their quantities.
The developer never declared that query. It emerged from differentiating and factoring the original business computation.
Expressed in our language, the compiler's newly discovered query looks like this:
const ExposureQuantity = Query.make(
"exposureQuantity",
QuoteLine,
$ => Query.where(
Expr.and(
Expr.eq($.quote.status, Expr.lit("draft")),
Expr.eq($.pricing, Expr.lit("live"))
)
).pipe(
Query.groupBy(
$.product.id,
$.quote.customer.id
),
Query.sum($.quantity)
)
)The compiler could introduce and maintain this query as an auxiliary data structure.
Consider the transformation we just performed:
Business computation
sum(quantity × price)
↓ Differentiate
sum(quantity × Δprice)
↓ Factor
sum(quantity) × Δprice
└──────┬─────┘
│
└── Independent of the price change
↓ Materialize
quantityIndex[product, customer] × ΔpriceWe have effectively discovered an index of the sensitivity of customer exposure to product prices.
The generated maintenance program can now look up those sensitivities directly.
for (const entry of exposureIndex.get(productId)) {
exposureDelta.add(
entry.customerId,
entry.quantity * priceChange
)
}Imagine that a product occurs in 10,000 eligible quote lines, distributed across 2,000 quotes belonging to 500 customers.
Original logical computation
1 product
│
10,000 lines
│
2,000 quotes
│
500 customers
Alternative maintenance program
Price change
│
500 grouped coefficients
│
500 exposure changesWith the auxiliary summary already maintained, we can process 500 grouped entries instead of 10,000 individual lines.
Any independently observed line or quote totals must still be correctly maintained or produced on demand. But for customer exposure itself, we've derived a different algorithm from the original declaration.
When is that algorithm better?
The quantity index costs something to maintain.
Changing a line's quantity, switching its pricing mode, moving it between products or customers, or finalizing its quote may alter the index. Those operations need maintenance programs of their own.
This gives us a choice between traversing affected lines whenever a price changes and maintaining a summary that makes future price changes cheaper.
Let's assign deliberately simple costs:
- Visiting a quote line costs one work unit.
- Visiting a grouped customer entry costs one work unit.
- Maintaining the summary for a line mutation costs two additional work units.
Let P represent the number of price changes and M the number of relevant line mutations.
Indexed line traversal:
cost = 10,000P
Maintain grouped quantities:
cost = 500P + 2MFor 100 price changes and 1,000 line mutations, the respective costs are 1,000,000 and 52,000.
Reverse the workload. With one price change and 10,000 line mutations, the respective costs become 10,000 and 20,500.
The preferable algorithm changes.
We can calculate the break-even point:
500P + 2M < 10,000P
M < 4,750PUnder this toy model, materialization wins when fewer than 4,750 line mutations occur per price change.
Quote-line mutations
↑
│
│ Prefer indexed traversal
│ /
│ / M = 4,750P
│ /
│ /
│ / Prefer materialized summary
│ /
└───────────────────────────→ Price changesA real decision would account for initialization, storage, database overhead, variations in the number of affected entities, and the requirements of other observations.
Nevertheless, the planner now has a concrete task: discover candidate algorithms, establish which preserve the business semantics, and compare their costs.
The original application declaration needn't change when its workload changes.
A query planner for the whole application
We've been reasoning forward from operations, determining which computations they affect. But the application also tells us which results it needs.
Suppose the sales application observes customer exposure but doesn't display individual quote totals. The product/customer quantity summary might be an excellent choice.
Open a quote-management screen, however, and quote totals become required observations. The planner may prefer a shared traversal or an additional product/quote summary.
| Required observations | Possible maintenance strategy |
|---|---|
| Customer exposure | Product/customer quantity summary |
| Quote totals | Product/quote quantity summary |
| Both | Shared traversal or compatible summaries |
| Approval classification | Threshold maintenance with necessary supporting state |
| No optional observations | Defer their maintenance where safe |
An operation identifies a region of potential change. Observation requirements identify a region of necessary computation.
Their intersection gives us a candidate region to optimize.
Forward from the operation
What could be affected?
│
▼
Candidate work
▲
│
What needs to be maintained?
Backward from observationsMandatory writes, effects, invariants, and the state required by future operations remain part of the planning problem even when they aren't visible to a user.
Within that candidate region, the compiler can differentiate, simplify, fuse computations, share traversals, introduce auxiliary structures, and specialize the surviving work.
Beyond the database
Return to the $2 price increase.
Alice currently has $980 of exposure against a $1,000 credit limit. Bob has $700 against the same limit.
Alice: $980 + $30 = $1,010
Bob: $700 + $16 = $716Under a policy that permits automatic approval when exposure doesn't exceed the credit limit, Alice's classification changes while Bob's remains the same.
A financial risk report might require both updated exposure values. An approval dashboard needs only one changed entry.
[
{ customerId: "alice", autoApproval: false }
]Now consider the complete logical graph:
Diagram source
flowchart TD
P["Product price"] --> L["Quote lines"]
L --> Q["Quote totals"]
Q --> E["Customer exposure"]
E --> R["Risk report"]
E --> A["Approval classification"]
A --> W["Approval workflow"]
A --> D["Sales dashboard"]For a workload where the exposure summary is materialized and individual quote totals aren't required, the physical execution plan could look quite different:
Diagram source
flowchart TD
P["Committed price change"] --> I["Product/customer quantity summary"]
I --> E["Grouped exposure deltas"]
E --> R["Risk report patches"]
E --> A["Approval deltas"]
A --> C["Alice: classification changed"]
A --> B["Bob: classification preserved"]
C --> W["Required approval event"]
C --> D["Sales dashboard patch"]
B -.-> X["No classification update"]We've replaced a traversal through quote lines and quote totals with a grouped maintenance program. The risk and approval computations share its results. Bob's unchanged approval classification produces no downstream classification patch.
The planner can also identify independent branches and schedule them concurrently when their transaction and effect requirements permit it.
But there's another dimension to the problem: where should those computations run?
Consider two clients observing the approval classification.
An internal sales application already receives authorized customer exposure and credit-limit updates because it displays both quantities elsewhere. Given a coherent local snapshot, it has everything needed to maintain the classification locally.
A restricted client may read the classification but isn't authorized to receive the financial values used to determine it.
Diagram source
flowchart TD
S["Committed exposure change"]
S --> A["Authorized exposure and limit changes"]
A --> B["Internal client"]
B --> C["Maintain classification locally"]
S --> D["Derive classification on server"]
D --> E["Authorized classification delta"]
E --> F["Restricted client"]The two clients maintain the same logical observation through different physical execution strategies.
Computing the classification once on the server might be preferable for thousands of compatible subscribers. Local computation might be cheaper when clients already receive the required inputs.
Authorization and data availability determine which strategies are legal. Latency, memory, and communication costs influence which legal strategy to choose.
The logical definition of the classification remains unchanged.
One application, several cooperating programs
By now, our semantic environment has grown to include entities, relationships, observations, operations, and laws.
const Pricing = Domain.make("pricing", {
entities: [Customer, Product, Quote, QuoteLine],
operations: [
ChangePrice,
ChangeQuantity,
FinalizeQuote,
UpdateCreditLimit
],
observations: [
CustomerExposure,
ApprovalEligibility,
RiskReport,
SalesDashboard
]
})A compiler could use this environment to prepare several cooperating execution programs.
const plan = Compiler.make({
domain: Pricing,
operation: ChangePrice,
observe: [RiskReport, SalesDashboard]
})Rather than imagining that the output is a single function, consider a collection of execution partitions with explicit inputs, outputs, and dependencies:
DATABASE
Validate and commit authoritative writes.
Maintain transactional invariants and summaries.
Produce a committed revision and change batch.
│
▼
SERVER
Consume the committed change batch.
Execute residual maintenance against its revision.
Share intermediate results across observations.
Record required durable business effects.
│
▼
SYNCHRONIZATION
Determine authorized, changed observations.
Publish coherent revisioned patches.
│
▼
CLIENT
Apply the change batch.
Maintain locally computable observations.
Update affected render bindings.The compiler can reason about these programs together because their semantics originate in the same declarations.
What remains unknown during compilation becomes an input to the generated program.
| Known during preparation | Resolved during execution |
|---|---|
| Relationships | Particular entity identities |
| Operation definitions | Operation inputs |
| Observation expressions | Current state |
| Applicable laws | Runtime guard results |
| Candidate algorithms | Demand and available data |
This is not an attempt to predict every future state of the application. It's an attempt to perform whatever reasoning doesn't depend on those states in advance, leaving a specialized program to handle the rest.
The individual mechanisms we've explored are established ideas in computation. Coordinating them through a single application-wide compiler is the architectural proposal.
More business logic, more opportunities
A counter has few interesting relationships and little opportunity for global optimization.
As we add business logic, we provide a compiler with additional information.
The relationships between products, quotes, and customers made it possible to derive grouped sensitivities. Arithmetic laws allowed us to compose changes across a chain. Classification rules introduced conditional preservation. Knowledge of observation requirements revealed which intermediate computations could disappear. Knowledge of client data introduced choices about execution placement.
For suitably structured workloads, those choices can alter the amount of computation required.
| Computation | Straightforward strategy | Specialized strategy |
|---|---|---|
| Preserved aggregate of N values | O(N) recomputation | No aggregate maintenance |
| Fusible chain of depth D | O(D) propagation steps | O(1) terminal maintenance steps |
| Price change across L lines and C customers | O(L) contributions | O(C) grouped contributions |
| Preserved remote observation | Maintain and check its value | No changed-value payload |
These are comparisons against particular algorithms, not universal performance bounds or measured speedups. Auxiliary state, indexing, arithmetic costs, and mandatory operation work still matter.
Fine-grained reactive systems such as SolidJS could execute these specialized updates just as readily as ordinary reactive computations. A developer could also manually discover and implement the same optimizations.
The difference is the possibility of deriving them automatically.
In some circumstances, the fastest way to propagate a change through a dependency graph is to compile a program that doesn't traverse the graph.
A database developer can describe a query without committing to a particular join algorithm, traversal order, or materialization strategy. Those decisions belong to the planner.
Much of application development consists of making comparable decisions manually: determining which related entities to traverse, which derived values to maintain, which caches to invalidate, which computations to share, and which information to send across a network.
The business semantics often contain the information necessary to make those decisions. Preserving that information gives a compiler the opportunity to derive alternative execution strategies.
A dependency graph describes how the quantities in an application are related. We've often treated that graph as a blueprint for execution.
But those relationships describe the meaning of the application. There may be many different programs that preserve that meaning, with radically different computational costs.
Finding those programs is a compiler problem.
A note on correctness
Every transformation described here must satisfy an incremental maintenance law. For an observation Q, transition T, state s, and operation input u:
Q(T(s, u)) ≡ applyDelta(Q(s), ΔQ(s, u))When the delta is a no-op, this becomes the preservation property from our opening puzzle:
Q(T(s, u)) ≡ Q(s)Such a law can serve several purposes: verifying a business operation, generating tests, justifying an optimization, and explaining why an observation remained unchanged.
Establishing the law for a domain operation is distinct from verifying an incremental transformation, and both are distinct from establishing correctness across sequences of distributed operations.
Materialization, transaction boundaries, authorization, concurrent updates, effect ordering, and publication protocols introduce their own obligations. A compiler must establish the validity of a plan before considering its cost.
Where sufficient information is unavailable, ordinary incremental maintenance, runtime checks, cache invalidation, and recomputation remain available.
Further reading
The mathematical mechanisms discussed here have extensive precedents in database, programming-language, and compiler research.
- Finite differencing: Robert Paige and Shaye Koenig, Finite Differencing of Computable Expressions (1982).
- Incremental lambda calculus: Yufei Cai, Paolo G. Giarrusso, Tillmann Rendel, and Klaus Ostermann, A Theory of Changes for Higher-Order Languages (2014).
- Incremental relational computation: Frank McSherry et al., Differential Dataflow (2013), and Mihai Budiu et al., DBSP: Automatic Incremental View Maintenance for Rich Query Languages (2023).
- Partial evaluation: Neil D. Jones, Carsten K. Gomard, and Peter Sestoft, Partial Evaluation and Automatic Program Generation (1993).
The typed factory APIs in this article describe an illustrative programming model. The algebraic transformations establish the computational possibilities; general-purpose automatic summary synthesis, cost-based planning, and coordinated whole-stack compilation remain the broader research and engineering direction.
Companion implementation
We've also created a small, dependency-free TypeScript demonstration (examples/metakit/src/query-planner-demo.ts, alongside our ongoing MetaKit work in PR #673) so the article's mathematical examples aren't entirely hypothetical.
The implementation passes strict TypeScript checking and execution under Node.js 22. It demonstrates symbolic cancellation, fusion of a 100-layer affine chain, the stale-cache failure and substitution fix, keyed cancellation, 100,201 threshold cases, and factored pricing with incremental summary maintenance.
Run it with:
node --experimental-strip-types examples/metakit/src/query-planner-demo.tsThe companion implements restricted versions of the mathematical mechanisms, not the complete factory API, relational compiler, or distributed planner. Its tests are reproducible evidence for the examples, not performance benchmarks or a universal correctness proof.