Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@

### Fixes

- A component with Events that comes from the render cache now writes
the same HTML as when it renders without the cache. Earlier releases
gave its root element an extra `data-cid` attribute, so the browser
could load a second compiled template for the same component.
- On free-threaded Python with the GIL off, the request data from an
Events check that failed, and the result of one that passed, are now
freed about a second after your code lets go of them, not up to 60
Expand Down
6 changes: 5 additions & 1 deletion docs/design/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -1068,7 +1068,11 @@ exactly.
The ownership payload restores active instances, invocations, fills, regions,
and init relations under fresh IDs. The client manifest generated from a replay
must be indistinguishable from one produced by a fresh render except that the
cached components' render lifecycle did not run. Page serialization and
cached components' render lifecycle did not run. The same holds for the HTML:
the browser finds an Events instance by the render ID in its manifest entry,
so Events adds nothing to the component's root element. Given the same render
IDs, a replay writes the same HTML and manifest as a fresh render, apart from
the State tokens it creates. Page serialization and
dependency discovery can still execute the hooks called out in section 5.4.

No public cache feature ships for interactive subtrees until this path is
Expand Down
4 changes: 2 additions & 2 deletions packages/py/citry/citry/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,8 +318,8 @@ def reject_script_capable_attr_name(

# Attribute names that Citry writes into the page and reads again later.
# After rendering, the server replaces each empty `<template c-render-id>`
# with a child component's HTML; `data-cid` and `data-cid-*` mark component
# roots and Events instances; `data-ccss-*` scopes CSS variables; the
# with a child component's HTML; `data-cid-*` marks component roots, and
# `data-cid` stays reserved beside it; `data-ccss-*` scopes CSS variables; the
# `data-cev-*` and `data-citry-*` names below are read by the Events, i18n,
# Vue, and stylesheet code in the browser and by the render cache. Citry UI
# writes names of its own under `data-citry-` through `c-bind`, so only the
Expand Down
6 changes: 3 additions & 3 deletions packages/py/citry/citry/ext/events/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ def stage_events_cache(

entries: dict[EventInstanceEntry, None] = {}
writes: list[RenderCacheWrite] = []
markers: list[tuple[int, tuple[str, ...]]] = []
seen: set[int] = set()
for record_index, raw in enumerate(ctx.payload["instances"]):
path = f"events.instances[{record_index}]"
Expand Down Expand Up @@ -194,15 +193,16 @@ def stage_events_cache(
state_token=token or None,
public_state_json=json.dumps(public_values, sort_keys=True),
)
# Events records this occurrence only as a manifest entry that names
# its new render ID, as a live render does, so both renders give the
# same HTML.
entries[entry] = None
markers.append((instance, (f'data-cid="{ctx.instance_ids[instance]}"',)))

if seen != set(expected):
raise CacheArtifactError("Events render-cache payload has incomplete instance coverage.")
return StagedRenderCacheContribution(
extra_items=((EXTRA_KEY, entries),) if entries else (),
cache_writes=tuple(writes),
frame_markers=tuple(markers),
)


Expand Down
7 changes: 3 additions & 4 deletions packages/py/citry/citry/ext/events/emission.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,10 @@ def capture_instance(extension: EventsExtension, ctx: OnComponentDataContext) ->
public_state_json=json.dumps(values, sort_keys=True, allow_nan=False),
)
entries: dict[EventInstanceEntry, None] = ctx.context.extra.setdefault(EXTRA_KEY, {})
# The browser finds the component through the manifest entry built from
# this one, so Events adds nothing to the root element. Render cache
# replay builds its entry the same way (see `cache.py`).
entries[entry] = None
from citry._vue.capture import direct_prepared_render_active # noqa: PLC0415

if not direct_prepared_render_active():
ctx.context._add_root_markers([f'data-cid="{ctx.component.id}"'])


def _write_plain_values(state: Any) -> None:
Expand Down
6 changes: 2 additions & 4 deletions packages/py/citry/citry/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -1256,10 +1256,8 @@ def _apply_valued_markers(
Markers with the same name merge into one attribute whose values are
space-separated. ``valued_markers`` arrives innermost component first
(own markers before inherited ones), and the merged value is written
outermost first, so the innermost component's value is last. This follows
the same innermost-last convention that ``events.md`` section 5.5 pins
for the separate ``data-cid`` instance-id list; the client does not use
``data-citry-key`` to resolve instance roots.
outermost first, so the innermost component's value is last. The client
does not use ``data-citry-key`` to resolve instance roots.
"""
by_name: dict[str, list[str]] = {}
for marker in valued_markers:
Expand Down
3 changes: 2 additions & 1 deletion packages/py/citry/tests/test_events_decimal_size.py
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,8 @@ def show(self, state):
return None

entry = next(iter(render_prepared_direct(Card()).context.extra[EVENTS_EXTRA_KEY]))
assert _stage_cached_render(c, entry).frame_markers == ((0, ('data-cid="c1abcdef"',)),)
staged = _stage_cached_render(c, entry)
assert [item.render_id for item in dict(staged.extra_items)[EVENTS_EXTRA_KEY]] == ["c1abcdef"]


################################################
Expand Down
51 changes: 50 additions & 1 deletion packages/py/citry/tests/test_ext_cache_typed_artifact.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import gc
import itertools
import json
import weakref
from concurrent.futures import ThreadPoolExecutor
Expand Down Expand Up @@ -1291,6 +1292,53 @@ def template_data(self, kwargs, slots):
assert app.cache.has(_state_cache_key(second_entry.state_token))


@pytest.mark.parametrize("cache_kind", ["component", "fragment"])
def test_cache_replay_of_an_events_component_writes_the_live_html(monkeypatch, cache_kind) -> None:
# Each render takes its render IDs from a counter that starts again at 1,
# so the live render and the replay hand out the same IDs.
ids = itertools.count(1)
app = Citry(secret="cache-state-test-secret", id_generator=lambda: f"c{next(ids)}") # noqa: S106
app.set_mounted_prefix("/citry")
builds = 0

class Card(Component):
citry = app

class Cache:
enabled = cache_kind == "component"

class Events:
def update(self):
return None

def template_data(self, kwargs, slots):
nonlocal builds
builds += 1
return {}

template = """
<button @c-click="update">go</button>
"""

class Page(Component):
citry = app
template = """
<main><c-cache key="events-card"><c-card /></c-cache></main>
"""

# The Vue app ID is random, so it is fixed here; only the cache can make
# the two renders differ.
monkeypatch.setattr("citry._vue.serialization.token_hex", lambda _size: "0" * 32)
rendered = []
for _ in range(2):
ids = itertools.count(1)
root = Card() if cache_kind == "component" else Page()
rendered.append(root.render().serialize())

assert builds == 1
assert rendered[1] == rendered[0]


def _state_cache_key(token: str) -> str:
"""The cache key a server-storage ``ces1.<key>`` token's State is stored under."""
return "citry:state:" + token.removeprefix("ces1.")
Expand Down Expand Up @@ -1398,7 +1446,8 @@ def test_replay_accepts_a_token_whose_values_fit_the_current_state_types() -> No

staged = _stage_signed_state(app, entry)

assert staged.frame_markers == ((0, ('data-cid="c1abcdef"',)),)
assert [item.render_id for item in dict(staged.extra_items)[EVENTS_EXTRA_KEY]] == ["c1abcdef"]
assert staged.frame_markers == ()


def test_replay_rejects_a_token_with_a_value_that_no_longer_fits_its_type() -> None:
Expand Down
Loading