Skip to content

perf: share a parsed template's lists instead of copying them on each read - #527

Merged
JuroOravec merged 2 commits into
mainfrom
perf/shared-ast-children
Oct 28, 2026
Merged

JuroOravec merged 2 commits into
mainfrom
perf/shared-ast-children

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

What this does

Fixes #384. citry check slowed down with roughly the cube of a template's nesting depth: at the nesting limits, checking one component took up to a minute. It now takes less than a second.

Why it was slow. The parsed template is a tree of Rust structs that are also the Python classes. PyO3 copies a field each time Python reads it, so reading a node's body or a template's elements copied everything below it. Each node also holds the variable uses and comments of its whole subtree, so one read near the root copied about depth² values. Every citry check walker that stepped down the tree paid depth³.

The change. The child lists, and the per-node lists of variables and comments, are now Shared<Vec<_>>, an Arc that copies of the tree share. A read copies one node, and the lists below it stay shared. Python sees no change: the same classes, fields, repr, == and constructors, and _rust.pyi is unchanged. This is the design Juro approved in the plan for #384.

  • How Shared behaves. It converts to and from Python exactly as its value does, compares and prints the value, and has no DerefMut. Every write goes through Shared::make_mut, which copies a list only when something else still holds it, so any copy is visible in the code. While the parser builds a tree, only Node::from_start_and_end_tags copies that way, as it did before.
  • The merge with refactor(parser): walk the template tree with a work list, not per-level recursion #520, which made the tree passes keep their own work list:
    • Template's Clone now shares its four lists and no longer walks the tree.
    • Drop still frees the tree from a work list, and skips any list that another copy still holds; that copy frees it.
    • The used-variables pass takes each list out of its Shared without copying, because the parser holds the only reference.

Measurements

