Skip to content

Serialize concurrent frontend dependency installs - #7051

Open
Alek99 wants to merge 18 commits into
mainfrom
codex/serialize-frontend-installs
Open

Alek99 wants to merge 18 commits into
mainfrom
codex/serialize-frontend-installs

Conversation

@Alek99

@Alek99 Alek99 commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Why

Two Reflex processes can currently enter the same frontend install transaction together. Both can mutate .web, invoke the package manager, overwrite the procedure cache, and persist root lockfiles concurrently. A simultaneous frontend reinitialization can also replace .web during an install.

What changed

  • Add a dependency-free per-project process lock at the stable, ignored app-root path .reflex.frontend.lock. POSIX uses flock; Windows uses a retrying one-byte msvcrt lock. The process-local layer is thread-safe and reentrant, and the OS releases ownership after crashes.
  • Hold that lock across the complete public install transaction: package-manager selection, root-to-web synchronization and cache invalidation, cached install execution, cache commit, and web-to-root persistence.
  • Coordinate initialize_web_directory with the same lock so it cannot replace .web during an active install.
  • Atomically replace procedure-cache and persisted package-manager files. Invalid/truncated pickles become cache misses; genuine I/O errors still surface. Existing modes and symlinks are preserved.
  • Keep the lock implementation lazily imported so ordinary CLI startup does not load platform lock modules or allocate lock state.

Atomic replacement guarantees complete-file visibility and preserves the prior file when commit fails; it does not claim power-loss durability without fsync.

Validation

  • uv run pytest -q tests/units/test_prerequisites.py tests/units/utils/test_utils.py tests/units/reflex_base/constants/test_base.py tests/units/reflex_base/constants/test_installer.py — 344 passed
  • uv run ruff check . — passed
  • uv run ruff format --check . — 1407 files already formatted
  • uv run pyright reflex tests — 0 errors, 0 warnings
  • uv run pre-commit run --all-files — all hooks passed, including Ruff, codespell, Pyright, ty, and Biome
  • Independent adversarial review: 104 prerequisite tests and 16 focused concurrency/atomic/cache tests passed; no release-blocking findings

Tests cover positive same-project OS contention, complete transaction scope, completed-cache reuse by a waiting process, separate-project concurrency, reentrancy, exceptions and abrupt process exits, Windows contention retries, initialization exclusion, atomic failure recovery, corrupt-cache recovery, permissions, and symlink compatibility.

Checklist

  • Bug fix (non-breaking)
  • Followed CONTRIBUTING.md
  • Checked for overlapping open PRs
  • Added regression tests for core behavior
  • Ran tests and linters locally

Review in cubic

@Alek99
Alek99 requested a review from a team as a code owner September 6, 2026 07:59
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@cubic-dev-ai cubic-dev-ai Bot 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.

All reported issues were addressed across 9 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread reflex/utils/frontend_lock.py Resolved
@codspeed

codspeed Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 20 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 151 untouched benchmarks


Comparing codex/serialize-frontend-installs (281f8dc) with main (99cf380)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (1ad20b0) during the generation of this report, so 99cf380 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@greptile-apps

greptile-apps Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable issues found.

Summary

Serializes frontend installs and workspace initialization with the existing per-path lock.

  • Frontend installs and .web initialization take turns for each app.
  • Package files appear as complete files when Reflex replaces them.
  • Damaged procedure caches are rebuilt instead of stopping the caller.

Reviews (11) · Last reviewed commit: "Write through symlinked frontend files a..." · Reviewed by Greptile

Comment thread reflex/utils/frontend_lock.py Resolved
Comment thread tests/units/test_prerequisites.py Resolved

@cubic-dev-ai cubic-dev-ai Bot 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.

All reported issues were addressed across 6 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread reflex/utils/frontend_lock.py Resolved
Alek99 and others added 5 commits September 6, 2026 01:48
Two exports (or an export and a prod/preview start) in the same project
used to race on .web: the second replaced build/ and env.json while the
first was still compiling or zipping, so one of them shipped the other's
frontend. Hold an exclusive, reentrant file lock on
.web/.reflex-build.lock from compilation through ZIP creation, release it
before serving, and never create .web for a backend-only export that has
nothing to protect.

