Skip to content

Rust 2024 edition, no static mut, rustfmt and clippy in CI; unsafe removed where it costs nothing - #7

Merged
danog merged 9 commits into
masterfrom
edition-2024
Nov 25, 2026
Merged

danog merged 9 commits into
masterfrom
edition-2024

Conversation

@danog

@danog danog commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Moves the workspace to Rust edition 2024, removes every unsafe that can go without a performance cost or a new dependency, removes every static mut, and adopts rustfmt and clippy (checked in CI). crates/core goes from 68 unsafe {} blocks to 53 and src/ from 71 to 52; crates/crypt had none.

Commits:

  • c19680a edition 2024, unsafe removed
  • a2a9bed clippy fixes and workspace lints
  • 4eadf17 no static mut (ClassEntry, EngineCell)
  • a48a367 cargo fmt, formatting only (listed in .git-blame-ignore-revs)
  • bf5617a CI lint job
  • 591f7de Lease holds an Option (measured below)
  • 46d9525 builds with PHP before 8.6 again (clippy's fixes had followed 8.6's headers)
  • 27e9630 compressors may be a list of strings (PHPC-2736, upstream's new tests failed without it)
  • bed6bd4 Version 0.2.3

Edition 2024

  • edition = "2024" in the three Cargo.toml files (CI's stable and pinned nightly both support it).
  • unsafe extern blocks, #[unsafe(no_mangle)]; gen is reserved, so the module is r#gen (and tools/gen/gen_api.py emits that) and the slot counters in src/driver/aio.rs are generation.
  • src/lib.rs allows unsafe_op_in_unsafe_fn: the binding layer's ~900 unsafe fn are engine access throughout, and cargo fix --edition would have wrapped ~840 bodies in { unsafe { … }}.
  • Drop order: the edition lints flagged src/driver/mod.rs:66, crates/core/src/kms_tls.rs:39 and crates/core/src/net.rs:343; all three are moved-from Result temporaries, so nothing changes. The one if let … else whose order does change (src/driver/manager.rs, the Client dropped before the throw) is now a match that keeps the old order.

unsafe removed

Where Change
net.rs reply buffer read() went into the Vec's uninitialised spare capacity as a &mut [u8] (the Read docs call that potential UB). The buffer is now zero-filled once and only grows (filled length tracked separately), so each byte is zeroed once per connection.
os.rs check_closed TcpStream::peek instead of a raw recv(MSG_PEEK) (same syscall), Unix and Windows.
os.rs socket addresses Built as std's socket_addr_to_c: struct literals, with one ..mem::zeroed() for the platform-only fields on Unix and none on Windows; no casts through sockaddr_storage.
json_parse.rs The tree's member lists are index ranges into two Vecs instead of slices of a hand-made arena (from_raw_parts, unsafe fn recycle); the per-thread buffer reuse is kept. See the note below.
scram.rs, log.rs, fmt.rs wipe_string wipes the taken bytes; the log handler is a OnceLock<Handler> (no fn-pointer transmute); a test helper's from_utf8_unchecked is gone.
clock_gettime_nsec_np, zend_fiber_switch_blocked Declared safe fn (no arguments or pointers).
os.rs socket addresses (Linux, Android, Apple, BSDs) Written field by field: these systems' sockaddr_in/sockaddr_in6 have no other fields, so no zeroed() is needed there (other Unix systems keep it).
client.rs Lease Option<Box<Client>> instead of ManuallyDrop + ManuallyDrop::take.

bson::ce_mut() was a safe fn returning &'static mut to the same static mut that ce() borrows (unsound); it is gone (see below).

No static mut

  • The 21 class-entry pointers and the BSON class table are ClassEntry (an AtomicPtr, set at MINIT; a relaxed load compiles to the same plain load as a static mut read).
  • The handler tables, the module entry and the ZTS globals id, which PHP keeps a pointer to, are EngineCell<T> (an UnsafeCell): one unsafe impl Sync and one zeroed() for the empty handler table, instead of one per static.

Code style

  • cargo fmt with rustfmt's defaults; the generated modules (src/gen, crates/crypt/src/unicode/*_fold_map.rs) are #[rustfmt::skip], so their generators' output passes the check.
  • clippy is clean with -D warnings. clippy --fix collapsed 133 nested if lets into let chains (2024). Lints that would change a deliberate choice are allowed at the site with a reason (Iter::next is bson_iter_next, not an Iterator; the boxed idle clients; Result<_, ()> meaning "a PHP exception was thrown"; NaN-aware negated comparisons; two KMS credential enums); too_many_arguments and type_complexity are allowed workspace-wide in Cargo.toml.
  • New lint job in tests.yml: cargo fmt --check and clippy on the whole workspace on Linux (with PHP and libclang, as the build), clippy on mongo-core/mongo-crypt on macOS and Windows. The README says how to run both.

The JSON parser and ldp

The first version of the index-range tree made fromJSON 5–22% slower. The cause was not the index lookups: in P the read position i ended up next to s.len, LLVM merged their loads into one ldp, and that 16-byte load cannot be forwarded from the 8-byte store of i still in flight, so it waited for it on every escape character (in P::string) and every token (in P::value). Fixed two ways:

  • P::string keeps the position in a local and writes it back on return (independent of layout);
  • P is #[repr(C)] with i after the tree, with a compile-time assertion that it is not adjacent to s.

Performance

tools/bench/fromjson.php plus small documents, extension builds, macOS arm64, median of 8 alternating rounds:

Case master this branch
1,000 docs, relaxed 179.9 µs 181.9 µs +1.1% (ranges overlap)
1,000 docs, canonical 283.2 µs 285.0 µs +0.7% (ranges overlap)
long string, frequent escapes 88.5 µs 85.2 µs −3.7%
small flat doc 110 ns 105 ns −4.7%
small nested doc 419 ns 408 ns −2.7%
50-element array doc 1,617 ns 1,582 ns −2.1%

The read-buffer change was timed on loopback against a fake peer (replies of 200 B to 2 MB): within noise.

Against a MongoDB 8.0 server (Docker on macOS, so wall times are ~9× native and noisy; CPU per operation, median of 8 alternating rounds, master → branch): ping 19.3 → 19.3 µs, findOne 20.1 → 20.7 µs, insertOne 20.2 → 19.8 µs, find of 100 documents 57.0 → 58.3 µs, of 1,000 in batches of 100 646.8 → 616.9 µs, findOne of a 1 MB document 567.8 → 556.2 µs: all within noise (the master and branch ranges overlap in every case).

ClassEntry/EngineCell: tools/bench/bson.php (48 cases) geometric mean +0.9% against the commit before; the toPHP cases measured again (8 rounds) at −1.3% to +2.3%, ranges overlapping.

Lease: a checkout, k accesses and the checkin (20M iterations, best of 7): k=1 3.43–3.46 ns against 3.68–3.76 ns with ManuallyDrop, k=10 12.10–12.40 ns against 12.22–12.48 ns. The release extension has 28 more panic paths (+964 bytes): null checks the optimiser kept, never taken.

Tests

  • cargo test -p mongo-core -p mongo-crypt: 94 pass (the live tests need MONGO_CORE_TEST_SERVER, not set here); mongo-core/mongo-crypt also check clean for x86_64-unknown-linux-gnu and x86_64-pc-windows-msvc.
  • PHPT suite without a server: identical to master (1706 pass, 550 skip, 10 xfail, the same 4 manager-ctor-* / auto-encryption failures), checked again after the static mut change.
  • clippy -D warnings clean on macOS, and for mongo-core/mongo-crypt on the Linux and Windows targets; the CI lint job itself runs here for the first time.
  • live::client_select_and_command (timing-based: a 200 ms connect timeout, then the 5 s cooldown; no server) failed twice locally during parallel builds and passed in every rerun.
  • PHPT suite against a MongoDB 8.0 server: the same as master apart from the four compressors tests, which pass now (and clientEncryption-getKeys-002, which assumes an empty key vault and failed once while other tests wrote to it in parallel; it passes alone with both builds).
  • Not built locally: the extension for Windows or ZTS PHP (CI covers them); Linux with PHP 8.4 was checked in Docker.

Left as is

  • The Unix-socket-as-TcpStream in net.rs (a separate variant would need its own raw recv: UnixStream::peek is unstable).
  • Only with a dependency (rustix/socket2, which wrap the same libc calls): socket creation, poll/WSAPoll, gethostname, the Linux clock.
  • Required: engine globals and the backend pointer in aio.rs, pthread_atfork, the macOS clocks matching PHP's hrtime, the Windows-only calls, fork in tests, and the Zend binding layer in src/.

Edition 2024 for the three crates: unsafe extern blocks, #[unsafe(no_mangle)],
`gen` (now reserved) as r#gen / `generation`. The binding layer allows
unsafe_op_in_unsafe_fn (its unsafe fns are engine access throughout). The one
if-let/else whose drop order changes is a match.

unsafe removed (crates/core: 68 unsafe blocks -> 53):
- net: the reply buffer is zero-filled once and only grows, instead of
  read() into uninitialized memory
- os: check_closed peeks with TcpStream::peek; socket addresses are built as
  std builds them (Unix: one zeroed() for the platform fields, Windows: none)
- json_parse: the tree's member lists are index ranges (no arena, no
  from_raw_parts); P::string keeps the position in a local, and P's layout
  keeps `i` apart from `s` (a merged ldp of both waits for the store of `i`)
- scram wipe_string, log handler (OnceLock), a test's from_utf8_unchecked
- clock_gettime_nsec_np and zend_fiber_switch_blocked declared safe fn

bson::ce_mut() returned &'static mut from a safe fn: now an unsafe fn (MINIT).
@claude

claude Bot commented Nov 25, 2026

Copy link
Copy Markdown

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

The machine-applicable fixes (`clippy --fix`: 133 nested ifs collapsed into let
chains, is_multiple_of, as_chunks, ...) and by hand: from_hash -> init_from_hash
(phongo's name), the wire tests module last, a test float literal, doc list
indentation. Allowed where clippy's suggestion would change a deliberate choice,
with the reason at the site: Iter::next (bson_iter_next, not an Iterator), the
boxed idle clients, Result<_, ()> (Err: a PHP exception was thrown), NaN-aware
negated comparisons, two KMS credential enums. Workspace-wide: too_many_arguments
(ports keep the C parameter lists) and type_complexity.

os: socket addresses are written field by field on Linux, Android, Apple and
the BSDs (no unsafe left there); other Unix systems keep the zeroed fallback.

Formatting follows in a separate commit (cargo fmt).
The 21 class-entry pointers and the BSON class table become ClassEntry (an
AtomicPtr: a relaxed load is the plain load a static mut read was), set at
MINIT; bson::ce_mut() is gone (ce() returns the table). The handler tables, the
module entry and the ZTS globals id, which PHP is given a pointer to, become
EngineCell<T> (an UnsafeCell): one Sync impl and one zeroed() for the empty
handler table instead of one per static.

BSON benchmark (tools/bench/bson.php, 48 cases): geometric mean +0.9%, the
toPHP cases measured again at -1.3%..+2.3% (noise).
Formatting only: src/gen (tools/gen/gen_api.py) and the Unicode fold maps
(tools/gen/gen_unicode_fold.py) keep their generators' output. Listed in
.git-blame-ignore-revs.
A lint job: cargo fmt --check and clippy on the whole workspace on Linux (with
PHP and libclang, as the extension's build), clippy on mongo-core and
mongo-crypt on macOS and Windows (their Apple-only and Windows-only code). The
README says how to run both; .git-blame-ignore-revs lists the formatting
commit.
Measured (a checkout, k accesses and the checkin, 20M iterations, best of 7):
k=1 3.43-3.46 ns against 3.68-3.76 ns with ManuallyDrop, k=10 12.10-12.40 ns
against 12.22-12.48 ns. The release extension has 28 more panic paths (+964
bytes of code): null checks the optimiser could not remove, never taken.
@danog danog changed the title Rust 2024 edition; unsafe removed where it costs nothing Rust 2024 edition, no static mut, rustfmt and clippy in CI; unsafe removed where it costs nothing Nov 25, 2026
clippy --fix had followed PHP 8.6's headers: zend_register_internal_class_with_flags
and zend_register_internal_interface take a const zend_class_entry * from 8.6
on (now &raw mut, valid for both), and enum_backing_type's cast is kept (its
type differs between versions). zstr: .cast::<u8>() instead of `as *const u8`
(c_char is u8 on arm64 Linux, so the cast is linted there).

Checked: rustfmt and clippy -D warnings with Rust 1.100 and PHP 8.4 on x86_64
and aarch64 Linux, and for mongo-core/mongo-crypt on the Apple and Windows
targets.
Port of phongo_manager_prep_compressors (mongo-php-driver c6309a00e): a list
of strings is joined with commas; a non-list array, a non-string element, a
comma inside an element and a NUL byte throw InvalidArgumentException with
ext-mongodb's messages, as does any other type ("Expected string or array of
strings ..."). The caller's array is not changed.

The upstream tests of that commit are copied into tests/phpt (listed in
tests/UPSTREAM.md); they pass, compression-001 against a MongoDB 8.0 server.
@danog
danog merged commit 5bbe6aa into master Nov 25, 2026
73 checks passed
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