Skip to content

feat(craft): add limits - #33

Open
innkuika wants to merge 2 commits into
craft/engine-mediafrom
craft/engine-limits
Open

innkuika wants to merge 2 commits into
craft/engine-mediafrom
craft/engine-limits

Conversation

@innkuika

@innkuika innkuika commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds limits: templates are untrusted, so every stage of the Craft engine now runs under limits, and input beyond them fails cleanly instead of overflowing the stack or running unbounded. Stacked on #32. Same three parts as the other engine PRs: a blueprint, conformance cases and the code.

  • Blueprint: craft/blueprints/features/craft_limits.blueprint.md.

  • CraftLimits: engine defaults that hosts can raise or lower, and a JSON form a host can publish:

    Limit Default
    source / blob size 1 MiB
    string length 64 KiB
    declarations per library 1,000
    nesting depth 100 (hosts can raise it up to 1,000)
    nodes 100,000
    evaluation steps per expansion 100,000
  • Exact checks at load time: the text parser, binary decoders and registry check size, depth, node count and strings before anything runs. let bindings are counted at each use, so they can't blow up exponentially.

  • Runtime budget: depth, steps and nodes are counted during expansion. Past a limit, the expansion becomes one bounded error node and keeps its state. Host input beyond the limits (agent data, props, event arguments) stops the expansion or the firing instead of throwing. Errors are reported to the host (in the A2UI integration, through onError with the component id).

  • Fixes the known crashes at the default limits: a 10,000-deep source, a 90 KB blob of nested lists, 20,000 nested function calls, deep template chains, deep data or props, exponential let and doubling a string through repeated set state.

  • Tests: 56 conformance cases in craft/conformance/craft/craft_limits.yaml, which set small explicit limits and have controls just under each. Unit tests reproduce the old crashes at the default limits, and a renderer widget test covers an over-long string.

  • Not in this PR: building-block limits (text length, images, event rate), cost estimation at load time, and forwarding errors to the agent.

An independent review checked the blueprint against the tests and the code: it re-derived the counts by hand, tried every stage at the depth ceiling, and ran mutations.

Pre-launch Checklist

One time:

For this PR:

  • 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).

@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 the 'Limits' feature across the a2ui_craft package, introducing constraints on source size, string length, declaration count, nesting depth, node count, and evaluation steps to safely handle untrusted templates. The limits are enforced during parsing, binary decoding, evaluation, and runtime expansion. The review feedback correctly points out an issue in the text parser's _checkSourceSize function, where iterating over runes instead of UTF-16 code units results in incorrect column reporting for surrogate pairs.

Comment on lines +650 to +680
void _checkSourceSize(String file, CraftLimits limits) {
// A UTF-16 code unit never takes less than one byte in UTF-8.
if (file.length <= limits.maxSourceBytes &&
utf8Length(file) <= limits.maxSourceBytes) {
return;
}
var bytes = 0;
var line = 1;
var column = 0;
for (final int rune in file.runes) {
column += 1;
bytes += rune < 0x80
? 1
: rune < 0x800
? 2
: rune < 0x10000
? 3
: 4;
if (bytes > limits.maxSourceBytes) break;
if (rune == 0x0A) {
line += 1;
column = 0;
}
}
throw ParserException(
'The source is longer than ${limits.maxSourceBytes} bytes',
line,
column,
limit: CraftLimit.maxSourceBytes,
);
}

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

In _checkSourceSize, the column is incremented by 1 for each rune from file.runes. However, ParserException expects column to be measured in UTF-16 code units. Since surrogate pairs (like emojis) consist of two UTF-16 code units but only one rune, iterating over file.runes will cause the reported column to be incorrect (too small) if there are surrogate pairs on the line before the limit is exceeded. Iterating over file.codeUnits or using file.codeUnitAt allows us to correctly count the column in UTF-16 code units.

void _checkSourceSize(String file, CraftLimits limits) {
  if (file.length <= limits.maxSourceBytes &&
      utf8Length(file) <= limits.maxSourceBytes) {
    return;
  }
  var bytes = 0;
  var line = 1;
  var column = 0;
  for (var i = 0; i < file.length; i += 1) {
    final int unit = file.codeUnitAt(i);
    column += 1;
    if (unit < 0x80) {
      bytes += 1;
    } else if (unit < 0x800) {
      bytes += 2;
    } else if (unit >= 0xD800 &&
        unit < 0xDC00 &&
        i + 1 < file.length &&
        (file.codeUnitAt(i + 1) & 0xFC00) == 0xDC00) {
      bytes += 4;
      if (bytes > limits.maxSourceBytes) break;
      i += 1;
      column += 1;
    } else {
      bytes += 3;
    }
    if (bytes > limits.maxSourceBytes) break;
    if (unit == 0x0A) {
      line += 1;
      column = 0;
    }
  }
  throw ParserException(
    'The source is longer than ${limits.maxSourceBytes} bytes',
    line,
    column,
    limit: CraftLimit.maxSourceBytes,
  );
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The tokenizer counts columns in code points (file.runes), so this keeps limit errors consistent with every other parser error; the suggested change would make them differ. The 'UTF-16 code units' doc on ParserException.column was inherited from RFW and was what's inaccurate; fixed the doc in #23.

@ditman ditman 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.

🤖 Really thorough limits architecture — the load-time checks across text/binary/registry (including let expansion accounting and truncation-before-allocation in _BlobDecoder), runtime depth/step/node budgets, and 56 conformance cases with exact boundary controls are great.

Blocking (prompting Request Changes):

  1. [High — Security/DoS] Exponential event/fire bomb via HandlerCallValue DAG (runtime.dart): _values(..., handlers: true) stops at case HandlerValue() when handlers: break; without recursing into HandlerCallValue.handler, and place() treats HandlerCallValue as a 1-node leaf. A ~1.5 KB template chaining 30 declarations of call [args.h, args.h] {} expands in ~400 steps and 2 nodes under default limits, then emits 2^30 (> 1 billion) events on a single fire() call (hanging/OOMing the process). Included a reproducer test inline.
  2. [High — Security/DoS] Unbounded state growth across firings (runtime.dart): _setState deep-copies owner.value (toValue) and runs limitedValue without a node-count bound, so a template with multiple state keys can accumulate millions of nodes across taps while staying under maxSteps per tap, making each subsequent _setState an unbounded copy/walk.

Non-blocking / follow-up items:

  1. [Medium — Consistency] validationErrors skips limits in TemplateArgs.from (a2ui_props.dart): BoundValue props are validated against limits and set beyondLimits, while validationErrors strings are copied unchecked, leaving TemplateArgs.beyondLimits null even when CraftRuntime._setArgs will reject them (and causing _TemplateComponentState._key to JSON-encode overlong strings).
  2. Post-stack barrel tightening reminder (lib/a2ui_craft.dart, src/evaluator.dart): Per our agreement on #23, please include src/limits.dart and src/evaluator.dart when switching lib/a2ui_craft.dart to explicit show lists (export 'src/limits.dart'; leaks BeyondLimits, utf8Length, limitedValue, libraryNodeChildren, and evaluator.dart leaks limitEvaluationError).

Comment on lines +938 to 942
Object _values(Object value, {bool handlers = false}) {
_step();
switch (value) {
case List<Object>():
for (final Object e in value) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 [High — Security/DoS] HandlerCallValue creates an exponential fire() bomb that bypasses all default limits (maxSourceBytes, maxDepth, maxNodes, maxSteps).

Because _values(..., handlers: true) hits case HandlerValue() when handlers: break; without recursing into HandlerCallValue.handler, and place() treats HandlerCallValue as a single leaf node (default: return value), a 31-declaration template (~1.5 KB) can build a binary DAG of HandlerCallValue([H, H], {}) via lazy template arguments in ~400 steps and 2 nodes—then a single runtime.fire(...) call traverses the DAG exponentially, emitting 2^30 (> 1 billion) events and hanging/OOMing the host.

Drop-in regression test for craft/packages/a2ui_craft/test/limits_test.dart:

test('a HandlerCallValue DAG cannot bypass expansion limits', () {
  const int levels = 20; // 2^20 = 1,048,576 leaves (30 -> >1B -> OOM)
  final StringBuffer src = StringBuffer('import core;\n');
  src.writeln('widget root = T0(h: event "boom" {});');
  for (int i = 0; i < levels - 1; i += 1) {
    src.writeln('widget T$i = T${i + 1}(h: call [args.h, args.h] {});');
  }
  src.writeln(
    'widget T${levels - 1} = Button(onTap: call [args.h, args.h] {});',
  );

  final CraftRuntime runtime = CraftRuntime(
    _registry(src.toString()),
    library: _main,
    widget: 'root',
  );
  final Expansion expansion = runtime.expand();
  // Currently fails: expands with no errors in <300 steps & 2 nodes, and
  // runtime.fire((expansion.root as WidgetNode).arguments['onTap']!)
  // emits 1,048,576 TemplateEvent("boom")s from a single tap.
  expect(
    expansion.errors.map((ExpansionError e) => e.node.kind),
    contains(
      anyOf(
        ExpansionErrorKind.stepsExceeded,
        ExpansionErrorKind.nodesExceeded,
      ),
    ),
  );
});

Recursing into HandlerCallValue.handler in _values(..., handlers: true) (and/or counting handler-tree nodes in place()) closes the DAG bypass at expansion time so Blueprint Req 9's invariant holds; adding a defensive step/event cap inside fire() would also provide defense-in-depth.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Great catch, fixed in 4d8bf24: a call now counts, in the expansion's nodes, every handler it would fire at each place it's applied, so your 20-level chain stops with nodesExceeded and firing can never do more than the expansion counted. Specified in craft_limits requirements 8–9, with your reproducer as a unit test and a conformance case (+ control).

Comment on lines 418 to 425
if (parts.isNotEmpty) {
try {
limitedValue(state, limits);
} on CraftLimitException catch (failure) {
return FireError(FireErrorKind.depthExceeded, failure.message);
}
owner.value = state;
return null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[High — Security/DoS] _setState deep-copies the entire owner.value via toValue(owner.value) and walks it with limitedValue(state, limits), which bounds maxDepth and maxStringBytes but does not bound total node count.

Across repeated firings, a stateful template with multiple keys (e.g., { seed: [...], s0: 0, ..., s99: 0 }) can copy a ~40,000-node list into s0, s1, ..., s99 on successive taps—each tap stays under maxSteps = 100,000 by only reading state.seed once—accumulating millions of nodes in owner.value and forcing every subsequent _setState to deep-copy and walk the entire map. Bounding the total nodes of state in _setState (e.g., against maxNodes) prevents unbounded cross-firing state growth.

Drop-in regression test for craft/packages/a2ui_craft/test/limits_test.dart:

test('state setters cannot grow state beyond maxNodes across firings', () {
  final CraftLimits limits = CraftLimits(maxNodes: 60);
  final CraftRuntime runtime = CraftRuntime(
    _registry(
      'import core;\n'
      'widget S { step: 0, a: 0, b: 0, c: 0, d: 0 } = Button(\n'
      '  onPressed: switch state.step {\n'
      '    0: [set state.a = data.chunk, set state.step = 1],\n'
      '    1: [set state.b = data.chunk, set state.step = 2],\n'
      '    2: [set state.c = data.chunk, set state.step = 3],\n'
      '    default: set state.d = data.chunk,\n'
      '  },\n'
      ');',
      limits: limits,
    ),
    library: _main,
    widget: 'S',
    data: <String, Object?>{'chunk': List<int>.filled(20, 0)},
  );
  final List<FireError> errors = <FireError>[];
  for (int i = 0; i < 4; i += 1) {
    final Expansion expansion = runtime.expand();
    expect(expansion.errors, isEmpty);
    final WidgetNode root = expansion.root as WidgetNode;
    final FireResult result = runtime.fire(root.arguments['onPressed']!);
    errors.addAll(result.errors);
  }
  // Currently fails: all 4 firings succeed (85+ nodes in state, exceeding
  // maxNodes: 60) with no FireError.
  expect(errors, isNotEmpty);
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4d8bf24: a setter whose resulting state would exceed maxNodes fails with a new firing error, nodesExceeded, and changes nothing. Specified in requirement 9, with your test and a conformance case.

Comment on lines +219 to +222
args['validationErrors'] = <Object>[...errors.whereType<String>()];
}
}
return TemplateArgs._(args, widgets, handlers);
return TemplateArgs._(args, widgets, handlers, beyond);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 validationErrors strings are copied into args['validationErrors'] without checking limits (maxStringBytes / maxDepth), unlike BoundValue props above.

CraftRuntime._setArgs will still reject an overlong validationErrors string at expansion time, so this isn't a bypass of runtime limits, but TemplateArgs.beyondLimits remains null—which means _TemplateComponentState._key in template_catalog.dart falls through to jsonEncode(canonicalExpansionValue(args.args)) on every rebuild instead of short-circuiting. Checking validationErrors through _value('validationErrors', ..., checked) keeps beyondLimits consistent with CraftRuntime.

Drop-in regression test for craft/packages/a2ui_craft/test/a2ui_integration_test.dart:

test('validationErrors beyond maxStringBytes sets beyondLimits', () {
  const TemplateInterface checkable = TemplateInterface(
    <String, ArgKind>{'title': ArgKind.string},
    checkable: true,
  );
  final TemplateArgs args = TemplateArgs.from(
    checkable,
    <String, Object?>{
      'validationErrors': <Object?>['a' * 20],
    },
    limits: CraftLimits(maxStringBytes: 10),
  );
  // Currently fails: beyondLimits is null even though CraftRuntime rejects
  // the overlong validationErrors string on expansion.
  expect(args.beyondLimits?.limit, CraftLimit.maxStringBytes);
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4d8bf24: validationErrors are checked against the limits like other props, so beyondLimits is set; test added.

export 'src/evaluator.dart';
export 'src/expansion.dart';
export 'src/functions.dart';
export 'src/limits.dart';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reminder for the post-stack barrel-tightening pass agreed in #23: please include src/limits.dart when switching lib/a2ui_craft.dart to explicit show lists so internal plumbing stays private:

export 'src/limits.dart'
    show CraftLimit, CraftLimitException, CraftLimits, checkLibraryLimits;

Right now export 'src/limits.dart'; leaks BeyondLimits, utf8Length, limitedValue, and libraryNodeChildren publicly on package:a2ui_craft/a2ui_craft.dart.

For convenience when doing the post-stack cleanup PR, here is the full list of internal/conformance symbols currently exposed via wildcard exports on lib/a2ui_craft.dart across #23–#33:

  • RFW internal runtime nodes: BoundArgsReference, BoundLoopReference, BoundStateReference, AnyStateReference, AnyEventHandler, WidgetLibrary
  • Conformance/testing helpers: canonicalLibrary, canonicalValue, canonicalExpansionValue, widgetNameString, a2uiJson
  • Internal engine/parser/limits helpers: constructCallNames, isExcludedFromQualifiedNames, isNumber, toValue, isStringKeyed, valueEquals, compareNumbers, numberToDisplayString, invokeFunction, readMedia, mediaFunctions, BeyondLimits, utf8Length, limitedValue, libraryNodeChildren, limitEvaluationError, checkResultArgs, reservedArgs, setterName

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Will do in the barrel-tightening PR on top of the stack (explicit show lists for all barrels, internal helpers off the public API).

Comment on lines +50 to +55
/// The evaluation error for the failure of a value limit.
EvaluationException limitEvaluationError(CraftLimitException failure) =>
EvaluationException(switch (failure.limit) {
CraftLimit.maxStringBytes => EvaluationErrorKind.stringTooLong,
_ => EvaluationErrorKind.depthExceeded,
}, failure.message);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Because we currently wildcard-export src/evaluator.dart from lib/a2ui_craft.dart (even after #39 adds hide checkCallArguments), internal plumbing limitEvaluationError leaks onto the public barrel. Keeping the barrel exports controlled and small in the post-stack tightening pass agreed in #23 makes this a non-issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Will do in the barrel-tightening PR on top of the stack (explicit show lists for all barrels, internal helpers off the public API).

@innkuika
innkuika force-pushed the craft/engine-limits branch from d240398 to 4d8bf24 Compare December 2, 2026 19:58
@innkuika
innkuika requested a review from ditman December 2, 2026 20:24
@innkuika
innkuika force-pushed the craft/engine-limits branch from 4d8bf24 to c42b974 Compare December 3, 2026 02:07

@ditman ditman 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.

🤖 Thanks for the fixes — all three prior issues (the exponential HandlerCallValue DAG bomb, _setState cross-firing maxNodes cap, and validationErrors limits) are cleanly resolved.

On re-review, however, we found one remaining blocking quadratic DoS in fire():

Blocking (prompting Request Changes):

  1. [High — Security/DoS] Quadratic O(maxNodes²) CPU hang and multi-GB OOM in a single fire() (runtime.dart): fire() has no per-firing work budget, _Pass.place / _countFired do not count EventValue.arguments, SetStateValue.value, or HandlerCallValue.arguments, and _setState deep-copies/walks all of owner.value twice per setter. Under default limits (maxNodes = 100,000, maxSteps = 100,000), an untrusted template can still trigger:
    • ~7.5B node operations in one fire() (2-tap: store a 50k-node list in state.big, then fire 50k copies of set state.x = 1)
    • ~1.4B node operations in one fire() (1-tap: 16,384 copies of set state.v = <21,845-node list>)
    • ~163.8M live map entries / multi-GB OOM in FireResult.events (1-tap: 16,384 EventValues wrapped in a HandlerCallValue with a 10,000-key arguments map)

Non-blocking hardening notes:

  1. _countFired / fire / isRunnableHandler recurse without a depth check; at CraftLimits.maxDepthCeiling (1000), chained HandlerCallValues can still reach StackOverflowError unless bounded or made iterative.
  2. _setState currently clones owner.value twice per setter (toValue(owner.value) + limitedValue(state, limits)).

Comment on lines +845 to +866
case HandlerCallValue():
_countFired(value.handler);
return value;
default:
return value;
}
}

Object eval(Object? node, _Env env) => switch (node) {
/// Counts the nodes of the handler that a handler application fires, each
/// time it would fire it, so that firing does no more than an expansion
/// counts (see the `craft_limits` blueprint, requirement 8).
void _countFired(Object handler) {
_node();
switch (handler) {
case HandlerCallValue():
_countFired(handler.handler);
case List<Object>():
for (final Object e in handler) {
_countFired(e);
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 [High — Security/DoS] _countFired closes the exponential HandlerCallValue DAG bomb, but EventValue.arguments, SetStateValue.value, and HandlerCallValue.arguments are still uncounted here, and fire() (L335-L364) has no per-firing work budget.

Because fire() spreads ...entry.arguments / ...arguments into a fresh Map for every EventValue and HandlerCallValue, an untrusted template within default limits (maxNodes = 100,000, maxSteps = 100,000) can still trigger:

  • Single-tap CPU freeze (~1.43B node ops): build a 21,845-node list, bind s: set state.v = args.x, and branch s into 16,384 copies.
  • Single-tap multi-GB OOM (~163.8M live map entries in FireResult.events): wrap 16,384 EventValues in a HandlerCallValue with a 10,000-key arguments map.

Giving fire() a per-firing work/node budget (e.g. bounded by limits.maxNodes / limits.maxSteps, stopping with a FireError when exceeded) covering map entries copied in TemplateEvent/HandlerCallValue and nodes touched in _setState closes both this and the 2-tap _setState quadratic vector in one place.

Drop-in reproducer test for craft/packages/a2ui_craft/test/limits_test.dart:

test('repeated setters on a large payload cannot cause quadratic work in fire()', () {
  // Small limits so the test runs fast while demonstrating O(maxNodes^2) work:
  // X0..X2 builds a 4^3 = 64-leaf (85-node) list; U0..U2 repeats the setter
  // 64 times (85 nodes). With maxNodes: 200, expansion succeeds, yet a single
  // fire() copies/walks ~64 * 4 * 85 ≈ 21,760 nodes (>100x maxNodes).
  // At default limits (100,000), 7 levels -> >1.4B node operations.
  const String source = '''
import core;
widget S { v: 0 } = X0(x: [0, 0, 0, 0]);
widget X0 = X1(x: [args.x, args.x, args.x, args.x]);
widget X1 = X2(x: [args.x, args.x, args.x, args.x]);
widget X2 = U0(s: set state.v = args.x);
widget U0 = U1(s: [args.s, args.s, args.s, args.s]);
widget U1 = U2(s: [args.s, args.s, args.s, args.s]);
widget U2 = Button(onPressed: [args.s, args.s, args.s, args.s]);
''';
  final CraftRuntime runtime = CraftRuntime(
    _registry(source, limits: CraftLimits(maxNodes: 200, maxSteps: 500)),
    library: _main,
    widget: 'S',
  );
  final Expansion expansion = runtime.expand();
  final List<FireError> fireErrors = expansion.errors.isEmpty
      ? runtime.fire((expansion.root as WidgetNode).arguments['onPressed']!).errors
      : const <FireError>[];
  // Currently fails: expansion succeeds with no errors and fire() runs all 64
  // full deep-copies with no FireError.
  expect(expansion.errors.isNotEmpty || fireErrors.isNotEmpty, isTrue);
});

(Minor hardening note: _countFired, fire, and isRunnableHandler also recurse without a depth guard, so at CraftLimits.maxDepthCeiling (1000), deeply chained HandlerCallValues can reach StackOverflowError unless bounded or made iterative.)

Comment on lines 421 to 434
if (parts.isNotEmpty) {
try {
limitedValue(state, limits);
} on CraftLimitException catch (failure) {
return FireError(FireErrorKind.depthExceeded, failure.message);
}
if (_hasMoreNodes(state, limits.maxNodes)) {
return FireError(
FireErrorKind.nodesExceeded,
'The state would have more than ${limits.maxNodes} nodes.',
);
}
owner.value = state;
return null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Note that even if SetStateValue.value is counted in place(), _setState still allows a 2-tap quadratic CPU freeze at default limits (maxNodes = 100,000): Tap 1 stores a 50,000-node list in state.big; Tap 2 fires 50,000 copies of set state.x = 1. Because each setter deep-copies owner.value via toValue(owner.value), clones it a second time in limitedValue(state, limits), and walks it in _hasMoreNodes(state, limits.maxNodes), one fire() performs ~50,000 × 3 × 50,000 = ~7.5 billion node operations.

Bounding total work across setters inside fire() (and avoiding the redundant second deep copy in limitedValue) prevents this vector cleanly.

Templates are untrusted, so every stage now runs under limits (the
`craft_limits` feature). This is new code; there was no prototype for
it.

- `CraftLimits` (lib/src/limits.dart): maxSourceBytes (1 MiB),
  maxStringBytes (64 KiB), maxDeclarations (1,000), maxDepth (100),
  maxNodes (100,000) and maxSteps (100,000), each settable by the host,
  with a JSON form for publishing; maxDepth is capped at 1,000.
- The text parser and the binary decoders reject sources and blobs
  beyond the limits (size, depth, nodes, string values, declarations)
  with a defined error naming the limit (line for text, offset and kind
  limitExceeded for blobs). `let` bindings count at each use, so they
  cannot multiply a small source.
- The registry checks every library it registers against the same
  library measures.
- The evaluator and the runtime limit the depth of evaluation and check
  host values and function results (depthExceeded, stringTooLong). Each
  expansion has a budget of steps and nodes; past it, the expansion is
  one error node (stepsExceeded, nodesExceeded) and keeps the state.
  Firings reject event arguments beyond the limits and setters that
  would nest the state deeper than maxDepth.
- The A2UI integration checks resolved prop values against the
  registry's limits before converting them (TemplateArgs.from); a value
  beyond them stops the expansion like other host input.
- Deep inputs that used to overflow the stack (10,000 nested lists in a
  source, in a 90 KB blob, in an expression) now fail cleanly.
- Blueprint craft/blueprints/features/craft_limits.blueprint.md, 56
  conformance cases in craft/conformance/craft/craft_limits.yaml
  (expansions through the expand_template action), and unit tests. The
  craft_text_format, craft_binary_format, functions, runtime and
  craft_a2ui_integration blueprints now point to the defined behavior.
- Conformance: the parse_limits and check_limits actions,
  expand_template's limits, and the F-CRAFT-LIMIT-01 to 09 feature IDs.
- A handler application now counts, in the expansion's nodes, the
  handler it applies, at each place it is applied. A chain of templates
  that each apply `call [args.h, args.h] {}` used to expand in a few
  hundred steps and 2 nodes and then fire 2^n events from one tap; it
  now stops with nodesExceeded, and firing never runs more than the
  expansion counted.
- A setter whose state would have more than maxNodes nodes fails with
  the new firing error nodesExceeded, so state cannot grow without bound
  across firings.
- TemplateArgs.from checks validationErrors against the limits like the
  other resolved props, so beyondLimits is set when the runtime would
  reject them.
- craft_limits requirements 8 and 9 say so; three new conformance cases
  (handler_applications_count_what_they_fire, with its control, and
  setters_beyond_the_node_limit) and the reviewer's reproducers as unit
  tests.
@innkuika
innkuika force-pushed the craft/engine-limits branch from c42b974 to ee5f7d5 Compare December 3, 2026 19:00
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.

2 participants