Split out of #7054 (lock only; the opt-in build cache that needs it follows
separately).

Claude-Session: https://claude.ai/code/session_018nWB9r2HcC5tkT72UxWgGj
PERF203 only applies before Python 3.11, where try/except in a loop costs
per iteration. With ruff targeting py311 since #7449 the directive is
unused, which RUF100 rejects.

Claude-Session: https://claude.ai/code/session_01PXcFKAgnzhgdnSvhuCmxWE
# Conflicts:
#	reflex/utils/js_runtimes.py
#	tests/units/test_prerequisites.py
Comment thread reflex/utils/frontend_lock.py Resolved
- Generalize path_ops.json_file_lock into file_lock and lock the web dir
  for installs and .web initialization; drop reflex/utils/frontend_lock.py,
  the project-root .reflex.frontend.lock file and its gitignore entry.
- Extract path_ops.atomic_write from _write_json_file and use it for
  package.json and lockfile writes; drop the private skeleton writer.
- Keep procedure cache writes plain (they run under the install lock) and
  read a corrupt cache file as a miss with a single except clause.
- Stub the lock in test_js_runtimes and isolate REFLEX_DIR so unit tests
  no longer leave lock files behind; drop tests for removed machinery.
Comment thread reflex/utils/js_runtimes.py Resolved
Comment thread reflex/utils/frontend_skeleton.py Resolved

@cubic-dev-ai cubic-dev-ai Bot 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.

1 issue found across 15 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="news/+serialize-frontend-installs.bugfix.md">

<violation number="1" location="news/+serialize-frontend-installs.bugfix.md:1">
P3: This guarantee is too absolute: `file_lock` intentionally proceeds unlocked when the lock location is unavailable, so concurrent installs can still race in that supported configuration. Qualify the fragment to say coordination applies when the OS lock is available, while atomic writes still prevent partial files.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread reflex/utils/frontend_skeleton.py Resolved
Comment thread reflex/utils/path_ops.py Resolved
@@ -0,0 +1 @@
Serialize frontend dependency installs and `.web` initialization per app, and atomically persist package-manager files, so concurrent Reflex commands in one app no longer corrupt or duplicate an install.

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.

P3: This guarantee is too absolute: file_lock intentionally proceeds unlocked when the lock location is unavailable, so concurrent installs can still race in that supported configuration. Qualify the fragment to say coordination applies when the OS lock is available, while atomic writes still prevent partial files.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At news/+serialize-frontend-installs.bugfix.md, line 1:

<comment>This guarantee is too absolute: `file_lock` intentionally proceeds unlocked when the lock location is unavailable, so concurrent installs can still race in that supported configuration. Qualify the fragment to say coordination applies when the OS lock is available, while atomic writes still prevent partial files.</comment>

<file context>
@@ -1 +1 @@
-Serialize frontend dependency installation per app and atomically persist package-manager files so concurrent Reflex commands cannot corrupt or duplicate an install.
+Serialize frontend dependency installs and `.web` initialization per app, and atomically persist package-manager files, so concurrent Reflex commands in one app no longer corrupt or duplicate an install.
</file context>
Suggested change
Serialize frontend dependency installs and `.web` initialization per app, and atomically persist package-manager files, so concurrent Reflex commands in one app no longer corrupt or duplicate an install.
Serialize frontend dependency installs and `.web` initialization per app, and atomically persist package-manager files. Concurrent commands are coordinated when the OS lock is available; when it is unavailable, atomic writes prevent partial files but installs may still race.

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.

