Skip to content

Rebuild native gem extensions from the source gem, precompiled gems included - #2098

Merged
Mikola Lysenko (mikolalysenko) merged 13 commits into
mainfrom
fix/gem-native-rebuild-from-archive
Nov 16, 2026
Merged

Mikola Lysenko (mikolalysenko) merged 13 commits into
mainfrom
fix/gem-native-rebuild-from-archive

Conversation

@mikolalysenko

@mikolalysenko Mikola Lysenko (mikolalysenko) commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

LLM Description written by Claude Code:claude-fable-5-2

Summary

Agent-mode patches to a native-extension gem now take effect by a real
rebuild, on source-built and on precompiled platform gems. Before this,
apply either refused such a patch or reported it applied while Ruby kept
loading the old binary.

Measured on nokogiri 1.18.3 (macOS arm64, Ruby 3.4.10), with a record that
only adds patches/libxml2/0100-….patch (the shape of about 500 live nokogiri
patches) and a record that changes ext/nokogiri/xml_node.c plus a .rb file:

Install Record 5.1.0 This branch
precompiled nokogiri-1.18.3-arm64-darwin adds a libxml2 patch file "applied" in 0.03 s, binary unchanged, apply --check in sync, vex not_affected rebuilt in 34 s; Nokogiri::VERSION_INFO lists 7 libxml2 patches instead of 6
precompiled ext/*.c + .rb refused (native_extensions_unsupported) applied in 35 s, loads and parses
source-built nokogiri-1.18.3 adds a libxml2 patch file, --offline "applied", binary unchanged, vex not_affected rebuilt in 34 s from the cached source gem
either rollback n/a original binary, gem tree and extension dir byte for byte
precompiled patch applied and attested, then the patched binary is overwritten with the original to simulate something reverting the patch (gem pristine, a reinstall) n/a the revert is noticed: apply --check reports out of sync and vex stops attesting until apply runs again
precompiled --offline, no source gem in cache/ n/a refused, nothing written, message says what is needed
pure-Ruby gem (addressable 2.3.3, live patch) 0.03 s unchanged: 0.8 s, no build

Root cause

Three things, all in patch/gem_ext.rs:

  • Build inputs were under-classified. Only C-family file names and files
    under the declared build-script dir counted. nokogiri's extconf.rb also
    builds its vendored libxml2 from patches/libxml2/*.patch,
    patches/libxslt/*.patch, ports/** and dependencies.yml. A record
    touching only those was written as plain files, with no rebuild, and
    apply --check and vex attested it.
  • A precompiled platform gem was refused for ext/** changes. That is the
    default nokogiri install on Linux and macOS since 1.11.
  • An in-place rebuild cannot work for nokogiri. Its extconf.rb deletes
    ports/ (the vendored tarballs) after a successful install, so
    Gem::Ext::Builder#build_extensions on the installed copy has to
    re-download them, which failed here with libxml2-2.13.6.tar.xz (404 Not Found). The complete inputs exist only in the source .gem.

The change

  • Classification. A gem is native when its installed gemspec declares
    extensions, or its platform is not ruby. In a native gem a patched file
    is a build input unless it clearly is not one: a file under a require path,
    bin/, exe/, tests, docs, type signatures, and Ruby source outside
    ext/** and outside a declared build script's dir (build scripts by name,
    and rake files of a rake-built extension, stay inputs). Non-Ruby files such
    as patches/**, ports/**, dependencies.yml and Cargo.* are
    inputs. A pure-Ruby gem takes the old path unchanged.
  • Rebuild from the source gem. The ruby-platform <name>-<version>.gem
    is taken from <gem home>/cache/, else downloaded. It is unpacked by
    RubyGems into a stage home under <gem home>/.socket-patch-build/, the
    record is applied to the staged tree in strict mode (every beforeHash is
    checked against the pristine source gem), build-time gems the install lacks
    (a precompiled nokogiri has no mini_portile2) are installed into the stage
    home only, and RubyGems' own extension builder runs there.
  • Source-built copy: sources are written in place and the staged extension
    dir and its lib/ copies replace the installed ones through the existing
    backup and marker path.
  • Precompiled copy: each staged binary is grafted over the prebuilt one
    Ruby loads, <require path>/<dir>/<ruby minor>/<file> (nokogiri:
    lib/nokogiri/3.4/nokogiri.bundle), or a unique file of the same name under
    the require path; otherwise the record is refused with nothing written. The
    replaced binaries are backed up with their modes. The marker is schema 2
    with grafted: true; schema 1 is still read.
  • Downloads (new patch/gem_source.rs) go only to the default registry
    (rubygems.org, or SOCKET_RUBYGEMS_URL) and are used only when their sha256
    is the one that registry's compact index records. Nothing in the lock drives
    a download: the existing guard test
    lock_pinned_locations_never_drive_a_download forbids it, because a lock
    entry may be Socket-hosted. The lock is read only to withhold a download for
    a gem it resolves from another source.
  • The source gem must be the installed gem's own. Before anything is
    patched or built, every file the unpacked source gem shares with the
    installed copy must be byte-identical (a file the record changes may hold
    its patched content). No overlap or any mismatch means it is not this gem:
    a precompiled copy is refused, a built one falls back to its own tree. This
    is what stops a same-named gem from the registry being built over a private
    one, including for a record that only adds files.
  • Fallbacks. For a gem RubyGems built, any failure of the staged path
    before the installed copy is touched falls back to the in-place rebuild, as
    before this change; so does a gem whose build leaves a library in its own
    tree and loads it from there. With no source gem, a precompiled copy is
    refused with what it needs. A -java gem is still refused for build
    inputs and is never attested.
  • Attestation of a grafted copy. It is attested as soon as its marker
    holds: the record's sources hash as recorded and every replaced binary
    still hashes as built. That is the standard a normal gem install meets: a
    native extension is built for the Ruby that installs it, and nothing is
    promised to another Ruby sharing the gem home. When apply runs under a
    Ruby minor the marker does not list, it grafts that minor's binary too.
  • The stage dir is named in one place and is never followed, emptied or
    deleted through a link: a gem tree can come from the repository, so nothing
    in it may steer a delete.
  • --dry-run, apply --check and vex still start no Ruby.
    --no-gem-native-rebuild keeps its meaning, now also for the newly
    classified inputs.
  • CLI_CONTRACT.md and docs/ecosystems.md describe the new behaviour.

What a reviewer should weigh

  • apply can now download a source gem and build-time gems from rubygems.org
    and compile for 35 to 60 seconds. On a precompiled install that happens on
    every apply after a fresh bundle install, and needs a C toolchain.
  • A gem from a private source or a mirror is never downloaded. A precompiled
    copy of one is refused unless its source gem is in cache/.
  • A precompiled gem ships one binary per Ruby minor and only the building
    Ruby's is replaced. Another Ruby minor sharing the same gem home keeps
    loading its stock binary until apply runs under it.
  • A compile error on a gem RubyGems built is now tried twice (staged, then in
    place) before it fails.
  • The diff is large (+8,400 lines, most of it in gem_ext.rs and its e2e
    suite), and gem_ext.rs was not split here.

Code review

/code-review high raised ten findings; all ten were confirmed and fixed
before this PR was opened: a planted link at the stage dir steering a delete;
a build that leaves its library in the gem tree; a download for a gem the
lock resolves elsewhere; a grafted marker attesting while another Ruby minor
loads a prebuilt binary (settled as described under attestation above,
by the maintainer's decision); missing fallbacks to the in-place rebuild; an
over-broad build-input classification; the ruby record applied on top of a
platform's own record; a stage swept without a lock while a build is live;
duplicated helpers; and repeated I/O per gem copy.

Left as is, on purpose: back_up_original and back_up_prebuilt stay
separate (they share only the info writer), gem_refresh keeps its own
stage and swap code, and a GemSource is still built once per gem copy
that reaches a rebuild. Lock discovery was not widened to a lock outside the
working directory; the own-source proof above closes that case instead.

Two findings from the review bot (plain-http downloads on the new path, and
a stage path that cannot be probed being read as "not a link") are NOT in
this PR: it merged at c6c9b80 before their fixes were pushed. They are in a
follow-up PR.

Testing

  • Unit tests for classification (nokogiri source and precompiled specs, a
    pure-Ruby gem, a -java gem), graft planning, markers, staged installs,
    stage sweeping, the lock-origin rule and release picking.
  • e2e_gem_native_ext_build: 30 tests, hermetic ones with a stand-in Ruby
    and #[ignore] capstones on the real toolchain. Two new capstones build a
    nokogiri-shaped fixture whose extconf.rb deletes ports/ and needs a
    helper gem: source-built (in-place fails, cached-archive rebuild works) and
    precompiled in the lib/<name>/<minor>/ layout fed from a mock registry.
    They assert on what Ruby loads, on apply --check, on vex, and on a
    byte-identical tree after rollback.
  • The table above, run by hand on real nokogiri 1.18.3 installs.

Not verified: Linux and Windows builds (CI has to say), Rubies other than
3.4.10 beyond a smoke test on 2.6, JRuby, a home shared by two real Ruby
minors (covered with a stand-in Ruby only), and precompiled gems other than
nokogiri (sqlite3, grpc, ffi are covered only by the fixture's layout).

🤖 Generated with Claude Code

…s included

An agent-mode gem patch that changes a native-extension build input now
takes effect by a build of the gem's source archive:

* In a native gem (its gemspec declares extensions, or its platform is
  not ruby) every patched file is a build input unless it clearly is
  not one, so nokogiri's patches/**, ports/** and dependencies.yml are
  inputs.
* The extension is built from the ruby-platform source gem (the gem
  home's cache/, else a sha256-verified download from the gem's source)
  in a stage inside the gem home, with the record laid over it. Gems the
  build needs and the install lacks are staged beside it.
* A gem RubyGems built gets the staged extension dir; a precompiled
  platform gem gets each prebuilt binary Ruby loads replaced, with the
  originals backed up. The marker, apply --check, vex and rollback treat
  both alike.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…s in the build backup

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…chive rebuilds and grafts

A record that changes a build input the installed copy no longer holds
(a build deletes nokogiri's ports/) is laid over the source gem, where
its beforeHash is checked, and the file is added to the copy; rollback
removes it. Without the source gem such a record is refused from files
alone.

The e2e suite gains a stand-in Ruby that speaks the stage modes, and two
capstones that build a nokogiri-shaped fixture gem for real: one built
from source whose build removes an input, one precompiled platform copy
in the rake-compiler layout, fed from a mock gem source.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… the lock names

The lock's remote: and CHECKSUMS no longer choose a URL or an expected
hash (the lock_pinned_locations_never_drive_a_download invariant): the
source gem and the gems its build lacks come from the gem home's cache,
else from the default registry, verified against its compact index. The
lock is read only to withhold the download for a gem it resolves from
another source.

A precompiled copy's Ruby is matched by the ABI of the home's extension
dirs, and a build input a native copy does not hold no longer decides
which release variant the copy matches.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ugh Ecosystem

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… only when dead

A link planted at <home>/.socket-patch-build, or at the stage dir inside
it, steered the stale-stage sweep (the first step of every native apply,
gem rollback and hosted refresh) into deleting the <gem>-<version> dir
behind it. The stage is now named through one guarded function wherever
it is opened, swept or removed.

Where a directory cannot be locked, a stage is swept only when its
heartbeat is older than any step of a build lasts.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ce; attest shared homes truthfully

Review hardening of the rebuild from the source gem:

* Before anything of an archive is built, every file it shares with the
  installed copy must be byte-identical (a record file may hold its
  patched content). A gem of the same name from elsewhere is refused
  whatever lock governs the home. A name the lock resolves from another
  source is withheld from download at any version.
* A gem RubyGems built falls back to the in-place rebuild on every
  failure before the installed copy is written, and a failed fallback
  names both failures. A build that leaves what Ruby loads in the gem's
  own tree takes the in-place path.
* A grafted copy is attested only when no prebuilt binary a Ruby could
  load from the gem home is left unpatched: the home is laid out for the
  grafted Ruby, or every per-minor binary is grafted. apply under
  another Ruby grafts its binary into the same marker and backup.
* Ruby source and type signatures outside ext/ and a build script's dir
  are no build inputs.
* A platform gem's copy takes only its own platform's record when the
  manifest has one.
* gem_source parses the lock once, builds its client on the first
  download and checks the cache by metadata; the registry test, the
  extension-dir confinement rule, the Ruby probe and the staged build
  are each one function.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…me shared by two Rubies

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ome attestation rule

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…source gem in reach

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@cursor

cursor Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

PR Summary

High Risk
Changes compile-and-replace behavior for installed gems (including network fetches verified only via compact index), with complex fallback and multi-Ruby attestation rules where a wrong step could leave Ruby loading an unpatched binary.

Overview
Agent-mode apply now rebuilds native Ruby gem extensions from the ruby-platform source .gem (gem home cache/ or a verified rubygems.org / SOCKET_RUBYGEMS_URL download), stages the build under .socket-patch-build/, and installs only into the existing copy—including precompiled platform gems, which get the owning Ruby’s prebuilt binary replaced while others stay untouched until each Ruby has run apply.

Behavior changes: build-input detection is expanded (e.g. patches/**, ports/**, build files outside ext/), with fallbacks to the old in-place rebuild when staging cannot work; platform gem installs pick the manifest record for their platform instead of stacking a ruby-platform record; variant matching ignores patch files the installed tree cannot hold; rollback drops apply-added build-only files; offline flows through gem native rebuild and refresh paths.

Docs and tests: CLI_CONTRACT.md and docs/ecosystems.md document the full contract (errors, attestation for multi-Ruby prebuilt layouts, JRuby refusal); a new gem_source module and a large e2e_gem_native_ext_build suite cover staged builds, registry checksum checks, and capstone nokogiri-shaped fixtures.

Reviewed by Cursor Bugbot for commit 4ad552f. Configure here.

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 4ad552f. Configure here.

A precompiled gem ships one binary per Ruby minor, and a rebuild from the
source gem replaces the one of the Ruby that ran `apply`. Until now such a
copy was attested only when its gem home was laid out for that one Ruby,
or every binary the gem ships had been replaced; otherwise `apply` warned
`native_extension_not_rebuilt` and `vex` / `apply --check` withheld the
patch.

That held a patched gem to more than a normal install: `gem install`
builds an extension for the Ruby that runs it and promises nothing to
another Ruby pointed at the same gem home. A grafted copy is now attested
once its marker holds: the sources hash as recorded and every replaced
binary still hashes as built. The binaries shipped for other Rubies are
not held against it, and the warning about them is gone.

Kept: `apply` under a Ruby whose binary is not in the marker builds for
that Ruby and replaces its binary too, in the same marker and backup, and
rollback restores every one. `apply` under a Ruby already built for does
nothing. Telling the two apart takes one question to the host Ruby; none
is started when every shipped binary is replaced, when the gem home is
laid out for a Ruby already built for, or on a dry run.

Removed: `ungrafted_binaries`, `ungrafted_after`, `other_rubies_warning`
and the gate in `marker_holds`. `built_state` now says from files what is
left for `apply` to do. `home_minor` and `prebuilt_siblings` remain only
to decide whether that question is needed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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.

2 participants