Skip to content

fix(server): the per-request site-context memo misses, because Vike hands each hook a new pageContext Proxy - #109

Merged
sydevs-bot merged 9 commits into
mainfrom
claude/fix-108-memo-key
Sep 22, 2026
Merged

sydevs-bot merged 9 commits into
mainfrom
claude/fix-108-memo-key

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • One wm-web-translations read per chromed SSR render, and one token verification per preview render, instead of two.
  • perRequest now owns the memo, so a new per-request read cannot key on the wrong object.
  • First test coverage for server/site-context.ts, which had no spec.

Changes

  • server/request-memo.ts — new. memoKey resolves the object vike keeps stable across hooks; perRequest wraps the WeakMap.
  • server/site-context.ts, server/live-preview.ts — three memos moved onto perRequest.
  • pages/+onBeforeRender.ts — comments that asserted a memo hit that did not occur.
  • tests/_helpers/page-context.ts — new. Builds the two hook views, and the context an abort forks, with vike's own code.

Preview

Test results

  • Lean gate: ✓ lint (0 errors), tsc --noEmit, vitest run — 71 files, 660 tests
  • Targeted specs: 25 passed across request-memo, site-context, live-preview
  • Build: ✓ pnpm build; dist/server contains no trace of the test helper

Manual verification

  1. pnpm dev, load / twice, and count wm-web-translations in the request log for the second render. One. Counting the first render is misleading — see the warm-server note added to docs/local-environment.md.
  2. Open a page in the CMS Live Preview panel and confirm drafts still render, and that editing translations does not draft the page itself.

Notes for reviewer

The judgement call worth checking: memoKey reads a vike internal. It goes through dangerouslyUseInternals, which vike types on PageContextServer and documents at vike.dev/warning/internals. I verified against a proxy built with warnings enabled that a bare _originalObject read warns and the hatch does not — so this is quiet by construction, not by accident of how vike happens to build this proxy today. server/request-memo.test.ts fails loudly if that stops holding.

No slot on pageContext can replace it, and no package ships one. forkPageContext copies every own property descriptor, symbols included, so a slot — string-keyed or under a module-local symbol — reaches the error page an abort renders, carrying the promise that rejected with that abort and a verified preview token. Only the object identity separates the two contexts. That is now a spec, not a claim.

The ticket left one open question — where memoKey lives. Its own module: site-context.ts already imports live-preview.ts, so neither could own it.

Filed separately rather than widened into this PR: on throw render(404), vike forks the pre-routing context and never re-runs onBeforeRoute, so the error page reads translations with locale === undefined and <html lang> is unset. Pre-existing, and visible in the dev log for /fr/<unknown-slug>.

Detail

Evidence, against the resolved [email protected] rather than from source reading. execHookList builds pageContextPublic once per call, and execHookDataAndOnBeforeRender calls execHookServer separately for data and onBeforeRender — two proxies, one target. getPageContextPublicShared asserts _isOriginalObject before wrapping, "to ensure we preserve the original object reference".

Measured, not assumed. pnpm dev at /, warm, counting loadTranslations executions: 2 on main's keying, 1 with the fix, 2 again when flipped back. wm-web-config is 1 either way, so the fix moved no call. The first cold attempt read 2-and-2 and was wrong — Vite logs [vite] program reload between reads while optimizing deps, which rebuilds the SSR module graph and resets every module-level memo. That trap is now in docs/local-environment.md.

Why not AsyncLocalStorage. The ticket rejected it because tryGetContext() returns undefined outside a request. The stronger reason is correctness: Hono's context is keyed per HTTP request, which is wider than the pageContext. Vike forks the pageContext on abort, and loadSiteContext caches a promise that can reject with throw render(404) — under ALS keying the _error re-render, same HTTP request, would read back that rejected promise and re-throw the abort. Keying on the forked object gets a miss, which is the correct answer.

Why not a plain pageContext property. The public proxy traps only get, so a write does reach the shared target and both hook views read it back, with no warning. It loses on three counts. objectAssign merges the route's result and every hook's return value onto that one flat namespace through Object.defineProperties with no collision guard, so a name clash overwrites the memo silently. The slot would need declaring in types/vike.d.ts, putting it on every pageContext in the app. And forkPageContext copies it into the abort's context, which is the AsyncLocalStorage defect again: the error page reads back the promise that rejected with the abort. That reasoning now sits beside the internal in server/request-memo.ts, which is where a reader stops.

Why not a module-local symbol. It answers the first two — objectAssign merges string keys, and a symbol needs no types/vike.d.ts entry — and loses to the third. forkPageContext hands the fork Object.getOwnPropertyDescriptors of the original, which includes symbols. request-memo.test.ts now builds the fork with vike's own forkPageContext and pins the miss.

Why no third-party package. The vike ecosystem's data packages integrate a query client or a store (vike-react-query, vike-vue-query, vike-react-zustand); none holds anything per request. DataLoader still needs a per-request home to keep its loaders in, which is this problem rather than an answer to it. unctx, Hono's contextStorage and the @universal-middleware context already in package.json are all AsyncLocalStorage keyed per HTTP request.

Why perRequest and not just memoKey. Exporting only the key left the shape that caused #108 still writable — a later memo could read with the derived key and write with the raw argument, and typecheck, because both are object. Seven cases fail against the old keying, including a concurrent pair pinning that perRequest stores the promise rather than the value, which is what makes the Promise.all in +onBeforeRender a single read.

Why the test fixture uses vike's own wrapper. The first pass hand-rolled a proxy exposing _originalObject. That pins what memoKey reads rather than what vike does: switching to the documented hatch would have left those specs green while production regressed. tests/_helpers/page-context.ts wraps one object with getPageContextPublicShared instead, forks with forkPageContext, and names vike's version in the error when the dist/ layout moves.

Cost. ~35 ns added per memo call, against a KV round trip (or, under preview, a full CMS fetch) removed per render. loadSiteContext's re-key is defensive — only data() calls it today; the translations and live-preview memos are where the duplicate I/O actually was.

Security. The memo key object is created fresh per renderPageServer() call, and error/abort paths fork to a new object, so they fail closed and re-verify the token — pinned by a spec, since every rejected alternative fails exactly here. No cross-request session bleed; passToClient is unchanged and toClientState still strips the token.

Scope check. Only four WeakMaps exist repo-wide: the three fixed, plus lib/i18n.ts, which keys on the translations object. That one's comment says "the translations object is stable for a request" — a premise that was false under the bug and is only now true.

Review findings dismissed: keying on Hono's Context instead (see the ALS note above); adding _originalObject to types/vike.d.ts, which would put a vike internal into every pageContext autocomplete in the app, including client components that never wrap; giving site-context.test.ts and live-preview.test.ts a hand-rolled stand-in for hookViews, which would have to expose _originalObject and so copy what memoKey reads into two more files — the one dist/ coupling already fails with an error naming server/request-memo.ts.

Closes #108

🤖 Written by the sydevs autonomous loop — see what this is


🤖 Generated with Claude Code

https://claude.ai/code/session_01RLng9q8acEgjdcswWDFjQs

`site-context.ts` and `live-preview.ts` memoised on the `pageContext`
argument. Vike builds a fresh public Proxy for every hook call, so `data()`
wrote each memo under one key and `+onBeforeRender` looked it up under
another and missed — a second `wm-web-translations` read on every chromed
SSR render, and a second token verification on every preview render.

`memoKey` reads the proxy's target through `_originalObject`, which vike's
own `execHookDataAndOnBeforeRender` mutates between the two hooks and
`getPageContextPublicShared` asserts it preserves. Its own module because
`site-context.ts` imports `live-preview.ts`, so neither could own it.

Measured on `pnpm dev` at `/`, warm, counting `loadTranslations` misses:
two before, one after, one `wm-web-config` read either way.

Three comments claimed a memo hit that did not happen. They do now.

Refs #108

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016WMB3nmzsr7UzNbzc4kiT3
…equest

`server/site-context.ts` had no spec at all. The new cases stand two proxies
over one target in for vike's two hooks and count the work behind them:
`getWebTranslations` calls for the globals, `crypto.subtle.importKey` calls
for the token. All five fail against the previous keying.

`request-memo.test.ts` guards the vike internal the fix rides on, against the
resolved `vike` in `node_modules` rather than a description of it — that the
wrapper hands out distinct proxies over one target, and that it reads
`_originalObject` without the warning `getPublicProxy` otherwise emits. The
third case drives that warning deliberately, so the silence in the second
cannot pass by vike dropping the warning altogether.

Refs #108

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016WMB3nmzsr7UzNbzc4kiT3
…cumented hatch

Two changes the review pass asked for, both narrowing what a future memo can
get wrong.

`perRequest` replaces the three hand-written get/compute/set blocks. Exporting
only the key left the half-keyed shape that caused #108 still writable: a
fourth memo could read with the derived key and write with the raw argument and
typecheck, because both are `object`. The WeakMap is no longer touched directly.

`memoKey` now reads through `dangerouslyUseInternals`, which vike types on
`PageContextServer` and documents at vike.dev/warning/internals. `getProp` sets
`skipOnInternalProp` before re-proxying, so that read cannot emit vike's
internal-property warning — where a bare `_originalObject` read stays quiet only
while whoever built the proxy passes the flag. Verified against a proxy built
with warnings enabled: `_originalObject` warns, the hatch does not. The cast
goes away with it.

Also corrects the new comment on `+onBeforeRender`: it claimed both reads are
memo hits, but the embed routes' `data()` asks only for the preview verdict, so
there the translations read is genuinely the first.

Refs #108

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016WMB3nmzsr7UzNbzc4kiT3
… memoKey reads

The first pass hand-rolled a proxy exposing `_originalObject`. That pins the
memo's current implementation rather than vike's behaviour: change what
`memoKey` reads and the specs stay green while production regresses to the
double fetch. `tests/_helpers/page-context.ts` wraps one object with vike's own
`getPageContextPublicShared` instead, so the fixture is the real pair of hook
views, in one place rather than three.

Also removes a time bomb. `loadLivePreview` passes no `nowSeconds`, so `jose`
reads the wall clock, and minting against the suite's fixed `NOW`
(2027-01-15) would have turned this file red on that date with a message about
the memo rather than expiry. Tokens are now minted relative to now.

Seven cases fail against the previous keying, including a concurrent pair that
pins `perRequest` storing the promise rather than the value — what makes the
`Promise.all` in `+onBeforeRender` one read. Adds the first coverage of
`site-context.ts`, which had no spec: both English-snapshot fallbacks and the
404 on an unavailable locale.

Refs #108

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016WMB3nmzsr7UzNbzc4kiT3
… locally

`server/AGENTS.md` gains the rule, since it loads on any read under `server/**`
and a new memo need not touch any file that carries the doc comment.

`docs/rules/rest-api.md` said `loadSiteContext` memoizes "on the `pageContext`
object", which is the mistake #108 was.

`docs/local-environment.md` names the memo key as a second cause of a doubled
read, and warns to count on a warm server: while Vite is still optimizing deps
it logs `[vite] program reload` and rebuilds the SSR module graph mid-request,
which resets every module-level memo. A cold first render shows duplicates that
a warm one does not — that cost this session a wrong reading before the A/B.

Refs #108

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016WMB3nmzsr7UzNbzc4kiT3
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Deploying wemeditate-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: 3cfa9c2
Status: ✅  Deploy successful!
Preview URL: https://231a7e11.wm-design.pages.dev
Branch Preview URL: https://claude-fix-108-memo-key.wm-design.pages.dev

View logs

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
wemeditate-web 3cfa9c2 Commit Preview URL

Branch Preview URL
Sep 22 2026, 04:04 AM

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 17, 2026
@sydevs-bot

sydevs-bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running
CI fix 2

recent dispatches
  • 03:59Z resolve-conflicts · attempt 1 · session · done
  • 03:59Z resolve-conflicts · attempt 1 · session
  • 16:32Z address-review · attempt 1 · session · done
  • 16:32Z address-review · attempt 1 · session
  • 02:14Z fix-ci · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot left a comment

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.

🧐 Adversarial review

The diff is the size of the bug: ~40 production lines over three call sites, the rest the spec site-context.ts never had, plus doc sync. Scope matches #108 and settles its open question. No contract moves — live-preview.ts changes memoisation, not the token format.

The judgement call the body flags holds up. Against [email protected]: two hook proxies over one target, dangerouslyUseInternals._originalObject === target, and getPageContextPublicServer is only getPageContextPublicShared, so the fixture is the production wrapper. But a plain property write crosses both hooks too, with no internal and no warning.

Findings

  • consider — server/request-memo.ts:24 — a pageContext property may reach the same target without the internal.
  • consider — tests/_helpers/page-context.ts:23 — three specs now ride vike's dist/ layout; one case needs it.

Checked: #108, all 11 changed files, every pages/** caller of the three loaders — embed data() does ask only for the preview verdict, as the new comment claims.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread server/request-memo.ts Resolved
Comment thread tests/_helpers/page-context.ts Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 17, 2026
The public proxy traps only `get`, so a property write does cross both hook
views — verified against [email protected], with no warning. It is rejected for two
other reasons, and the internal is what a reader stops on, so they belong
beside it: vike's `objectAssign` merges the route's result and every hook's
return value onto the same flat namespace via `Object.defineProperties` with no
collision guard, and the slot would need a declaration in `types/vike.d.ts`
that every `pageContext` in the app would then carry.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JTTKvDQuc2cxMqEroGpdDb
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Both adversarial-review threads answered. Pushed 068ec03; lean gate green (lint 0 errors, tsc --noEmit, 71 files / 659 tests).

Adopted — server/request-memo.ts:24. The mechanism was right: the property write does cross both proxies, with no warning. So the note beside the internal now records what sinks it — objectAssign merges every hook's return onto that flat namespace with no collision guard, and the slot would need declaring in types/vike.d.ts app-wide. Resolved.

Rebutted — tests/_helpers/page-context.ts:23. A stand-in must expose _originalObject, copying what memoKey reads into two more files. The one dist/ coupling already fails with an error naming server/request-memo.ts. Left open for you.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 17, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review September 17, 2026 01:52
@sydevs-bot
sydevs-bot requested a review from Ardnived September 17, 2026 01:52
Comment thread server/request-memo.ts Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 18, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

One thread, answered with a question. Nothing pushed — the ask is architectural.

Asked — server/request-memo.ts. No vike built-in memoises per request. getPageContext() cannot: measured against 0.4.266 it returns a fresh proxy on every call, and null after a single await, so an async loader never reaches it.

What does work is a slot on pageContext — the approach the ⚠ block rejects. A module-local Symbol removes both of its objections: objectAssign merges the hook returns' string keys, which a module-local symbol cannot clash with, and a symbol needs no types/vike.d.ts declaration. createPageContextObject() still builds a fresh object per render, so the abort fork still misses and re-verifies the token.

That would delete memoKey, dangerouslyUseInternals and tests/_helpers/page-context.ts, and close the second thread with it. It reverses a decision this PR documents, so it waits on you.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. awaiting labels Sep 18, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 18, 2026
Cloudflare Pages is red on 797d9c9, and the build log lives only in the
Cloudflare dashboard, which a routine cannot reach. The branch forked at
2af1870, three commits back, so the Pages build was still installing the
pre-#111 dependency tree: 88 extra packages and a whole unused Next.js
subtree. This merge builds against the tree main installs today.

It also brings in the two server changes this PR's memos sit on top of:
#107 drops `preview` from `getWebConfig`, which `loadSiteContext` calls,
and #113 adds `+onCreatePageContext.server.ts`, the error-page path this
PR's fork spec describes.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B9MPJ8NWXhK85k27xRq6Ji
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged main in and pushed 05e4897. Pages was the only red check.

I still cannot read the Cloudflare build log, so this names no root cause. Red again on 05e4897 means the dashboard log is the next step.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 18, 2026
@sydevs-bot sydevs-bot moved this from Revising to Approved in SYDevelopers Technical Roadmap Sep 18, 2026

@Ardnived Ardnived left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is it possible that updating Vike would allow us to resolve this issue with less custom code?

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 18, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

No vike update exists, and the newest vike has the same defect. Nothing pushed.

Rebutted — updating vike. [email protected] is npm's latest, published 2026-09-02, and is what pnpm-lock.yaml resolves. The only newer artifact is 0.4.266-commit-e71fad0, a commit snapshot of that same version.

Vike's own per-request accessor does not help either. getPageContext({ asyncHook: true }) — the option answering the null-after-await I reported last round — returns a fresh proxy per call (dist/server/runtime/asyncHook.js). Measured against the installed 0.4.266:

same object across two calls?  false
WeakMap keyed on it hits?      false
unwrapped targets identical?   true

That reproduces #108 rather than removing memoKey. Only the unwrapped target is stable.

The custom surface is two functions. If vike ships a stable per-request store later, only memoKey's body changes.

Left open for you.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 18, 2026
@sydevs-bot sydevs-bot moved this from Approved to Revising in SYDevelopers Technical Roadmap Sep 18, 2026
@sydevs-bot sydevs-bot moved this from Revising to Approved in SYDevelopers Technical Roadmap Sep 18, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 22, 2026
#131 renamed the SahajCloud modules. The only textual conflict was the
import block in `server/site-context.ts`: this branch added `perRequest`
where main renamed `./cms-types` to `./sahajcloud-types`. Both sides kept.

`server/site-context.test.ts` is new on this branch, so git merged it
without a conflict while its imports still named `./cms-client` and
`./cms-types`. Repointed, along with the three "CMS" mentions in its
prose, which #131 would have rewritten had the file existed on main.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014BPd2Y1UEHBrEGkEPEw5oa
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged main and pushed. #131's SahajCloud rename is what conflicted.

One textual conflict, in server/site-context.ts: this branch adds the perRequest import where main renamed ./cms-types to ./sahajcloud-types. Both sides kept.

server/site-context.test.ts is new on this branch, so git merged it with no conflict while its imports still named ./cms-client and ./cms-types. Repointed, along with its three "CMS" mentions.

Lean gate green on the merge: lint 0 errors, tsc --noEmit, 785 tests across 78 files.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 22, 2026
@sydevs-bot
sydevs-bot added this pull request to the merge queue Sep 22, 2026
Merged via the queue into main with commit 88d1b8b Sep 22, 2026
11 checks passed
@sydevs-bot
sydevs-bot deleted the claude/fix-108-memo-key branch September 22, 2026 04:12
@sydevs-bot sydevs-bot moved this from Approved to Done in SYDevelopers Technical Roadmap Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

fix(server): the per-request site-context memo misses, because Vike hands each hook a new pageContext Proxy

3 participants