Skip to content

Strict CSP makes serialize() about 20 times slower on a large page (975 ms versus 42 ms for 1,400 rows) #274

Closed

Description

@JuroOravec

What happens

With security_csp="strict" and a nonce, serialize() of the board page
from Citry's web benchmark (benchmarks/web/apps/citry/, 1,400 rows) takes
about 975 ms. The same page with the default
settings takes about 42 ms. Rendering takes the same time in both (about
33 ms), so all of the extra time is in serialize(). Render plus serialize goes
from about 75 ms to about 1,000 ms, about 13 times as long.

About half of the extra time is garbage collection: the strict page runs 8
full collections per serialize (about 420 ms of them), the default page
fewer than 1.

Install Page render serialize GC time full GCs
origin/main 88d7e4869 default 33 ms 42 ms 11 ms 0.6
origin/main 88d7e4869 strict CSP + nonce 33 ms 975 ms 510 ms 8
736071308 (before native render) default 44 ms 58 ms 16 ms 0.8
736071308 (before native render) strict CSP + nonce 44 ms 890 ms 437 ms 8

Means of 5 renders after 2 warm-ups, release builds of citry_core,
Python 3.12.15, macOS arm64, measured with a local timing script that is
not in the repository. Its strict page sets
engine.settings.security_csp="strict" and calls
serialize(security_csp="strict", csp_nonce=...). The output is about the
same size on both pages (2.70 MB and 2.84 MB) and holds all 1,400 rows in
both, so the strict page does not write more HTML.

Reproduction

A smaller page shows the same pattern:

import gc
import time
from typing import Any

from citry import Citry, Component

engine = Citry(
    secret="x" * 32, autodiscover=False, security_csp="strict"
)


class Row(Component):
    citry = engine
    simple = "vue"

    class Kwargs:
        row: dict

    template = """
        <li
          c-id="row['id']"
          class="row"
          data-state="open"
        >
          <a c-href="row['url']">{{ row['title'] }}</a>
          <span class="badge">{{ row['badge'] }}</span>
          <button type="button" @click="open = !open">
            Toggle
          </button>
        </li>
    """
    js = """
        $component({data(){return {open: true};}});
    """


class Page(Component):
    citry = engine

    def template_data(self, kwargs: Any, slots: Any) -> dict[str, Any]:
        rows = [
            {"id": f"r{i}", "url": f"/r/{i}", "title": f"Row {i}",
             "badge": "ok"}
            for i in range(1_400)
        ]
        return {"rows": rows}

    template = """
        <ul>
          <c-Row
            c-for="row in rows"
            #c-key="row['id']"
            c-row="row"
          />
        </ul>
    """


full: list[int] = []
gc.callbacks.append(
    lambda phase, info: full.append(1)
    if phase == "stop" and info["generation"] == 2
    else None
)
for csp in ("off", "strict", "off", "strict"):
    rendered = Page().render()
    full.clear()
    start = time.perf_counter()
    html = rendered.serialize(security_csp=csp, csp_nonce="fixednonce")
    ms = 1000 * (time.perf_counter() - start)
    print(f"security_csp={csp}: serialize {ms:.0f} ms, "
          f"{len(full)} full GCs, {len(html)} bytes")
security_csp=off: serialize 45 ms, 0 full GCs, 1339707 bytes
security_csp=strict: serialize 156 ms, 2 full GCs, 1339707 bytes
security_csp=off: serialize 26 ms, 0 full GCs, 1339707 bytes
security_csp=strict: serialize 158 ms, 2 full GCs, 1339707 bytes

736071308 gives 33 ms and 167 ms, so this is not caused by the native
render work.

Where the time goes

cProfile of one serialize of the board with strict CSP (2.72 s under the
profiler, which inflates the many small Python calls):

Function Calls Cumulative Own
_CspRenderValidator.validate_settled_html (citry/_csp_validation.py:51) 2 2.49 s
scan_output_html (citry/_output_html.py:60) 2 1.31 s 0.21 s
its per-attribute generator (_output_html.py:64) 159,096 0.84 s 0.20 s
_walk_template (_csp_validation.py:113) 72,060 1.18 s 0.13 s
_validate_attribute (_csp_validation.py:228) 87,038 0.82 s 0.06 s
_decode_html_attribute (_csp_validation.py:294) 87,038 0.67 s 0.35 s
the Rust scan html_transform.scan_output_html 2 0.08 s 0.08 s

The default page runs none of this. Its top costs are ordinary render work
(_render_simple_vue_leaf 0.13 s, precompile_selected_tree_for_serialization
0.11 s, both under the profiler).

Timing one validation of the board's final HTML without the profiler:

Step Time Full GCs
Rust scan only (36,040 tags, 43,555 attributes, 2.84 MB) 68 ms 0
Rust scan plus building the Python OutputTemplate objects 555 ms 4
_walk_template and the attribute checks 166 ms 0
_decode_html_attribute over every attribute value 45 ms 0
one whole validate_settled_html 748 ms 2

So the cost has two causes:

  1. The whole page is checked twice. With strict CSP, Citry decides
    whether the server HTML can be sent inside the element Vue mounts on by
    running a private validator over that HTML
    (_server_contents_pass_policies, citry/_vue/serialization.py:1025,
    called at line 1390, validator call at line 1045). Then
    _serialize_render_result validates the finished page again
    (citry/serialize.py:974). On this page the body is almost the whole
    page, so both passes do the same work.
  2. Each check turns every tag and attribute into Python objects.
    scan_output_html (citry/_output_html.py:60-80) receives the Rust
    scan's dicts and builds an OutputNode, OutputTemplate, OutputTag,
    OutputToken and OutputText per tag and an OutputAttr plus two
    OutputText per attribute. That is roughly 400,000 new objects per check
    and about 800,000 per serialize, which matches the timing script's estimate of
    808,000 tracked allocations (46,000 on the default page). These objects
    start the 8 full collections, and each full collection walks the large
    heap that holds the rendered page. The validator then reads only a few
    things from them: tag names for <script> and <style>, attribute names
    starting with on or data-cid-, URL attributes, and the marker prefix.

_decode_html_attribute decodes one character per loop step in Python, but
on this page it costs only 45 ms because no value contains &. It looks
large in cProfile only because of the per-call overhead.

Does it affect both render paths?

Yes. This is serialize-time work. With CITRY_NATIVE_RENDER=0 the small
reproduction gives 32 ms and 155 ms, and the install from before native
render (736071308) is equally slow.

Suggested fix

  • Check the page once. Either reuse the first validation's findings for the
    final page (the body is a slice of it, so findings can be mapped by
    offset), or run the final validation first and use its result to decide
    what goes inside the element Vue mounts on.
  • Move the walk into Rust, or at least filter there: have
    html_transform.scan_output_html (or a new CSP check function) return
    only the tags and attributes the validator looks at, or the findings
    themselves. That removes almost all of the Python objects and with them
    the full collections.
  • As a smaller step, have _walk_template read the Rust dicts and tuples
    directly instead of building the Output* dataclasses, and skip
    _decode_html_attribute when a value has no &.
  • Add a timing check (or a count of objects created) for a strict-CSP
    serialize so the gap does not come back.

Found while shipping the native render levels (#263, #265-#269).

Activity

  1. JuroOravec commented on Oct 23, 2026

    @JuroOravec
    MemberAuthor

    Done with #289, which runs the strict CSP and JavaScript-policy checks in Rust: on the 1,400-row benchmark board, strict-CSP serialize() went from about 560 ms to about 99 ms (release build, 10 fresh processes), with the default page unchanged at about 25 ms.

    The plan's second step, checking the page body only once (the final check skipping the body bytes the Vue body gate had already checked), was built and then dropped. It would have saved about 22 ms more (100 to 79 ms). Independent reviews of it found four separate cases in which the gate's read of the body and the browser's read of the whole page could build different structures (a self-closed non-void tag before the Vue host, a self-closed raw-text tag such as <iframe/>, tag sequences the tree builder rearranges, and quirks-mode versus no-quirks parsing). Each was fixed in turn, but a skip whose soundness rests on matching the browser's parser exactly is not worth 22 ms inside a security check, so the final check keeps reading the whole page.

    The self-closed raw-text case also affected main on its own (an opaque <iframe/> or <c-raw> block swallowed the rest of the page); that fix ships separately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions