Skip to content

fix(dev): key route module reloads on mtime so module state survives a request - #3912

Merged
kojiwakayama merged 3 commits into
mainfrom
fix/dx-dev-route-module-reuse
Aug 21, 2026
Merged

kojiwakayama merged 3 commits into
mainfrom
fix/dx-dev-route-module-reuse

Conversation

@kojiwakayama

Copy link
Copy Markdown
Contributor

What

Under veryfront dev, module-level state in an API route resets between requests. Under veryfront serve it persists. Same code, different behaviour, no error either way.

Measured with a module-scoped id returned from a route (0.1.1246-rc.13479):

dev  (:3000)  same route, 3 calls → k2u8zg / 7j7tl5 / 25hs0k   (new instance each request)
prod (:3100)  same route, 3 calls → jxv31l / jxv31l / jxv31l   (stable)

Cause

src/routing/api/module-loader/loader.ts appended ?v=${Date.now()} to the import URL on the direct-import path, unconditionally. Every request routes through loadHandlerModule, so every request minted a new module URL and therefore a new module instance.

The intent is clearly hot reload. The defect is that it busts the cache even when the file has not changed.

Why it matters beyond one feature

Any module-scoped client, cache, connection pool, rate limiter, or in-memory store behaves differently in dev than in production, silently.

It is also what makes the workflows guide's start-then-poll flow impossible in dev: createWorkflowClient() keeps runs in a per-instance MemoryBackend, so with a new module per request no run is ever visible to a later one. Extracting a shared client module does not help, because the shared module is re-instantiated too. (The doc side of that is #3911; this is the runtime side.)

Fix

Key the cache buster on the file's mtime. An edited route gets a new module; an untouched route keeps the one it has. A filesystem that cannot report mtime falls back to the clock, which is no worse than current behaviour.

Verification

Two tests, pinning both halves — I confirmed the first fails against the old implementation and the second already passed, so hot reload is genuinely protected rather than assumed:

  • reuses an unchanged route module so module state survives between requests
  • picks up an edited route module instead of serving the cached one

Live check against a real dev server built from this branch:

call 1: {"instance":"41p1tq","count":1}
call 2: {"instance":"41p1tq","count":2}
call 3: {"instance":"41p1tq","count":3}

# then edit the route file on disk
call 1: {"instance":"ixgcld","count":101,"edited":true}
call 2: {"instance":"ixgcld","count":102,"edited":true}

State persists, and the edit is still picked up without a restart. Full pre-push suite green.

Found while dogfooding the documented developer journey.

…a request

Every request loads its route through `loadHandlerModule`, and the direct-import
path appended `?v=${Date.now()}` unconditionally. That minted a fresh module URL
per load, so module-level state reset between requests under `veryfront dev`
while persisting under `veryfront serve`.

The cost is not limited to any one feature: a module-scoped client, cache,
connection pool, or in-memory store behaves differently in dev than in
production, silently and with no error to show for it. It is what makes the
workflows guide's start-then-poll flow impossible in dev, because
`createWorkflowClient()` keeps runs in a per-instance memory backend.

Key the cache buster on the file's mtime instead. An edited route still gets a
new module, and an untouched route keeps the one it already has. A filesystem
that cannot report mtime falls back to the clock, which is no worse than today.

Both halves are pinned by tests: state survives a repeat load of an unchanged
file, and an edit is still picked up rather than served from cache.
@coderabbitai

coderabbitai Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@kojiwakayama, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 28 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fba236be-248b-4852-b440-0a9128cb6751

📥 Commits

Reviewing files that changed from the base of the PR and between 23803a6 and dc62189.

📒 Files selected for processing (2)
  • src/routing/api/module-loader/loader.test.ts
  • src/routing/api/module-loader/loader.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

📦 Client bundle boundary

Entrypoint Modules Source size Server leaks
src/index.client.ts 326 1949 KiB ✅ 0

A server module in a client graph aborts hydration in the browser. New leaks fail CI; known leaks are tracked in scripts/lint/client-bundle-baseline.json to burn down.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4438e5c981

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/routing/api/module-loader/loader.ts Outdated
@kojiwakayama

Copy link
Copy Markdown
Contributor Author

Scope note, so the fix is not read as broader than it is.

loadModule has two paths, and this PR only fixes one.

Direct import (loadTSModuleDirect, local file, Deno, non-compiled) is what this PR fixes. It was keyed on Date.now(); it is now keyed on mtime. The tests and the live dev-server check both exercise this path.

Bundle and transpile (loadAndTranspileModule) is not fixed here, and has the same defect by a different mechanism: loadModuleFromCode writes every load into a fresh temp dir —

const tempDir = await fs.makeTempDir({ prefix: "vf-api-" });
const tempFile = pathHelper.join(tempDir, "handler.mjs");

— so the module URL is unique per load regardless of whether the source changed. Because bundling inlines dependencies, this also re-instantiates any module the route imports, which is why extracting a shared client module into lib/ did not help in the project I first measured this on. That project reached the bundling path; the counter project in the description reached the direct path.

Fixing that side means keying the temp file on a content hash and reusing it, which is a larger change than this one and worth doing separately rather than folding in here.

So: after this PR, module state survives between requests on the direct-import path. Routes that fall back to bundling still reset per request.

…nged

The mtime fix covered the direct-import path only. A route that Deno cannot
resolve on its own, such as one importing through the project's `@/` alias,
falls back to bundling, and that path had the same defect by a different
mechanism: `loadModuleFromCode` imports from a fresh `makeTempDir` every call,
so the module URL is unique per load no matter what the source says. Because
bundling inlines dependencies, this re-instantiated everything the route
imported too, which is why extracting a shared client module did not help.

Cache bundled modules on their generated source instead. The key carries the
project and route path as well as the code, so two projects that happen to
bundle byte-identical output never share a module, and with it module state. A
failed build is not remembered, and the cache is capped so a long editing
session does not grow without bound.

Together with the previous commit, both load paths now keep module state across
requests and still pick up an edit.
Route modules need stable instances while unchanged and fresh imports after any edit. Mtime alone can collide on coarse filesystems or same-millisecond same-size writes, so the direct import key now includes a source digest. The bundled fallback keeps equivalent generated-source caching scoped to the project route.

Confidence: high

Scope-risk: moderate

Tested: deno test --preload=src/testing/preload.ts --no-check --allow-all --unstable-worker-options --unstable-net src/routing/api/module-loader/loader.test.ts

Tested: deno check src/routing/api/module-loader/loader.ts src/routing/api/module-loader/loader.test.ts

Tested: git diff --check -- src/routing/api/module-loader/loader.ts src/routing/api/module-loader/loader.test.ts
@kojiwakayama

Copy link
Copy Markdown
Contributor Author

Pushed ca1d8d60a, which closes the gap I flagged above. Both load paths are now fixed, so the scope note no longer applies.

loadModuleFromCode imported from a fresh makeTempDir on every call, so the bundling path minted a unique module URL regardless of the source. Bundled modules are now cached on their generated source, keyed by project and route path as well as the code, so two projects that happen to bundle identical output never share module state. Failed builds are not cached, and the cache is capped.

Two more tests, same shape as the direct-path pair, and I confirmed the reuse one fails against the old implementation first:

  • reuses an unchanged bundled route module too
  • rebuilds a bundled route module when its source changes

The project that previously reset every request now holds state and still hot reloads:

call 1: {"instance":"36x17l","count":1}
call 2: {"instance":"36x17l","count":2}
call 3: {"instance":"36x17l","count":3}
# edit the shared lib
call 1: {"instance":"ihe8ns","count":501}
call 2: {"instance":"ihe8ns","count":502}

src/routing/ suite: 44 passed, 0 failed. Full pre-push green.

This also unblocks #3913. With both commits applied, a workflow started in one request is readable in the next on the bundling path, which was returning 404 before:

POST /api/workflows/pipeline/start   → {"runId":"run_ba3605c9-5d5"}
GET  /api/workflows/runs/run_ba36…   → {"status":"completed","nodes":[{"only":"completed"}]}

@kojiwakayama
kojiwakayama added this pull request to the merge queue Aug 21, 2026
Merged via the queue into main with commit 199bd13 Aug 21, 2026
34 checks passed
@kojiwakayama
kojiwakayama deleted the fix/dx-dev-route-module-reuse branch August 21, 2026 06:29
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.

1 participant