Skip to content

feat(craft): incremental expansion; CraftView rebuilds what changed - #59

Open
innkuika wants to merge 1 commit into
craft/stdlibfrom
craft/incremental
Open

innkuika wants to merge 1 commit into
craft/stdlibfrom
craft/incremental

Conversation

@innkuika

@innkuika innkuika commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Description

Stacked on #58 (craft/stdlib).

What

Expanding the root again reuses the subtree of every template instance (and of the root) whose inputs did not change. The result is always exactly what expanding every node gives; only the cost changes. CraftView renders a reused node as the identical widget, so Flutter skips those subtrees.

Spec

  • craft_runtime req 15 (new): every expansion equals a full expansion (canonical form, error templates/positions/messages, states, firing incl. fire-time payloads, builder outputs, steps and nodes); limits apply to the whole tree (reused parts count as re-evaluated, stops exactly where/with the kind a full expansion would); adapters can tell unchanged nodes; SHOULD-level description of what a template instance depends on.
  • craft_limits req 8: budgets count reused parts; an expansion MUST report the steps and nodes it counted.

Design

  • Frame = expansion of the root or of a template call at a position (path + depth). It records: the call/scope shape; the arguments of its call it read (value, order, depth of the read); observations of data/state/media parts and of registry answers (name classification + function identity, symbol values), its own and its children's; its instances, errors, own steps/nodes; its child frames keyed by relative position.
  • Reuse: same call shape, instances still kept, observations hold (checked in O(1) via data/media/state/registry epochs when nothing they read changed), and re-reading the arguments in order gives the same values. Re-reading evaluates an argument nothing has read yet at the recorded depth, so arguments are still evaluated once, at the depth of their first read, and their steps count; own steps exclude those evaluations.
  • Muting: while a template argument is evaluated for the first time, frames started after it was created don't record what it reads (its value covers it).
  • Not reused: subtrees holding builder nodes (closures keep the scope); arguments holding widgets/builders are never "the same".
  • Limits: reused frames add their steps/nodes; if a reusing pass hits a limit it is redone without reuse, so the first limit exceeded is that of a full expansion.
  • API: CraftRuntime(incremental: true) (false = full expansion, for comparison), Expansion.steps/nodes, TemplateRegistry.revision. Adapters: a node identical to one of the previous expansion is unchanged with its subtree.

Tests

  • 8 conformance cases (F-CRAFT-RT-15), expectations from a full expansion; YAML mutations fail.
  • Equivalence property test: on every expand_template case of the runtime, media and limits suites and on 150 random template programs (two libraries, state, loops, switches, builders, event payloads, widget args placed twice, recursion, symbol refs, introspection) under random limits: random data/args/media updates, firings (incl. stale handlers), re-registrations (new source, same object, other library variants, primitives metadata, host functions, app version), builder outputs; compares expansion (+steps/nodes, error details), firing results and builder outputs with a non-reusing runtime after every step. Runs in dart test and dart test -p node (~4 s VM); CRAFT_EQUIVALENCE_ROUNDS scales it (30 rounds: 4,633 tests pass).
  • Mutation testing of the reuse logic: 33 mutants, all killed except one intentionally redundant guard (taint on reads of another scope's arguments).
  • Unit tests (reuse identity, corner cases, limits interleaving, steps/nodes counted by hand), widget tests counting primitive builds.

Benchmarks (VM, ms per update, one root expansion per update as a view does; median of 15×10 updates; before = #58 head 340b93b)

scenario n before after (reuse)
list, one row changes 250 2.26 0.83
list, one row changes 1000 14.80 3.29
list, one row changes 4000 70.56 19.46
list, every row changes (worst case) 1000 15.14 17.34
lazy list (builder), one visible row changes, 20 outputs expanded 1000 0.66 0.60
form, one keystroke 45 0.68 0.21
form, one keystroke 180 1.50 0.41
deep chain, innermost changes 25 0.21 0.09
deep chain, innermost changes 100 1.30 0.47
deep chain, innermost changes 300 12.78 3.31

Lazy lists gain nothing in the engine (a template holding a builder re-expands, and visible outputs are expanded again); ...for lists and template instances are what gets faster.

Flutter (widget tests, primitive builds per update): 50-row list, one row changes: 151 → 4; form, one keystroke: all fields → the field typed into (4 builds); on an A2UI surface, a keystroke in a field bound to the data model rebuilds only that field (renderer test).

CI (craft-performance job, dart test -P performance): growth 1000 vs 250 rows ≤ 8, 180 vs 45 fields ≤ 8, lazy list 4000 vs 1000 rows ≤ 8, depth 300 vs 75 ≤ 32 on the fastest runs (node paths grow with depth, so n² — up to 16, 9–13 measured idle or loaded; per-level bookkeeping in depth would be n³, up to 64; 32 is halfway on a log scale); reuse vs full ≤ 0.8 (list), ≤ 0.7 (form), ≤ 0.8 (chain), ≤ 1.5 (lazy list), ≤ 3 when every row changes.

Review fixes

  • CraftView keeps pending rendering errors of a node that a later expansion in the same frame reuses (reviewer's probe W1 is a test).
  • Host widget and error nodes rebuild on every view update through an inherited counter, so a new hostWidgetBuilder/errorBuilder closure no longer drops the widget cache; the renderer passes a tear-off anyway.
  • Tests for the three guards the suite missed (payload arguments, payload data, instance generation); the random generator now also passes event payloads to a template and registers without refresh, which finds them.

Known limits

  • Unit of reuse is a template instance: a single big template re-expands its body; split into templates.
  • Builder outputs (LazyList items) are not cached; a template holding a builder re-expands.
  • Introspection functions answer from all registrations, so templates calling them re-expand after any registration.
  • Worst case (everything changes) costs ~1.2–1.7× a full expansion. Frames are kept per template instance; their memory is not measured.

An independent review compared the reusing and non-reusing runtimes with its own differential harness: about 26,000 random programs and 815,000 expansions (128,000 stopped at a limit), with no mismatch.

Pre-launch Checklist

  • I signed the CLA.
  • I read the Contributors Guide.
  • I updated/added relevant documentation.
  • My code changes (if any) have tests.
  • License checks pass (python3 ./scripts/fix_licenses.py --check).
  • Format checks pass (./scripts/fix_format.sh --check).

@innkuika
innkuika requested a review from ditman December 2, 2026 23:58
@innkuika
innkuika added this pull request to stack #51 December 2, 2026 23:58

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements incremental expansion (requirement 15) for the Craft engine in Dart, allowing the runtime to reuse unchanged subtrees from previous expansions. It tracks epochs for data, media, and state changes to optimize reuse checks, and updates CraftView in a2ui_craft_flutter to avoid rebuilding subtrees of reused nodes. Additionally, it adds comprehensive equivalence tests and performance benchmarks. Feedback suggests generalizing the parameter types in _sameKeys within reuse.dart to support maps with more general key types.

Comment on lines +636 to +643
bool _sameKeys(Map<String, Object?> a, Map<String, Object?> b) {
if (a.length != b.length) return false;
final Iterator<String> other = b.keys.iterator;
for (final String key in a.keys) {
if (!other.moveNext() || other.current != key) return false;
}
return true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using Map<String, Object?> for _sameKeys restricts key comparison to maps statically typed with String keys. To make the key comparison more robust and support maps with more general types (such as Map<Object?, Object?> or Map<dynamic, dynamic>) that still contain string keys, consider generalizing the parameter types to Map<Object?, Object?>.

Suggested change
bool _sameKeys(Map<String, Object?> a, Map<String, Object?> b) {
if (a.length != b.length) return false;
final Iterator<String> other = b.keys.iterator;
for (final String key in a.keys) {
if (!other.moveNext() || other.current != key) return false;
}
return true;
}
bool _sameKeys(Map<Object?, Object?> a, Map<Object?, Object?> b) {
if (a.length != b.length) return false;
final Iterator<Object?> other = b.keys.iterator;
for (final Object? key in a.keys) {
if (!other.moveNext() || other.current != key) return false;
}
return true;
}

@innkuika
innkuika force-pushed the craft/incremental branch 2 times, most recently from dda3123 to 7ca077a Compare December 3, 2026 19:00
Expanding the root again reuses the subtree of each template instance (and
of the root) whose inputs did not change, so an update costs about what it
changed instead of the whole tree; the result is always what expanding
every node gives.

- craft_runtime requirement 15: every expansion equals a full expansion
  (canonical form, errors with templates and positions, states, firing,
  builder outputs, steps and nodes); limits apply to the whole tree; the
  engine tells adapters which nodes are unchanged; what a template
  instance depends on. craft_limits requirement 8: budgets count reused
  parts; an expansion reports its steps and nodes.
- lib/src/reuse.dart (part of runtime.dart): frames record the arguments
  of the call that they read (values, order, depth), observations of data,
  state, media and registry answers (with input epochs for cheap checks),
  instances, errors and counts; reuse reads the arguments again so each is
  still evaluated once at the depth of its first read; a pass stopped by a
  limit is redone without reuse. Expansion.steps/nodes,
  CraftRuntime.incremental, TemplateRegistry.revision. The classification
  of each call node is remembered until the registrations change.
- CraftView keeps one widget per node, so Flutter skips reused subtrees.
- Tests: 8 conformance cases (F-CRAFT-RT-15); an equivalence test running
  random updates on every runtime/media/limits case and on random
  templates under random limits, comparing with a runtime that does not
  reuse (also under dart test -p node); unit tests for what is reused and
  the corner cases; widget tests counting primitive builds.
- Benchmarks (dart test -P performance, new CI job craft-performance):
  growth n vs 4n and reuse vs full for a list with one row changing, a
  form with one keystroke, a deep template chain, and every row changing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant