Repository navigation
Rust 2024 edition, no static mut, rustfmt and clippy in CI; unsafe removed where it costs nothing - #7
Merged
Merged
Conversation
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).
Code reviewNo 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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Moves the workspace to Rust edition 2024, removes every
unsafethat can go without a performance cost or a new dependency, removes everystatic mut, and adopts rustfmt and clippy (checked in CI).crates/coregoes from 68unsafe {}blocks to 53 andsrc/from 71 to 52;crates/crypthad none.Commits:
c19680aedition 2024,unsaferemoveda2a9bedclippy fixes and workspace lints4eadf17nostatic mut(ClassEntry,EngineCell)a48a367cargo fmt, formatting only (listed in.git-blame-ignore-revs)bf5617aCI lint job591f7deLeaseholds anOption(measured below)46d9525builds with PHP before 8.6 again (clippy's fixes had followed 8.6's headers)27e9630compressorsmay be a list of strings (PHPC-2736, upstream's new tests failed without it)bed6bd4Version 0.2.3Edition 2024
edition = "2024"in the threeCargo.tomlfiles (CI's stable and pinned nightly both support it).unsafe externblocks,#[unsafe(no_mangle)];genis reserved, so the module isr#gen(andtools/gen/gen_api.pyemits that) and the slot counters insrc/driver/aio.rsaregeneration.src/lib.rsallowsunsafe_op_in_unsafe_fn: the binding layer's ~900unsafe fnare engine access throughout, andcargo fix --editionwould have wrapped ~840 bodies in{ unsafe { … }}.src/driver/mod.rs:66,crates/core/src/kms_tls.rs:39andcrates/core/src/net.rs:343; all three are moved-fromResulttemporaries, so nothing changes. The oneif let … elsewhose order does change (src/driver/manager.rs, theClientdropped before thethrow) is now amatchthat keeps the old order.unsaferemovednet.rsreply bufferread()went into the Vec's uninitialised spare capacity as a&mut [u8](theReaddocs 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.rscheck_closedTcpStream::peekinstead of a rawrecv(MSG_PEEK)(same syscall), Unix and Windows.os.rssocket addressessocket_addr_to_c: struct literals, with one..mem::zeroed()for the platform-only fields on Unix and none on Windows; no casts throughsockaddr_storage.json_parse.rsfrom_raw_parts,unsafe fn recycle); the per-thread buffer reuse is kept. See the note below.scram.rs,log.rs,fmt.rswipe_stringwipes the taken bytes; the log handler is aOnceLock<Handler>(no fn-pointertransmute); a test helper'sfrom_utf8_uncheckedis gone.clock_gettime_nsec_np,zend_fiber_switch_blockedsafe fn(no arguments or pointers).os.rssocket addresses (Linux, Android, Apple, BSDs)sockaddr_in/sockaddr_in6have no other fields, so nozeroed()is needed there (other Unix systems keep it).client.rsLeaseOption<Box<Client>>instead ofManuallyDrop+ManuallyDrop::take.bson::ce_mut()was a safe fn returning&'static mutto the samestatic mutthatce()borrows (unsound); it is gone (see below).No
static mutClassEntry(anAtomicPtr, set at MINIT; a relaxed load compiles to the same plain load as astatic mutread).EngineCell<T>(anUnsafeCell): oneunsafe impl Syncand onezeroed()for the empty handler table, instead of one per static.Code style
cargo fmtwith 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.-D warnings.clippy --fixcollapsed 133 nestedif lets into let chains (2024). Lints that would change a deliberate choice are allowed at the site with a reason (Iter::nextisbson_iter_next, not anIterator; the boxed idle clients;Result<_, ()>meaning "a PHP exception was thrown"; NaN-aware negated comparisons; two KMS credential enums);too_many_argumentsandtype_complexityare allowed workspace-wide inCargo.toml.lintjob intests.yml:cargo fmt --checkand clippy on the whole workspace on Linux (with PHP and libclang, as the build), clippy onmongo-core/mongo-crypton macOS and Windows. The README says how to run both.The JSON parser and
ldpThe first version of the index-range tree made
fromJSON5–22% slower. The cause was not the index lookups: inPthe read positioniended up next tos.len, LLVM merged their loads into oneldp, and that 16-byte load cannot be forwarded from the 8-byte store ofistill in flight, so it waited for it on every escape character (inP::string) and every token (inP::value). Fixed two ways:P::stringkeeps the position in a local and writes it back on return (independent of layout);Pis#[repr(C)]withiafter the tree, with a compile-time assertion that it is not adjacent tos.Performance
tools/bench/fromjson.phpplus small documents, extension builds, macOS arm64, median of 8 alternating rounds: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):
ping19.3 → 19.3 µs,findOne20.1 → 20.7 µs,insertOne20.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; thetoPHPcases 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 withManuallyDrop, 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 (thelivetests needMONGO_CORE_TEST_SERVER, not set here);mongo-core/mongo-cryptalso check clean forx86_64-unknown-linux-gnuandx86_64-pc-windows-msvc.manager-ctor-*/ auto-encryption failures), checked again after thestatic mutchange.-D warningsclean on macOS, and formongo-core/mongo-crypton 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.compressorstests, which pass now (andclientEncryption-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).Left as is
TcpStreaminnet.rs(a separate variant would need its own rawrecv:UnixStream::peekis unstable).rustix/socket2, which wrap the same libc calls): socket creation,poll/WSAPoll,gethostname, the Linux clock.aio.rs,pthread_atfork, the macOS clocks matching PHP'shrtime, the Windows-only calls,forkin tests, and the Zend binding layer insrc/.