Depth doubling (the plan's acceptance check). These are debug builds, timing check_project on one component. The before figures are one run each, on main at 82a2b94. The after figures are the median of 5 runs, after rebasing onto d6e2212 (#520).

Template Depths Before After After ratio
<c-if cond="flag"><div #c-ignore> 128 → 256 6.73 → 48.2 s 0.107 → 0.206 s 1.93
<c-if cond="flag"> 128 → 256 1.90 → 20.5 s 0.105 → 0.239 s 2.28
<div> 256 → 512 1.82 → 7.88 s 0.114 → 0.283 s 2.48
<c-if>…<c-elif> chain 128 → 256 6.69 → 27.4 s 0.248 → 0.665 s 2.68

The c-elif row misses the plan's 2.5 limit. The plan says a ratio between 2.5 and 4 must be profiled and reported before merging. Here is the profile:

  • The Vue compile that citry check runs once per component (_rust.vue._compile_vue, from _vue_compile_lint.py) goes from 0.109 s to 0.365 s, which is 3.3 times as long.
  • The rest of the check goes from 0.178 s to 0.351 s, which is 1.97 times as long.
  • A small part of the growth is line_break_count (_source_lines.py:30), which is called once per node and goes from 0.006 s to 0.022 s.
  • The <div> row only just passes, at 2.48, for the same reason: its Vue compile also grows about 3 times per doubling.
  • The copying this PR targets is gone. Both remaining costs are filed as citry check's Vue compile grows faster than template depth #501.

Ordinary templates were measured on a release build, on a quiet machine with all other work paused (1-minute load 1.9 to 2.8). The benchmark ran main and this branch in alternating order over 10 rounds, across all 146 citry_ui templates.

Measure main (median) branch (median) Change
Parse and compile, 20 passes 0.4028 s 0.3944 s −2.1%
check_project on all of citry_ui, including libraries 6.327 s 6.164 s −2.6%

Main's own two halves differ by 1.0% and 1.3%, so the plan's limit is max(3%, 2 × noise) = 3% slower. The branch is faster.

Not measured. The plan also asked for a profile showing that the getattr time is gone. I didn't record one separately. The depth profiles above show where the time goes now, and the copying no longer appears in them.

Tests

  • Rust:
  • Python:
    • test_compiling_leaves_the_parsed_template_unchanged compiles one parsed template twice with each compiler entry point, and checks that its repr and the output stay the same. The template covers the places where the compiler changes a tree.
  • Wider citry check coverage, now that a check at the limit is fast:
    • test_nesting_limits.py runs citry check on all four shapes, up from two.
    • _frame_budget.py checks four of its 14 fixtures, up from two. The other 10 were written for rendering: their check findings change with depth, or they hold no name at the innermost level (two don't nest at all). So comparing their findings at two depths wouldn't show that the check reached the innermost level. The comment says so.
    • Together these add about 1.3 seconds on a debug build. The frame-budget part runs only in the Linux jobs. I ran both of its render paths locally by calling its entry point directly, and both passed.

What else had to change (cross-language check)

  • ast.rs: Shared and the field types. parser.rs and compiler.rs: mechanical edits.
  • src/lang/*.rs (LangImpl): no change. The formatter: no change, because it only reads the tree.
  • PyO3 (citry_core_py): only a comment in template_parser.rs. _rust.pyi and the Python wrappers are unchanged.
  • Docs: the parser's AGENTS.md (a gotcha about shared lists) and docs/agent/INDEX.md.
  • Changelogs: an entry in the root CHANGELOG.md (citry check is faster) and one in packages/py/citry_core/CHANGELOG.md (reading a field copies one node).

Follow-ups

Local evidence

All on macOS arm64, CPython 3.14.9, debug build, rebased on d6e2212:

  • Rust: cargo fmt, cargo clippy -D warnings and cargo test on every first-party crate passed (1,325 tests). After the review fixes, I reran the parser, formatter and core-binding crates (710 tests passed).
  • Python: core 543, citry 10,374, citry_lsp 1,017, citry_ui 3,299 and pygments_citry 73 passed. After the review fixes, I reran the citry_core tests, the deep and nesting tests, and the LSP tests (1,782 passed). Ruff, format and scripts/validate.py are clean.
  • One failure, probably unrelated: test_citry_ui_type_check.py::test_citry_ui_components_have_no_typescript_or_ty_findings. It reports tsc (7.0.2) DOM-type errors in five citry_ui components' embedded JS, such as host on Node. Its findings come from type-checking component JS, not from the parsed template's fields. I couldn't run it on main's build to confirm, so CI is the check.
  • Not installed locally: the four test_benchmark_django* modules need the optional benchmark group.

An independent reviewer read the change against the plan and the merge with #520. It found no correctness problem in Shared, copy-on-write or Drop. Its other findings are folded in: the stale comments, the missing tests, Drop allocating when it had nothing to free, the wider check coverage, and the wording.

🤖 Generated with Claude Code

… read

PyO3 copies a field each time Python reads it, and a template's child
lists held everything below them. Each node also holds the variable uses
and comments of its whole subtree, so one read near the root copied about
depth² values, and every `citry check` walker that stepped down the tree
paid depth³ (#384). At the nesting limits one component took up to a
minute to check.

The child lists and the per-node lists of variables and comments are now
`Shared<Vec<_>>`, an `Arc` that copies of the tree share. A read copies
one node; the lists below it stay shared. Python sees no change: the same
classes, fields, `repr`, `==` and constructors.

- `Shared` converts to and from Python as its value does, compares and
  prints the value, and has no `DerefMut`. Writes go through
  `Shared::make_mut`, which copies only a list something else still
  holds. While the parser builds a tree, only
  `Node::from_start_and_end_tags` does that, as before.
- `Template`'s `Clone` now shares its four lists, so it needs no work
  list. `Drop` still frees the tree from a work list, and skips any list
  another copy still holds; that copy frees it. The used-variables pass
  takes each list out of its `Shared` without a copy.
- New tests check that a cloned template and node share their lists, that
  compiling leaves the Python-held template unchanged, and that a deep
  body held after its root is dropped still frees on a small stack.
- The nesting-limit test now runs `citry check` on all four shapes, and
  the frame-budget test on four of its 14 fixtures instead of two. The
  others were written for rendering: their findings change with depth, or
  their innermost level holds no name the check reports. Together they add
  about 1.3 seconds on a debug build.

Debug build, `check_project` on one component. Before: one run on main
at 82a2b94. After: median of 5 runs, rebased on d6e2212.

  template                     depths      before         after
  <c-if><div #c-ignore>        128 -> 256  6.73 -> 48.2 s  0.107 -> 0.206 s
  <c-if>                       128 -> 256  1.90 -> 20.5 s  0.105 -> 0.239 s
  <div>                        256 -> 512  1.82 -> 7.88 s  0.114 -> 0.283 s
  <c-if>..<c-elif> chain       128 -> 256  6.69 -> 27.4 s  0.248 -> 0.665 s

The c-elif row grows 2.7 times per doubling, above the plan's 2.5 limit.
A profile puts most of the excess in the Vue compile that `citry check`
runs (#501), and a little in `line_break_count`. On a release build,
parsing, compiling and checking all of citry_ui is 2 to 3% faster.

Fixes #384.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@JuroOravec
JuroOravec merged commit f67bb05 into main Oct 28, 2026
0 of 10 checks passed
@JuroOravec
JuroOravec deleted the perf/shared-ast-children branch October 28, 2026 21:48
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.

citry check slows down with roughly the cube of template nesting depth

1 participant