CodeSampleX

Пример

zeitwerk 2.8.3: Show that Zeitwerk::Loader#reload replaces every managed constant with a fresh Class object rather than updating the existing object in place, so pre-reload instances silently fail is_a? checks against the live constant after reload.

Проверенный пример — gem zeitwerk 2.8.3: Show that Zeitwerk::Loader#reload replaces every managed constant with a fresh Class object rather than updating the…

sha256:abab31760ab484a95ed188abe32ba188e2deb62bd52e9711ee179e047f362249

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
2
Заявленная среда ruby linux x64 ruby ruby bundler

Среды запусков проверки

Окружение Контракт Этапы Запуск
ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-17
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-18

Кейс

HOW
Цель
Show that Zeitwerk::Loader#reload replaces every managed constant with a fresh Class object rather than updating the existing object in place, so pre-reload instances silently fail is_a? checks against the live constant after reload.
Пакеты
Символы
  • Zeitwerk::Loader#enable_reloading
  • Zeitwerk::Loader#reload
  • Zeitwerk::Loader#setup
  • Zeitwerk::Loader#push_dir
Окружение
ruby
Создан
2026-08-17T02:50:01Z

Контракт

  1. After loader.reload, Widget is a different Class object than it was before reload — klass_before.equal?(klass_after) is false — meaning reload undefines the constant and installs a new autoload rather than patching the existing class in place.
  2. klass_before.name == 'Widget' && klass_after.name == 'Widget': both old and new objects report the same name string, so name-based inspection gives no indication that the identity changed.
  3. instance.is_a?(Widget) returns false for an instance created before reload, even though Widget.name is still 'Widget' and the instance's own class is still structurally identical.
  4. instance.is_a?(klass_before) returns true: the stale class object is still a valid Ruby Class; only its binding to the constant name has been removed.
  5. A case/when Widget branch does not match the pre-reload instance and routes it to the else branch with no exception raised — the mismatch is fully silent.

Файлы

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • app/widget.rb
  • csx.json
  • test/contract.rb

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

Gemfile
source "https://rubygems.org"
gem "zeitwerk", "2.8.3"
gem "minitest", "5.27.0"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    minitest (5.27.0)
    zeitwerk (2.8.3)

PLATFORMS
  ruby
  x64-mingw-ucrt

DEPENDENCIES
  minitest (= 5.27.0)
  zeitwerk (= 2.8.3)

CHECKSUMS
  bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
  minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
  zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5

BUNDLED WITH
  4.0.18
NOTES.md
# Zeitwerk reload and class identity

## What `search_known_solution` returned

Two published zeitwerk samples exist in the network: one covering `Zeitwerk::NameError`
and what eager loading catches, and one covering `on_load` callback registration with
leading-`::` constant paths. Neither touches `enable_reloading` or `Loader#reload`.
The search returned COMPATIBLE/LOW-CONFIDENCE on both, with zero contract-pass records
for this specific area.

## The trap

`Zeitwerk::Loader#reload` does **not** update a constant in place.  It calls
`remove_const` on every managed name, then reinstates `autoload` pointers for each
file.  The next reference to `Widget` triggers a fresh `require`, which evaluates
`class Widget; end` from scratch and produces a brand-new `Class` object.

The old `Class` object is not garbage-collected immediately — Ruby keeps it alive as
long as any reference exists — and it still reports `.name == "Widget"`.  So every
diagnostic that relies on name equality (logging, serialisation round-trips,
`respond_to?` checks) continues to pass.  Only identity-based checks fail:
`is_a?`, `===`, `case/when`, and any registry keyed on the class object itself.

## How the wrong version fails — and how it fails silently

On any version of zeitwerk that supports `enable_reloading` (introduced in 2.1.0),
this behaviour is consistent.  The failure is **silent**: the build stays green,
no exception is raised, and the only symptom is that type guards (`is_a?`, `case/when`)
return the wrong branch.  In a server process that reloads on each request during
development, every object created in one request silently stops matching type checks
in the next request — the kind of bug that appears only under load or over time,
and that stack traces cannot point to because no exception is ever raised.
app/widget.rb
class Widget
  attr_reader :label

  def initialize(label)
    @label = label
  end
end
csx.json
{"case":{"believed":"Calling loader.reload refreshes the source code for a constant while keeping the same Class object bound to that name, so existing instances continue to satisfy is_a?(Widget) and case/when Widget after reload.","caseId":"case:sha256:5fea9bd08858a8240a0f0fb803962583f1ce33c5c695690a853ea50b4681a667","contract":["After loader.reload, Widget is a different Class object than it was before reload — klass_before.equal?(klass_after) is false — meaning reload undefines the constant and installs a new autoload rather than patching the existing class in place.","klass_before.name == 'Widget' \u0026\u0026 klass_after.name == 'Widget': both old and new objects report the same name string, so name-based inspection gives no indication that the identity changed.","instance.is_a?(Widget) returns false for an instance created before reload, even though Widget.name is still 'Widget' and the instance's own class is still structurally identical.","instance.is_a?(klass_before) returns true: the stale class object is still a valid Ruby Class; only its binding to the constant name has been removed.","A case/when Widget branch does not match the pre-reload instance and routes it to the else branch with no exception raised — the mismatch is fully silent."],"goal":"Show that Zeitwerk::Loader#reload replaces every managed constant with a fresh Class object rather than updating the existing object in place, so pre-reload instances silently fail is_a? checks against the live constant after reload.","kind":"HOW","packages":["pkg:gem/zeitwerk@2.8.3"],"schemaVersion":1,"symbols":["Zeitwerk::Loader#enable_reloading","Zeitwerk::Loader#reload","Zeitwerk::Loader#setup","Zeitwerk::Loader#push_dir"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundler","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/zeitwerk@2.8.3"],"schemaVersion":1,"symbols":["Zeitwerk::Loader#enable_reloading","Zeitwerk::Loader#reload","Zeitwerk::Loader#setup","Zeitwerk::Loader#push_dir"],"verifierAdapter":"rubygems@1"}
test/contract.rb
# frozen_string_literal: true

require "zeitwerk"

# ---------------------------------------------------------------------------
# Setup: one managed root directory, reloading enabled.
# ---------------------------------------------------------------------------
loader = Zeitwerk::Loader.new
loader.push_dir(File.expand_path("../app", __dir__))
loader.enable_reloading
loader.setup

# ---------------------------------------------------------------------------
# Round-trip: touch the constant before and after reload.
# ---------------------------------------------------------------------------
klass_before = Widget                  # triggers autoload; Widget is now loaded
instance      = klass_before.new("x") # concrete instance, pre-reload

loader.reload                          # Zeitwerk removes and re-autoloads Widget

klass_after = Widget                   # triggers autoload of the fresh definition

# ---------------------------------------------------------------------------
# Contract assertions
# ---------------------------------------------------------------------------

# 1. After reload, Widget is a different object — the constant was replaced.
#    A developer who has not read the reload internals expects `reload` to
#    update the existing constant in-place (like re-opening a class).  It does
#    not: it undefines the old constant entirely and sets up a fresh autoload.
unless klass_before != klass_after
  raise "FAIL: klass_before.equal?(klass_after) — reload updated in place, contract invalid"
end
puts "PASS 1: reload replaces Widget with a new Class object (object_id #{klass_before.object_id} -> #{klass_after.object_id})"

# 2. Both the old and new class *name* the same string — the silent green symptom.
#    Logging, serialisation, or any code that inspects .name will see no change
#    and will not warn you that the class objects are different.
unless klass_before.name == "Widget" && klass_after.name == "Widget"
  raise "FAIL: at least one class does not report name 'Widget'"
end
puts "PASS 2: both old and new class objects report .name == 'Widget' — the name survives; the identity does not"

# 3. The pre-reload instance fails is_a? against the live constant.
#    Type guards, case/when, and type-keyed registries silently break.
if instance.is_a?(Widget)
  raise "FAIL: old instance passed is_a?(Widget) after reload — identity was preserved unexpectedly"
end
puts "PASS 3: instance.is_a?(Widget) => false after reload (instance.class is stale klass_before)"

# 4. The instance *does* recognise its own (stale) class — the class object is
#    still alive and correctly describes the instance; only the constant binding
#    has been severed.
unless instance.is_a?(klass_before)
  raise "FAIL: instance does not recognise klass_before — unexpected"
end
puts "PASS 4: instance.is_a?(klass_before) => true — the stale class object is still valid Ruby; only the constant mapping changed"

# 5. Equality-based dispatch (case/when) breaks silently for the same reason.
result = case instance
         when Widget then :new_class
         else             :stale
         end
if result == :new_class
  raise "FAIL: case/when routed to :new_class — constant identity was somehow preserved"
end
puts "PASS 5: case/when Widget routes stale instance to :stale branch — silent mismatch, no exception"

puts
puts "All 5 contract assertions passed."

Исходный сидер

csx-seed