With the best-effort lock confirmed as the design (masenf on #7453), this wording nit is fair: the fragment could say coordination applies when the OS lock is available while atomic writes still prevent partial files. Leaving the edit to the PR's author since it is a one-line docs change on their branch.


Generated by Claude Code

The production build lock had its own copy of the platform-specific
locking (flock / msvcrt) next to the sidecar-based json_file_lock, with
different Windows polling, a different failure mode and a lock file inside
.web. Keep one implementation: json_file_lock becomes file_lock, usable for
files and directories, and gains the reentrancy and fork handling the build
lock needed. Exports and production/preview startup now lock the .web
directory through it.

The sidecar lives in REFLEX_DIR, so locking never creates .web and the
lock inode survives .web being replaced. Backend-only exports therefore
always take the lock instead of skipping it when .web is absent, which
closes the race the review bots flagged. The lock is released explicitly
on Windows before the descriptor closes.

Claude-Session: https://claude.ai/code/session_017XAFCkYB3Z8w3S6pgJrLCh
# Conflicts:
#	reflex/utils/path_ops.py
#	tests/units/utils/test_path_ops.py
The backend ZIP walks the app root, and REFLEX_DIR sat inside it, so the
exporter archived its own held lock file. Windows refuses reads of a
byte-range-locked file, failing the zip with PermissionError.

Claude-Session: https://claude.ai/code/session_01PXcFKAgnzhgdnSvhuCmxWE
@FarhanAliRaza
FarhanAliRaza changed the base branch from main to farhan/frontend-workspace-lock October 19, 2026 21:15

FarhanAliRaza commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Merged the head of #7453 into this branch (merge commit, no history rewrite). The PR stays targeted at main: this repo's test workflows only run for pull requests against main, so a stacked base would leave it with no unit or integration CI. Until #7453 merges, the diff therefore also shows #7453's changes.

Why: #7453 holds file_lock(get_web_dir()) across the whole export, and build.setup_frontend calls install_frontend_packages, which this PR locks on the same path. With this PR's non-reentrant file_lock, merging both independently would deadlock inside every export. #7453 now carries the single path_ops.file_lock (same name and semantics as here, plus same-thread reentrancy, fork handling, and an explicit Windows unlock), so the install lock nests inside the export lock.

Resolution: the json_file_lock to file_lock rename conflicted in path_ops.py and its tests; both sides were kept as #7453 has them. atomic_write, the install and initialize_web_directory locking, and the procedure-cache changes are untouched. A later merge brought in #7453's Windows fix for the export race test. ruff, pyright reflex tests, codespell, and the utils, CLI, prerequisites and decorator unit suites pass on the merged head.


Generated by Claude Code

@FarhanAliRaza
FarhanAliRaza changed the base branch from farhan/frontend-workspace-lock to main October 19, 2026 21:37
development_dependencies.update(
_pinned_args_from_constants(
constants.PackageJson.REACT_COMPILER_DEV_DEPENDENCIES
with path_ops.file_lock(get_web_dir()):

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.

P1 Preview startup hangs

When Granian is selected, _run_preview holds the .web lock while _compile_app starts a worker process and waits for it. During compilation, that worker reaches this new lock acquisition and waits for the parent to release the same lock. Neither process can continue, so the preview server never starts.

Move compilation and lock ownership into the same process, or change the preview lock scope so the parent does not hold it while waiting.

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.

Confirmed from the code. With Granian selected (the default when uvicorn and gunicorn are absent), _run_preview holds file_lock(.web) and calls _compile_app(), which runs compile_or_validate_app in a ProcessPoolExecutor worker. That reaches App._compile → js_runtimes.install_frontend_packages, which with this PR takes file_lock(get_web_dir()) in the worker. The parent waits on the worker's result, the worker waits on the parent's lock. _run_prod compiles in-process (avoid_dirty_check=False) and export compiles in-process, so only the preview path deadlocks. This only appears now that #7453 is on main.

Smallest fix, in reflex/reflex.py: pass the parent's held lock paths (path_ops._held_locks.paths) into _compile_app_worker and seed the worker's _held_locks.paths with them before running the task. The worker then reenters the lock the parent holds, which is correct because the parent is blocked on it for the whole compile. About six lines plus a test; it is safe on main without this PR too. Leaving the choice of where it lands (this PR or a small PR against main) to the author.


Generated by Claude Code

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.

Thanks for confirming the execution path. This is a real deadlock introduced by the new lock scope: in Granian preview, the parent holds the .web lock while waiting for the compile worker, while the worker reaches the same lock during install_frontend_packages.

The proposed handoff is the smallest targeted fix: pass the parent’s held lock paths to _compile_app_worker, seed the worker’s process-local held-path set before invoking app_task, and add a regression test covering Granian preview compilation. This preserves the existing fork behavior— inherited descriptors are cleared—while making the worker’s reentrant acquisition explicit. Please land that fix before merging this PR, whether here or as the prerequisite change on main.

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.

Fixed in 281f8dc: _compile_app passes path_ops.held_lock_paths() to the worker, which calls path_ops.adopt_held_locks before compiling, so the worker reenters the .web lock the waiting parent holds. Regression tests in test_reflex.py and test_path_ops.py cover the handoff.


Generated by Claude Code

Preserve atomic manifest writes alongside UTF-8/LF package.json formatting.
Add atomic replacement and rollback regression coverage.

Copy link
Copy Markdown
Contributor

Pushed 61d1052 on top of the main merge: pre-commit's codespell read the escaped "café" in the new test_frontend_skeleton.py fixture as the word "caf" and failed the check. The fixture now spells the character literally; codespell and the module's tests pass locally. No other changes.


Generated by Claude Code

…the compile worker

atomic_write replaced a symlinked destination (e.g. a root bun.lock linked
to a shared file) with a regular file and left the shared file stale. It now
resolves the destination first, so the link survives and its target is
replaced, as the previous copy-based writer did.

With Granian, `reflex run --env preview` holds the .web lock while a
ProcessPoolExecutor worker compiles the app, and that compile's frontend
install takes the same lock: the parent waited on the worker and the worker
on the parent. _compile_app now hands the locks held by its thread to the
worker, which reenters them; the parent stays blocked for the whole compile,
so the worker effectively owns them.

Claude-Session: https://claude.ai/code/session_01LwJUCTv4VmfFw1ND9wvz8Z

@cubic-dev-ai cubic-dev-ai Bot 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.

1 issue found across 5 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="tests/units/test_reflex.py">

<violation number="1" location="tests/units/test_reflex.py:228">
P2: The deadlock cleanup kills every active child process, which can terminate unrelated test subprocesses and create cascading, misleading failures. Track the pool’s child process or the child set created by this test, then terminate only those processes.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

View guided diff | Turn on auto-fix | Re-trigger cubic

deadlocked = thread.is_alive()
if deadlocked:
# Break the deadlock so the pool and the parent's lock are released.
for child in multiprocessing.active_children():

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.

P2: The deadlock cleanup kills every active child process, which can terminate unrelated test subprocesses and create cascading, misleading failures. Track the pool’s child process or the child set created by this test, then terminate only those processes.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/units/test_reflex.py, line 228:

<comment>The deadlock cleanup kills every active child process, which can terminate unrelated test subprocesses and create cascading, misleading failures. Track the pool’s child process or the child set created by this test, then terminate only those processes.</comment>

<file context>
@@ -175,6 +175,64 @@ def test_compile_app_worker_flushes_telemetry_on_failure(mocker):
+    deadlocked = thread.is_alive()
+    if deadlocked:
+        # Break the deadlock so the pool and the parent's lock are released.
+        for child in multiprocessing.active_children():
+            child.kill()
+        thread.join(DEFAULT_TIMEOUT)
</file context>

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.

Staying as is. That block runs only on the failure path, after the regression has already reproduced and the test has already failed; its sole job is to unwind the blocked pool so the suite can continue. multiprocessing.active_children() lists only this process's children, the unit suite does not run under xdist, and the pool's worker is created inside _compile_app, so the test has no handle to it. Tracking it would mean reaching into the executor for a cleanup that never runs when the fix holds.


Generated by Claude Code

@FarhanAliRaza FarhanAliRaza added the bug Something isn't working label Nov 12, 2026 — with ChatGPT Codex Connector

This branch has not been deployed

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

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants