CodeSampleX

Exemple

zeitwerk 2.8.3: Differentiate Zeitwerk exception hierarchy and error dispatch paths across invalid namespace definitions, unmanaged files, and lifecycle misordering

Échantillon vérifié pour gem zeitwerk 2.8.3: Differentiate Zeitwerk exception hierarchy and error dispatch paths across invalid namespace definitions…

sha256:9be8f03e18da8a40234c0072cc13a93ec3afcdf7b74fe38906c30c2e17c369d6

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré ruby linux x64 ruby ruby bundler

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-16
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-18

Cas

HOW
Objectif
Differentiate Zeitwerk exception hierarchy and error dispatch paths across invalid namespace definitions, unmanaged files, and lifecycle misordering
Paquets
Symboles
  • Zeitwerk::Loader
  • Zeitwerk::Loader#push_dir
  • Zeitwerk::Loader#setup
  • Zeitwerk::Loader#enable_reloading
  • Zeitwerk::Loader#reload
  • Zeitwerk::Loader#eager_load
  • Zeitwerk::Loader#load_file
  • Zeitwerk::Loader#nsfile=
  • Zeitwerk::ConstAdded#const_added
  • Zeitwerk::Error
  • Zeitwerk::ReloadingDisabledError
  • Zeitwerk::SetupRequired
  • Zeitwerk::ConflictingNamespaceDefinitionError
Environnement
ruby
Créé
2026-08-16T17:17:19Z

Contrat

  1. assert assigning a non-module object in an explicit namespace file immediately raises Zeitwerk::Error from const_added during autoload, escaping rescue NameError and rescue TypeError
  2. assert push_dir rejects Symbol and String namespace arguments with Zeitwerk::Error rather than TypeError or ArgumentError
  3. assert push_dir rejects anonymous modules with Zeitwerk::Error stating root namespaces cannot be anonymous
  4. assert calling reload without enabling reloading raises Zeitwerk::ReloadingDisabledError while calling enable_reloading after setup raises base Zeitwerk::Error
  5. assert calling eager_load before setup raises Zeitwerk::SetupRequired rather than RuntimeError or ArgumentError
  6. assert load_file normalizes missing files, non-Ruby files, ignored files, hidden files, and unmanaged files to Zeitwerk::Error instead of LoadError or Errno::ENOENT
  7. assert conflicting explicit namespace file and nsfile definitions raise Zeitwerk::ConflictingNamespaceDefinitionError identifying both file paths

Fichiers

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • src/error_paths.rb
  • src/trees/anonymous_ns/dummy.rb
  • src/trees/conflicting_ns/accounts.rb
  • src/trees/conflicting_ns/accounts/ns.rb
  • src/trees/eager_unsetup/dummy.rb
  • src/trees/file_inputs/.hidden.rb
  • src/trees/file_inputs/doc.txt
  • src/trees/file_inputs/entry.rb
  • src/trees/file_inputs/ignored.rb
  • src/trees/invalid_namespace/router.rb
  • src/trees/invalid_namespace/router/route.rb
  • src/trees/non_module_ns/dummy.rb
  • src/trees/reloading/item.rb
  • test/contract.rb

Télécharger l’artefact source (tar.gz)

Code source

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
  x86_64-linux-musl

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 Error Hierarchy and Dispatch Paths

## Known Solution Search
`search_known_solution` returned existing sample `sha256:fe3c29ae9cd4ff1fa9203d040133804b1057836934a88d30aab4c109c86f7647` covering `Zeitwerk::NameError` raised during constant autoloading naming mismatches. This sample targets the separate, non-NameError exception hierarchy and error dispatch paths in Zeitwerk: explicit namespace non-module type checks during constant definition, root namespace type validation in `push_dir`, reloading lifecycle error states, file input error normalization in `load_file`, and namespace collision detection.

## Key Behaviors Proven

1. **Explicit Namespace Type Validation via `ConstAdded`**: When a directory structure defines an explicit namespace file (such as `router.rb` alongside a `router/` directory), assigning a non-module object (e.g. an instance of `Object`, `Hash`, or integer) immediately triggers `Module#const_added` prepended by `Zeitwerk::ConstAdded`. Zeitwerk raises `Zeitwerk::Error` synchronously at the point of assignment inside the file, before file execution completes. Because `Zeitwerk::Error` inherits from `StandardError` rather than `TypeError` or `NameError`, typical `rescue NameError` or `rescue TypeError` handlers fail to catch it.
2. **Root Namespace Constraints in `push_dir`**: Passing a Symbol or String (such as `namespace: :Api` or `namespace: "Api"`) raises `Zeitwerk::Error` rather than `TypeError` or `ArgumentError`. Passing an anonymous module (`Module.new`) raises `Zeitwerk::Error` explaining that root namespaces cannot be anonymous.
3. **Lifecycle State Errors**: Calling `loader.reload` when reloading was not enabled before setup raises `Zeitwerk::ReloadingDisabledError` (a subclass of `Zeitwerk::Error`). Calling `loader.enable_reloading` after `setup` raises base `Zeitwerk::Error` rather than `ReloadingDisabledError`. Calling `loader.eager_load` before `setup` raises `Zeitwerk::SetupRequired`.
4. **Normalized File Input Errors**: `loader.load_file` wraps all underlying resolution failures into `Zeitwerk::Error` (not Ruby's `LoadError`, `Errno::ENOENT`, or `ArgumentError`), covering missing files, non-Ruby extensions, ignored files, hidden files, and unmanaged paths.
5. **Conflicting Namespace Definitions**: When an explicit namespace file and a configured `nsfile` define the same namespace, `loader.setup` raises `Zeitwerk::ConflictingNamespaceDefinitionError` identifying both conflicting paths.

## Failure Mode
When assumptions about error types are wrong, rescue blocks targeting NameError or TypeError fail loudly with uncaught Zeitwerk::Error exceptions during autoloading or setup.
csx.json
{"case":{"believed":"Defining a non-module object in an explicit namespace file raises Ruby's standard TypeError on nested constant access or Zeitwerk::NameError during autoloading.","caseId":"case:sha256:09da8380b7947f7bcd62a91206ed93f9eaff9fcdffdb8e67cfde51e0780bc070","contract":["assert assigning a non-module object in an explicit namespace file immediately raises Zeitwerk::Error from const_added during autoload, escaping rescue NameError and rescue TypeError","assert push_dir rejects Symbol and String namespace arguments with Zeitwerk::Error rather than TypeError or ArgumentError","assert push_dir rejects anonymous modules with Zeitwerk::Error stating root namespaces cannot be anonymous","assert calling reload without enabling reloading raises Zeitwerk::ReloadingDisabledError while calling enable_reloading after setup raises base Zeitwerk::Error","assert calling eager_load before setup raises Zeitwerk::SetupRequired rather than RuntimeError or ArgumentError","assert load_file normalizes missing files, non-Ruby files, ignored files, hidden files, and unmanaged files to Zeitwerk::Error instead of LoadError or Errno::ENOENT","assert conflicting explicit namespace file and nsfile definitions raise Zeitwerk::ConflictingNamespaceDefinitionError identifying both file paths"],"goal":"Differentiate Zeitwerk exception hierarchy and error dispatch paths across invalid namespace definitions, unmanaged files, and lifecycle misordering","kind":"HOW","packages":["pkg:gem/zeitwerk@2.8.3"],"schemaVersion":1,"symbols":["Zeitwerk::Loader","Zeitwerk::Loader#push_dir","Zeitwerk::Loader#setup","Zeitwerk::Loader#enable_reloading","Zeitwerk::Loader#reload","Zeitwerk::Loader#eager_load","Zeitwerk::Loader#load_file","Zeitwerk::Loader#nsfile=","Zeitwerk::ConstAdded#const_added","Zeitwerk::Error","Zeitwerk::ReloadingDisabledError","Zeitwerk::SetupRequired","Zeitwerk::ConflictingNamespaceDefinitionError"]},"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","Zeitwerk::Loader#push_dir","Zeitwerk::Loader#setup","Zeitwerk::Loader#enable_reloading","Zeitwerk::Loader#reload","Zeitwerk::Loader#eager_load","Zeitwerk::Loader#load_file","Zeitwerk::Loader#nsfile=","Zeitwerk::ConstAdded#const_added","Zeitwerk::Error","Zeitwerk::ReloadingDisabledError","Zeitwerk::SetupRequired","Zeitwerk::ConflictingNamespaceDefinitionError"],"verifierAdapter":"rubygems@1"}
src/error_paths.rb
# frozen_string_literal: true

require "zeitwerk"

module ErrorPaths
  TREES = File.expand_path("trees", __dir__)

  def self.tree(name)
    File.join(TREES, name)
  end

  def self.file(tree_name, *segments)
    File.join(tree(tree_name), *segments)
  end

  def self.loader_for(tree_name)
    loader = Zeitwerk::Loader.new
    loader.push_dir(tree(tree_name))
    loader
  end
end
src/trees/anonymous_ns/dummy.rb
# Dummy file in anonymous_ns directory
class AnonymousNsDummy
end
src/trees/conflicting_ns/accounts.rb
module Accounts
end
src/trees/conflicting_ns/accounts/ns.rb
module Accounts
end
src/trees/eager_unsetup/dummy.rb
# Dummy file in eager_unsetup directory
class EagerUnsetupDummy
end
src/trees/file_inputs/.hidden.rb
class Hidden
end
src/trees/file_inputs/doc.txt
Non-ruby text document for file type error path testing.
src/trees/file_inputs/entry.rb
class Entry
  def self.name
    "Entry"
  end
end
src/trees/file_inputs/ignored.rb
class Ignored
end
src/trees/invalid_namespace/router.rb
# Explicit namespace file defining a non-module object (an instance of Object).
# When this file is required, Zeitwerk::ConstAdded intercepts const_added(:Router)
# and immediately raises Zeitwerk::Error before the rest of the file evaluates.
Router = Object.new
$router_file_finished = true
src/trees/invalid_namespace/router/route.rb
class Router::Route
  def self.call
    :ok
  end
end
src/trees/non_module_ns/dummy.rb
# Dummy file in non_module_ns directory
class NonModuleNsDummy
end
src/trees/reloading/item.rb
class Item
  VERSION = 1
end
test/contract.rb
# frozen_string_literal: true

require "minitest/autorun"
require_relative "../src/error_paths"

class ZeitwerkErrorContractTest < Minitest::Test
  def test_explicit_namespace_non_module_raises_zeitwerk_error_via_const_added
    # Trap: When a directory 'router/' has an explicit namespace file 'router.rb'
    # that defines Router as a non-Module object (e.g. Object.new, Hash, or number),
    # naive models expect referencing Router to raise TypeError or Zeitwerk::NameError.
    #
    # Reality: Zeitwerk intercepts Module#const_added via Zeitwerk::ConstAdded synchronously
    # during file evaluation and raises Zeitwerk::Error (a StandardError, NOT TypeError or NameError).
    # This aborts the file mid-execution and bypasses rescue NameError / rescue TypeError.
    tree = ErrorPaths.tree("invalid_namespace")
    loader = Zeitwerk::Loader.new
    loader.push_dir(tree)
    loader.setup

    rescued_name_error = false
    rescued_type_error = false
    rescued_zeitwerk_error = false

    begin
      begin
        Router
      rescue ::NameError
        rescued_name_error = true
      rescue ::TypeError
        rescued_type_error = true
      end
    rescue Zeitwerk::Error => e
      rescued_zeitwerk_error = true
      assert_equal "Router is expected to be a namespace, should be a class or module (got Object)", e.message
      assert_instance_of Zeitwerk::Error, e
      refute_kind_of ::NameError, e
      refute_kind_of ::TypeError, e
    end

    refute rescued_name_error, "Zeitwerk::Error does not inherit from NameError"
    refute rescued_type_error, "Zeitwerk::Error does not inherit from TypeError"
    assert rescued_zeitwerk_error, "Must raise Zeitwerk::Error on const_added"

    # Evaluation aborted before the rest of the file executed
    refute $router_file_finished
  end

  def test_push_dir_rejects_non_module_namespace_with_zeitwerk_error
    # Trap: Models often expect push_dir(path, namespace: :Api) or namespace: "Api"
    # to work or raise TypeError/ArgumentError.
    #
    # Reality: Zeitwerk explicitly raises Zeitwerk::Error (not TypeError or ArgumentError)
    # when namespace is not a Class or Module.
    loader = Zeitwerk::Loader.new
    tree = ErrorPaths.tree("non_module_ns")

    err_sym = assert_raises(Zeitwerk::Error) do
      loader.push_dir(tree, namespace: :Api)
    end
    assert_equal ":Api is not a class or module object, should be", err_sym.message
    refute_kind_of ::TypeError, err_sym
    refute_kind_of ::ArgumentError, err_sym

    err_str = assert_raises(Zeitwerk::Error) do
      loader.push_dir(tree, namespace: "Api")
    end
    assert_equal "\"Api\" is not a class or module object, should be", err_str.message
    refute_kind_of ::TypeError, err_str
    refute_kind_of ::ArgumentError, err_str
  end

  def test_push_dir_rejects_anonymous_module_with_zeitwerk_error
    # Trap: Models often expect anonymous Module.new to work as an isolated sandbox namespace.
    #
    # Reality: Zeitwerk requires named modules for constant path resolution and raises
    # Zeitwerk::Error: root namespaces cannot be anonymous.
    loader = Zeitwerk::Loader.new
    tree = ErrorPaths.tree("anonymous_ns")
    anon = Module.new

    err = assert_raises(Zeitwerk::Error) do
      loader.push_dir(tree, namespace: anon)
    end
    assert_equal "root namespaces cannot be anonymous", err.message
    assert_instance_of Zeitwerk::Error, err
    refute_kind_of ::ArgumentError, err
  end

  def test_reloading_lifecycle_errors_distinguish_disabled_from_post_setup_configuration
    # Trap: Models expect reload without enable_reloading to raise Zeitwerk::Error,
    # or expect enable_reloading to work after setup.
    #
    # Reality:
    # 1. Calling reload when reloading is disabled raises Zeitwerk::ReloadingDisabledError
    #    (a subclass of Zeitwerk::Error).
    # 2. Calling enable_reloading after setup raises base Zeitwerk::Error (NOT ReloadingDisabledError).
    tree = ErrorPaths.tree("reloading")
    loader = Zeitwerk::Loader.new
    loader.push_dir(tree)
    loader.setup

    err_reload = assert_raises(Zeitwerk::ReloadingDisabledError) do
      loader.reload
    end
    assert_equal "can't reload, please call loader.enable_reloading before setup", err_reload.message
    assert_kind_of Zeitwerk::Error, err_reload
    assert_instance_of Zeitwerk::ReloadingDisabledError, err_reload

    err_enable = assert_raises(Zeitwerk::Error) do
      loader.enable_reloading
    end
    assert_equal "cannot enable reloading after setup", err_enable.message
    assert_instance_of Zeitwerk::Error, err_enable
    refute_instance_of Zeitwerk::ReloadingDisabledError, err_enable
  end

  def test_eager_load_before_setup_raises_setup_required
    # Trap: Models expect eager_load before setup to raise RuntimeError, ArgumentError, or auto-run setup.
    #
    # Reality: Zeitwerk raises Zeitwerk::SetupRequired (< Zeitwerk::Error).
    loader = Zeitwerk::Loader.new
    tree = ErrorPaths.tree("eager_unsetup")
    loader.push_dir(tree)

    err = assert_raises(Zeitwerk::SetupRequired) do
      loader.eager_load
    end
    assert_equal "please, finish your configuration and call Zeitwerk::Loader#setup once all is ready", err.message
    assert_kind_of Zeitwerk::Error, err
    assert_instance_of Zeitwerk::SetupRequired, err
    refute_kind_of ::RuntimeError, err
    refute_kind_of ::ArgumentError, err
  end

  def test_load_file_normalizes_all_input_failures_to_zeitwerk_error
    # Trap: Models expect file lookup errors to raise Ruby's LoadError, Errno::ENOENT, or ArgumentError.
    #
    # Reality: load_file normalizes all file input failures to Zeitwerk::Error with specific diagnostic messages.
    dir = ErrorPaths.tree("file_inputs")
    valid_file = File.join(dir, "entry.rb")
    txt_file = File.join(dir, "doc.txt")
    ignored_file = File.join(dir, "ignored.rb")
    hidden_file = File.join(dir, ".hidden.rb")
    missing_file = File.join(dir, "missing.rb")

    loader = Zeitwerk::Loader.new
    loader.push_dir(dir)
    loader.ignore(ignored_file)
    loader.setup

    # Missing file -> Zeitwerk::Error (not LoadError / Errno::ENOENT)
    e1 = assert_raises(Zeitwerk::Error) { loader.load_file(missing_file) }
    assert_equal "#{missing_file} does not exist", e1.message
    refute_kind_of ::LoadError, e1
    refute_kind_of ::SystemCallError, e1

    # Non-Ruby file -> Zeitwerk::Error (not ArgumentError)
    e2 = assert_raises(Zeitwerk::Error) { loader.load_file(txt_file) }
    assert_equal "#{txt_file} is not a Ruby file", e2.message

    # Ignored file -> Zeitwerk::Error
    e3 = assert_raises(Zeitwerk::Error) { loader.load_file(ignored_file) }
    assert_equal "#{ignored_file} is ignored", e3.message

    # Hidden file -> Zeitwerk::Error
    e4 = assert_raises(Zeitwerk::Error) { loader.load_file(hidden_file) }
    assert_equal "#{hidden_file} is ignored", e4.message

    # Unmanaged file (or file under hidden ancestor directory) -> Zeitwerk::Error
    external_file = ErrorPaths.file("reloading", "item.rb")
    e5 = assert_raises(Zeitwerk::Error) { loader.load_file(external_file) }
    assert_match(/I do not manage|is ignored/, e5.message)

    # Valid file loads and returns the constant
    assert_equal Entry, loader.load_file(valid_file)
  end

  def test_conflicting_namespace_definition_raises_conflicting_namespace_error
    # Trap: Models expect duplicate or conflicting namespace definitions to raise NameError or issue warnings.
    #
    # Reality: Setting nsfile when an explicit namespace file also exists for the same constant
    # raises Zeitwerk::ConflictingNamespaceDefinitionError (< Zeitwerk::Error) during setup,
    # naming both the namespace and the two conflicting absolute file paths.
    dir = ErrorPaths.tree("conflicting_ns")
    explicit_file = File.join(dir, "accounts.rb")
    ns_file = File.join(dir, "accounts", "ns.rb")

    loader = Zeitwerk::Loader.new
    loader.nsfile = "ns.rb"
    loader.push_dir(dir)

    err = assert_raises(Zeitwerk::ConflictingNamespaceDefinitionError) do
      loader.setup
    end

    assert_kind_of Zeitwerk::Error, err
    assert_instance_of Zeitwerk::ConflictingNamespaceDefinitionError, err
    refute_kind_of ::NameError, err
    assert_includes err.message, "conflicting namespace definition for Accounts"
    assert_includes err.message, explicit_file
    assert_includes err.message, ns_file
  end
end

Seeder d'origine

csx-seed