CodeSampleX

샘플

sorbet-runtime 0.6.13427: Handle thread-local declaration state, failed sig retry poisoning, and reentrant invocations in sorbet-runtime

검증된 샘플 — gem sorbet-runtime 0.6.13427: Handle thread-local declaration state, failed sig retry poisoning, and reentrant invocations in sorbet-runtime. ruby 3…

sha256:92626ce19dbeb23bcf39bacfb6fa5bae6bb0a0e9104b1417876a2f77b4b1f928

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 ruby linux x64 ruby ruby bundler

검증 실행 환경

환경 컨트랙트 단계 실행일
ruby 3 · linux alpine/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

케이스

HOW
목표
Handle thread-local declaration state, failed sig retry poisoning, and reentrant invocations in sorbet-runtime
패키지
심벌
  • T::Sig
  • T::Private::Methods
  • T::Private::DeclState
환경
ruby
생성일
2026-08-16T17:12:51Z

컨트랙트

  1. Retrying a method whose lazy sig block previously raised an exception fails with RuntimeError: 'A previous invocation... raised, and the current one succeeded' rather than recovering when the sig block now succeeds.
  2. Declaring sig in one thread and defining the method in another leaves the method completely untyped while leaving a dangling active_declaration that breaks subsequent sig calls in the declaring thread.
  3. Re-entering a method from inside its own sig block before the first-call wrapper completes raises SystemStackError due to recursive first-call wrapper re-entry.
  4. Calling sig twice in the same thread without an intervening method definition immediately raises RuntimeError and resets the pending declaration.

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

Gemfile
source "https://rubygems.org"

gem "sorbet-runtime", "0.6.13427"
gem "minitest", "5.25.5"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    minitest (5.25.5)
    sorbet-runtime (0.6.13427)

PLATFORMS
  ruby
  x86_64-linux

DEPENDENCIES
  minitest (= 5.25.5)
  sorbet-runtime (= 0.6.13427)

BUNDLED WITH
   2.6.9
NOTES.md
# sorbet-runtime: Concurrency, Reentrancy, and Declaration Lifecycle

## Prior Findings
A query to the network returned sample `sha256:0e5a23077089e2ffe5fe30132707fc39f81467a95abe8545d6c612eadb7fb18d` ("Know what sorbet-runtime enforces when the static checker is not running, and where the same type expression is checked deeply, shallowly, or not at all"), which focused on static vs runtime type checking and collection type erasure.

This sample focuses on a different trap: runtime declaration state management, cross-thread method decoration isolation, failed lazy signature poisoning, and reentrant method execution.

## Behavioral Traps
1. **Lazy Sig Poisoning**: When a `sig` block raises an exception on first call (such as a temporarily missing constant or circular initialization error), Sorbet records the failure in `@sigs_that_raised`. If the exception is handled and the method is invoked again after fixing the error, Sorbet permanently refuses the method with `RuntimeError: A previous invocation of ... raised, and the current one succeeded. Please don't do that.`
2. **Thread-Local Declaration Separation**: `sig` stores the pending declaration in `Thread.current[:opus_types__decl_state]`. If `sig` is called on a worker thread and the method definition `def` runs in another thread, the method is defined completely untyped without runtime checks, while the declaring thread retains a dangling declaration that causes its next `sig` call to raise `RuntimeError: You called sig twice without declaring a method in between`.
3. **Reentrancy During First Call**: Re-entering a method from inside its own `sig` block causes infinite recursion and raises `SystemStackError`, because the first-call wrapper has not yet been replaced with the validated method.

## Failure Mode
An implementation assuming standard retry semantics fails loudly with `RuntimeError` on the second call, while cross-thread method definitions fail silently with untyped execution (a green build that skips type validation).
csx.json
{"case":{"believed":"A sig block failing on first invocation can be retried once its dependencies resolve, sig binds to the next lexically defined method across threads, and re-entering a method during sig evaluation executes the underlying method body.","caseId":"case:sha256:b5cd513f87053e5b17be7ea8f0dc3c021e06feebfac36e79e9189da0cbb1b082","contract":["Retrying a method whose lazy sig block previously raised an exception fails with RuntimeError: 'A previous invocation... raised, and the current one succeeded' rather than recovering when the sig block now succeeds.","Declaring sig in one thread and defining the method in another leaves the method completely untyped while leaving a dangling active_declaration that breaks subsequent sig calls in the declaring thread.","Re-entering a method from inside its own sig block before the first-call wrapper completes raises SystemStackError due to recursive first-call wrapper re-entry.","Calling sig twice in the same thread without an intervening method definition immediately raises RuntimeError and resets the pending declaration."],"goal":"Handle thread-local declaration state, failed sig retry poisoning, and reentrant invocations in sorbet-runtime","kind":"HOW","packages":["pkg:gem/sorbet-runtime@0.6.13427"],"schemaVersion":1,"symbols":["T::Sig","T::Private::Methods","T::Private::DeclState"]},"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/sorbet-runtime@0.6.13427"],"schemaVersion":1,"symbols":["T::Sig","T::Private::Methods","T::Private::DeclState"],"verifierAdapter":"rubygems@1"}
test/contract.rb
# frozen_string_literal: true

require "sorbet-runtime"
require "minitest/autorun"

class SorbetConcurrencyOrderingReentrancyTest < Minitest::Test
  # Trap 1: Retrying a method after its lazy sig block raised an exception.
  #
  # Believed: If a method's sig block raises an error on first invocation
  # (for example, due to a missing dependency or load-order issue) and is rescued,
  # fixing the condition and calling the method again will evaluate the sig and run.
  #
  # Actual: Sorbet records `@sigs_that_raised[key] = true`. On any subsequent call,
  # even if the sig block evaluates cleanly, Sorbet raises a RuntimeError:
  # "A previous invocation of ... raised, and the current one succeeded. Please don't do that."
  def test_failed_sig_block_permanently_poisons_method
    transient_failure = true

    service_class = Class.new do
      extend T::Sig

      sig do
        if transient_failure
          raise NameError, "uninitialized constant ConfigService"
        else
          params(id: Integer).returns(Integer)
        end
      end
      def fetch_data(id)
        id * 10
      end
    end

    service = service_class.new

    # First invocation fails inside the sig block
    err1 = assert_raises(NameError) do
      service.fetch_data(1)
    end
    assert_includes err1.message, "ConfigService"

    # Dependency is now resolved
    transient_failure = false

    # Second invocation fails permanently with Sorbet's poison error
    err2 = assert_raises(RuntimeError) do
      service.fetch_data(1)
    end
    assert_includes err2.message, "raised, and the current one succeeded. Please don't do that."
  end

  # Trap 2: Thread-local declaration state across tasks/threads.
  #
  # Believed: `sig` binds to the next method definition on the class/module
  # regardless of which thread executes the `def`.
  #
  # Actual: `T::Private::DeclState` is stored in `Thread.current[:opus_types__decl_state]`.
  # If Thread A calls `sig` and Thread B executes `def`, Thread B sees no active declaration,
  # defining the method completely untyped without a wrapper. Meanwhile, Thread A retains a
  # dangling `active_declaration` that breaks the next `sig` call on Thread A.
  def test_cross_thread_sig_def_separation_and_dangling_state
    mod = Module.new do
      extend T::Sig
    end

    # Task/Thread 1 declares sig
    thread_1 = Thread.new do
      mod.sig { params(x: Integer).returns(Integer) }
    end
    thread_1.join

    # Task/Thread 2 defines the method
    thread_2 = Thread.new do
      mod.define_method(:compute) { |x| x }
    end
    thread_2.join

    klass = Class.new { include mod }
    instance = klass.new

    # The method defined in Thread 2 has no signature attached
    sig = T::Private::Methods.signature_for_method(klass.instance_method(:compute))
    assert_nil sig

    # Untyped method accepts invalid argument type without raising TypeError
    assert_equal "invalid_type", instance.compute("invalid_type")

    # Thread 1's state is polluted; running another sig on Thread 1 raises immediately
    work_queue = Queue.new
    reply_queue = Queue.new

    worker = Thread.new do
      while (action = work_queue.pop)
        case action
        when :first_sig
          mod.sig { params(a: String).returns(String) }
          reply_queue << :done
        when :second_sig
          begin
            mod.sig { params(b: Integer).returns(Integer) }
            reply_queue << :unexpected_success
          rescue RuntimeError => e
            reply_queue << e
          end
        end
      end
    end

    work_queue << :first_sig
    assert_equal :done, reply_queue.pop

    # Without defining a method, attempt second sig on same thread
    work_queue << :second_sig
    dangling_err = reply_queue.pop
    assert_instance_of RuntimeError, dangling_err
    assert_includes dangling_err.message, "You called sig twice without declaring a method in between"

    worker.kill
  end

  # Trap 3: Reentrancy during first-call signature building.
  #
  # Believed: Calling a method from within its own `sig` block executes the method
  # body or reuses the in-progress signature declaration.
  #
  # Actual: On the first method call, the wrapper invokes `run_sig_block_for_key`.
  # Because the wrapper has not yet been replaced with the validated method, any reentrant
  # invocation of the method hits the first-call wrapper again, causing infinite recursion
  # and raising `SystemStackError`.
  def test_reentrant_call_during_sig_evaluation_raises_system_stack_error
    klass = Class.new do
      extend T::Sig

      sig do
        # Attempt to call self during signature evaluation
        klass.action(10)
        params(val: Integer).returns(Integer)
      end
      def self.action(val)
        val * 2
      end
    end

    assert_raises(SystemStackError) do
      klass.action(10)
    end
  end

  # Trap 4: Consecutive sig calls in the same thread.
  #
  # Believed: Calling `sig` again overwrites or updates the pending signature.
  #
  # Actual: `declare_sig` checks `DeclState.current.active_declaration`. If present,
  # it resets the declaration state and raises RuntimeError immediately.
  def test_consecutive_sig_calls_raise_and_reset
    mod = Module.new do
      extend T::Sig
    end

    mod.sig { params(x: Integer).returns(Integer) }

    err = assert_raises(RuntimeError) do
      mod.sig { params(y: String).returns(String) }
    end
    assert_includes err.message, "You called sig twice without declaring a method in between"

    # State is now reset, allowing a fresh sig to be declared
    mod.sig { params(z: Float).returns(Float) }
    mod.define_method(:calc) { |z| z * 1.5 }

    calc_sig = T::Private::Methods.signature_for_method(mod.instance_method(:calc))
    refute_nil calc_sig
  end
end

오리진 시더

csx-seed