Skip to content

[rust] Write se-metadata.json atomically - #18200

Merged
titusfortner merged 3 commits into
SeleniumHQ:trunkfrom
UweKubosch:sm-atomic-metadata-write
Nov 18, 2026
Merged

titusfortner merged 3 commits into
SeleniumHQ:trunkfrom
UweKubosch:sm-atomic-metadata-write

Conversation

@UweKubosch

@UweKubosch UweKubosch commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🔗 Related Issues

Follow-up to #18101, which made unparseable metadata a warning. Related to #14898, whose cache lock covers driver and browser downloads but not the metadata file.

💥 What does this PR do?

write_metadata wrote se-metadata.json in place (fs::write truncates, then writes). When several Selenium Manager processes share a cache, one of them can read the file between the truncate and the write, or halfway through it. This happens routinely in parallel test suites (e.g. Rails system tests with one worker per core), where every worker resolves the driver at the same moment. Since #18101 each such read logs:

WARN Selenium [:selenium_manager] Metadata file .../se-metadata.json cannot be parsed: EOF while parsing a string at line 14 column 13. Using empty metadata

With 18 workers we see about six of these per run, each pointing at a different line and column, one for each half-written file a reader caught.

This PR writes the metadata to a sibling temporary file and renames it over se-metadata.json. The rename is atomic within a filesystem, so a reader always sees either the previous or the new content.

🔧 Implementation Notes

  • The temporary file is se-metadata.json.<pid>.tmp in the cache folder, so the rename never crosses filesystems. It is created with fs::write, so the file mode follows the umask exactly as before. tempfile::NamedTempFile would create it 0600, which would change behaviour for caches shared between users.
  • If the write or the rename fails, the temporary file is removed and the existing warning is logged, as before.
  • fs::rename replaces an existing target on Windows too (MoveFileExW with MOVEFILE_REPLACE_EXISTING). If a reader holds the file open there, the rename can fail. The old metadata then stays in place and the existing warning is logged, which is no worse than today.
  • New test concurrent_reader_never_sees_partially_written_metadata (Unix only) reads the metadata in a loop while another thread rewrites it 500 times, and checks that every read returns the full content and that no temporary files are left behind. Without the change to metadata.rs it fails on the first read; with it, it passed 10 runs out of 10 locally (macOS, arm64).

🤖 AI assistance

  • No substantial AI assistance used
  • AI assisted (complete below)
    • Tool(s): Claude Code
    • What was generated: the change to write_metadata, the new test, and this description
    • I reviewed all AI output and can explain the change

💡 Additional Considerations

The same race can, in principle, lose updates: two processes that read, modify and write the metadata concurrently each write back only their own view. That costs one extra version lookup and is out of scope here.

🔄 Types of changes

  • Bug fix (backwards compatible)

Several Selenium Manager processes can share one cache, most commonly
when a test suite runs in parallel workers that each start a browser
at the same moment. write_metadata wrote the file in place, so a
process reading it in the meantime could see it truncated or half
written. Since SeleniumHQ#18101 that read is reported as "Metadata file ...
cannot be parsed: EOF while parsing ...", once per affected worker.

Write the metadata to a sibling temporary file and rename it over
se-metadata.json. The rename is atomic, so a reader sees either the
previous or the new content.
@selenium-ci selenium-ci added C-rust Rust code is mostly Selenium Manager B-manager Selenium Manager labels Oct 19, 2026
@CLAassistant

CLAassistant commented Oct 19, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@UweKubosch
UweKubosch marked this pull request as ready for review October 19, 2026 13:15
@qodo-code-review

Copy link
Copy Markdown
Contributor

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@titusfortner titusfortner added the Q-qodo-review Request a Qodo review label Nov 18, 2026
@selenium-ci

Copy link
Copy Markdown
Member

/agentic_review

@selenium-ci selenium-ci removed the Q-qodo-review Request a Qodo review label Nov 18, 2026
@qodo-code-review

qodo-code-review Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Concurrent threads can corrupt metadata 🐞 Bug ≡ Correctness
Description
write_metadata gives every thread in a process the same temporary pathname because it uses only
the process ID. If one thread renames that file while another still has it open for writing, the
second thread can continue writing into the installed metadata file and expose partial JSON to
readers.
Code

rust/src/metadata.rs[R265-267]

+        let tmp_path = metadata_path.with_extension(format!("json.{}.tmp", std::process::id()));
+        fs::write(&tmp_path, serde_json::to_string_pretty(metadata).unwrap())
+            .and_then(|_| fs::rename(&tmp_path, &metadata_path))
Evidence
The temporary pathname contains no per-call identifier, and the write and rename have no
synchronization. Metadata is read and written from multiple manager paths without a
metadata-specific lock; readers parse the destination directly.

rust/src/metadata.rs[96-128]
rust/src/metadata.rs[265-269]
rust/src/lib.rs[333-342]
rust/src/lib.rs[1219-1235]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Concurrent writers in one process share the PID-named temporary file, allowing writes to continue after another thread renames it into place.
## Fix Focus Areas
- rust/src/metadata.rs[265-269]
## Recommended Fix
Give each invocation its own exclusively created sibling temporary file, and rename or remove only that invocation's file. Add a multiple-writer regression test.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


2. Shared-cache writes can erase user files ✗ Dismissed
Description
write_metadata creates a predictable PID-named temporary path with fs::write, which follows a
symlink already placed at that path and truncates its target. In a cache directory writable by
another local user, that user can plant the link before a victim process writes and redirect the
write to any file the victim can modify; the subsequent rename does not undo the damage.


Remediation recommended

3. The concurrency test may skip all reads ✓ Resolved

Resolving commit: 2334c7b

Resolution reason
Added an assertion after writer.join() that reads > 0, so the test fails rather than silently
passing when the writer finishes before the reader performs any read.
Description
concurrent_reader_never_sees_partially_written_metadata checks done before its first read
without synchronizing the reader with the writer. If the writer finishes its iterations before the
reader reaches that check, the loop runs zero times and the test passes without exercising its
metadata assertion.

4. Read-only cache folders block updates ✗ Dismissed
Description
write_metadata now requires permission to create a sibling file and rename it in the cache
directory, even when the existing metadata file is writable. With a writable metadata file inside a
non-writable cache directory, the previous in-place update succeeded but the new temporary-file
creation fails, logs a warning, and leaves the metadata stale.

5. Formatter check fails on new test ✗ Dismissed
Description
The final assert! in concurrent_reader_never_sees_partially_written_metadata is wrapped across
four lines, although it fits on one line at about 81 columns under the default 100-column limit.
rustfmt would collapse it, so the repository formatter check fails on this changed file until the
assertion is reformatted.

View medium (1)
6. Shared users lose access to metadata ✗ Dismissed
Description
write_metadata now replaces the existing metadata file with a newly created file owned by the
current writer and governed by that writer's umask, rather than retaining the existing file's owner
and mode. If two users can write the cache directory and each uses a restrictive umask, one user's
rename can make the other's next get_metadata open fail and fall back to an empty cache.

Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #18101
  🌐 PR #14898
Review mode: Auto: 🚀 Fast: Localized concurrency regression test with contained, non-production behavior.
✅ Fix-loop round: fix loop

Grey Divider

Tip of the day
💡 Did you know, you can type 'qodo, fix this' on a finding and the fix lands right on your PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 2334c7b

Results up to commit ad421a0 ⚖️ Balanced


🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required
1. Concurrent threads can corrupt metadata 🐞 Bug ≡ Correctness
Description
write_metadata gives every thread in a process the same temporary pathname because it uses only
the process ID. If one thread renames that file while another still has it open for writing, the
second thread can continue writing into the installed metadata file and expose partial JSON to
readers.
Code

rust/src/metadata.rs[R265-267]

+        let tmp_path = metadata_path.with_extension(format!("json.{}.tmp", std::process::id()));
+        fs::write(&tmp_path, serde_json::to_string_pretty(metadata).unwrap())
+            .and_then(|_| fs::rename(&tmp_path, &metadata_path))
Evidence
The temporary pathname contains no per-call identifier, and the write and rename have no
synchronization. Metadata is read and written from multiple manager paths without a
metadata-specific lock; readers parse the destination directly.

rust/src/metadata.rs[96-128]
rust/src/metadata.rs[265-269]
rust/src/lib.rs[333-342]
rust/src/lib.rs[1219-1235]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Concurrent writers in one process share the PID-named temporary file, allowing writes to continue after another thread renames it into place.
## Fix Focus Areas
- rust/src/metadata.rs[265-269]
## Recommended Fix
Give each invocation its own exclusively created sibling temporary file, and rename or remove only that invocation's file. Add a multiple-writer regression test.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


2. Shared-cache writes can erase user files ✗ Dismissed
Description
write_metadata creates a predictable PID-named temporary path with fs::write, which follows a
symlink already placed at that path and truncates its target. In a cache directory writable by
another local user, that user can plant the link before a victim process writes and redirect the
write to any file the victim can modify; the subsequent rename does not undo the damage.


Remediation recommended
3. Shared users lose access to metadata ✗ Dismissed
Description
write_metadata now replaces the existing metadata file with a newly created file owned by the
current writer and governed by that writer's umask, rather than retaining the existing file's owner
and mode. If two users can write the cache directory and each uses a restrictive umask, one user's
rename can make the other's next get_metadata open fail and fall back to an empty cache.

4. Formatter check fails on new test ✗ Dismissed
Description
The final assert! in concurrent_reader_never_sees_partially_written_metadata is wrapped across
four lines, although it fits on one line at about 81 columns under the default 100-column limit.
rustfmt would collapse it, so the repository formatter check fails on this changed file until the
assertion is reformatted.

5. The concurrency test may skip all reads ✓ Resolved

Resolving commit: 2334c7b

Resolution reason
Added an assertion after writer.join() that reads > 0, so the test fails rather than silently
passing when the writer finishes before the reader performs any read.
Description
concurrent_reader_never_sees_partially_written_metadata checks done before its first read
without synchronizing the reader with the writer. If the writer finishes its iterations before the
reader reaches that check, the loop runs zero times and the test passes without exercising its
metadata assertion.

View medium (1)
6. Read-only cache folders block updates ✗ Dismissed
Description
write_metadata now requires permission to create a sibling file and rename it in the cache
directory, even when the existing metadata file is writable. With a writable metadata file inside a
non-writable cache directory, the previous in-place update succeeded but the new temporary-file
creation fails, logs a warning, and leaves the metadata stale.

Grey Divider

Qodo Logo

Comment thread rust/tests/cache_unit_tests.rs Resolved
Comment thread rust/src/metadata.rs Resolved
Comment thread rust/src/metadata.rs Resolved
Comment thread rust/src/metadata.rs Resolved
Comment thread rust/src/metadata.rs Resolved
Comment thread rust/tests/cache_unit_tests.rs Resolved
@titusfortner

Copy link
Copy Markdown
Member

@UweKubosch Thanks for this fix! I pushed 2334c7b so the new test runs on Windows too: there std::fs::rename falls back to a POSIX-semantics replace, so a reader holding the file open doesn't block it. The test also fails now if the reader never gets a read in.

@titusfortner titusfortner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should be good to merge once the tests finish.

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 2334c7b

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

Labels

B-manager Selenium Manager C-rust Rust code is mostly Selenium Manager

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants