CodeSampleX

Sample

faraday 2.14.3: Handle middleware stack caching and isolation traps when duplicating Faraday connections across requests or tasks

Verified sample for gem faraday 2.14.3: Handle middleware stack caching and isolation traps when duplicating Faraday connections across requests or tasks.…

sha256:ba99fb2bf3dcbb90f9cfeb92673322d9bb85a7bdef5493050f6dd3a779abd62d

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment ruby linux x64 ruby ruby rubygems

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
Handle middleware stack caching and isolation traps when duplicating Faraday connections across requests or tasks
Packages
Symbols
  • Faraday::Connection
  • Faraday::Connection#dup
  • Faraday::Connection#use
  • Faraday::Connection#app
  • Faraday::RackBuilder
  • Faraday::RackBuilder#lock!
  • Faraday::RackBuilder#locked?
  • Faraday::RackBuilder::StackLocked
  • Faraday::Middleware
Environment
ruby
Created
2026-08-17T02:39:03Z

Contract

  1. Adding middleware to a duplicated Faraday connection after the original connection has executed a request silently ignores the new middleware during request execution because dup preserves the parent connection's pre-compiled rack app instance.
  2. assert modifying the middleware stack of a connection after executing a request raises Faraday::RackBuilder::StackLocked
  3. assert duplicating a connection before any requests are executed successfully compiles and runs newly appended middleware
  4. assert headers mutated on a duplicated connection are isolated from the parent connection whereas mutating headers on a shared connection affects all callers
  5. assert nested middleware request callbacks execute in insertion order while response on_complete hooks unwind in reverse order

Files

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

Download the source artifact (tar.gz)

Source

Gemfile
source "https://rubygems.org"

gem "faraday", "2.14.3"
gem "minitest", "5.27.0"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    faraday (2.14.3)
      faraday-net_http (>= 2.0, < 3.5)
      json
      logger
    faraday-net_http (3.4.4)
      net-http (~> 0.5)
    json (2.21.2)
    logger (1.7.0)
    minitest (5.27.0)
    net-http (0.9.1)
      uri (>= 0.11.1)
    uri (1.1.1)

PLATFORMS
  ruby
  x64-mingw-ucrt

DEPENDENCIES
  faraday (= 2.14.3)
  minitest (= 5.27.0)

CHECKSUMS
  bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
  faraday (2.14.3) sha256=1882247e6766615c8220b4392bf1d27f6ebb63d8e28267587cef1fb0bf37f278
  faraday-net_http (3.4.4) sha256=0e78af151747ed1b00f33e25973b4bc220d7f16c00c39676817c8b12331eb588
  json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a
  logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
  minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
  net-http (0.9.1) sha256=25ba0b67c63e89df626ed8fac771d0ad24ad151a858af2cc8e6a716ca4336996
  uri (1.1.1) sha256=379fa58d27ffb1387eaada68c749d1426738bd0f654d812fcc07e7568f5c57c6

BUNDLED WITH
  4.0.18
NOTES.md
# Faraday Middleware Stack Caching on Duplicated Connections

## What search_known_solution answered
`search_known_solution` returned COMPATIBLE hits for existing Faraday samples:
- `sha256:d333c442d13a4e2eadf3208bd9bad459dd1eb9c2a60d7330e824131abf35f5c9`: default proxy, header, and SSL option resolution when arguments are left unset or falsy.
- `sha256:c50f9bbfe83d4d0f5b44242b2e1675ffca6f3c29d43f04ddd3ac9e36f0f0ce46`: `url_prefix` leading slash path stripping and `params_encoder` bracket formatting.
- `sha256:46eed9d91592cb5df8548ed6884a818eba294fbab879f42106d919a145b91d8a`: test adapter HTTP stubbing and gem separation.

This sample addresses an uncovered concurrency and connection-lifecycle trap: middleware stack caching when duplicating a `Faraday::Connection` across tasks or requests.

## What a naive model would write instead
A naive model assumes that calling `conn.dup` unlocks the builder and compiles a fresh middleware stack, so adding new middleware via `dup_conn.use` will intercept and process subsequent requests dispatched on the cloned connection.

## How the wrong version fails
Silently with a green build: `dup_conn.use` succeeds without error and appends the handler to `dup_conn.builder.handlers`, but because `dup` preserves the pre-compiled `@app` reference from the original connection, requests dispatched on `dup_conn` silently execute the parent's cached rack app and ignore newly added middleware.
csx.json
{"case":{"believed":"Duplicating an existing Faraday connection with dup creates an unlocked connection that executes subsequently added middleware on its requests.","caseId":"case:sha256:b630d12860411bd756ca71ec19c107885493351f11cff28c87f1caaffc5f33ef","contract":["Adding middleware to a duplicated Faraday connection after the original connection has executed a request silently ignores the new middleware during request execution because dup preserves the parent connection's pre-compiled rack app instance.","assert modifying the middleware stack of a connection after executing a request raises Faraday::RackBuilder::StackLocked","assert duplicating a connection before any requests are executed successfully compiles and runs newly appended middleware","assert headers mutated on a duplicated connection are isolated from the parent connection whereas mutating headers on a shared connection affects all callers","assert nested middleware request callbacks execute in insertion order while response on_complete hooks unwind in reverse order"],"goal":"Handle middleware stack caching and isolation traps when duplicating Faraday connections across requests or tasks","kind":"HOW","packages":["pkg:gem/faraday@2.14.3"],"schemaVersion":1,"symbols":["Faraday::Connection","Faraday::Connection#dup","Faraday::Connection#use","Faraday::Connection#app","Faraday::RackBuilder","Faraday::RackBuilder#lock!","Faraday::RackBuilder#locked?","Faraday::RackBuilder::StackLocked","Faraday::Middleware"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/faraday@2.14.3"],"schemaVersion":1,"symbols":["Faraday::Connection","Faraday::Connection#dup","Faraday::Connection#use","Faraday::Connection#app","Faraday::RackBuilder","Faraday::RackBuilder#lock!","Faraday::RackBuilder#locked?","Faraday::RackBuilder::StackLocked","Faraday::Middleware"],"verifierAdapter":"rubygems@1"}
src/connection_factory.rb
require "faraday"
require "json"

module ConnectionFactory
  class HeaderInjector < Faraday::Middleware
    def initialize(app, key, value)
      super(app)
      @key = key
      @value = value
    end

    def call(env)
      env.request_headers[@key] = @value
      @app.call(env)
    end
  end

  class ExecutionTracer < Faraday::Middleware
    def initialize(app, label, tracer)
      super(app)
      @label = label
      @tracer = tracer
    end

    def call(env)
      @tracer << "#{@label}:request"
      response = @app.call(env)
      response.on_complete do
        @tracer << "#{@label}:on_complete"
      end
      @tracer << "#{@label}:post_call"
      response
    end
  end

  def self.create_connection(url: "http://example.com", &block)
    Faraday.new(url, &block)
  end
end
test/contract.rb
require "minitest/autorun"
require "json"
require_relative "../src/connection_factory"

class FaradayDuplicationAndConcurrencyContract < Minitest::Test
  def setup
    @stubs = Faraday::Adapter::Test::Stubs.new do |stub|
      stub.get("/api/data") do |env|
        [200, { "Content-Type" => "application/json" }, env.request_headers.to_json]
      end
    end
  end

  def test_dup_after_request_silently_ignores_new_middleware_due_to_cached_app
    conn = ConnectionFactory.create_connection do |f|
      f.use ConnectionFactory::HeaderInjector, "X-Base", "present"
      f.adapter :test, @stubs
    end

    # Original connection makes a request, forcing compilation and caching of @app
    resp1 = conn.get("/api/data")
    headers1 = JSON.parse(resp1.body)
    assert_equal "present", headers1["X-Base"]
    assert_nil headers1["X-Branch"]
    assert_equal true, conn.builder.locked?

    # Duplicating the connection yields an unlocked builder
    dup_conn = conn.dup
    assert_equal false, dup_conn.builder.locked?

    # Adding middleware succeeds at builder level without error
    dup_conn.use ConnectionFactory::HeaderInjector, "X-Branch", "added"
    assert_equal 2, dup_conn.builder.handlers.size

    # Executing request on duplicated connection returns the cached app from parent
    resp2 = dup_conn.get("/api/data")
    headers2 = JSON.parse(resp2.body)

    # Contradiction: naive expectation is that X-Branch is injected into request headers.
    # Reality: dup preserved the compiled @app, silently ignoring the newly added middleware handler.
    assert_nil headers2["X-Branch"]
    assert_equal "present", headers2["X-Base"]
    assert_same conn.app, dup_conn.app
  end

  def test_modifying_middleware_after_request_raises_stack_locked
    conn = ConnectionFactory.create_connection do |f|
      f.adapter :test, @stubs
    end

    conn.get("/api/data")
    assert_equal true, conn.builder.locked?

    assert_raises(Faraday::RackBuilder::StackLocked) do
      conn.use ConnectionFactory::HeaderInjector, "X-Late", "fails"
    end
  end

  def test_dup_before_request_compiles_fresh_app_and_runs_new_middleware
    conn_fresh = ConnectionFactory.create_connection do |f|
      f.use ConnectionFactory::HeaderInjector, "X-Base", "present"
      f.adapter :test, @stubs
    end

    # Duplicating before any request has been dispatched
    dup_fresh = conn_fresh.dup
    dup_fresh.use ConnectionFactory::HeaderInjector, "X-Branch", "added"

    resp = dup_fresh.get("/api/data")
    headers = JSON.parse(resp.body)

    assert_equal "present", headers["X-Base"]
    assert_equal "added", headers["X-Branch"]
    refute_same conn_fresh.app, dup_fresh.app
  end

  def test_headers_isolation_between_duplicated_connections_vs_shared_mutation
    conn = ConnectionFactory.create_connection do |f|
      f.adapter :test, @stubs
    end
    conn.headers["X-Tenant"] = "tenant-parent"

    # Duplicated connection receives a copy of headers
    dup_conn = conn.dup
    dup_conn.headers["X-Tenant"] = "tenant-isolated-branch"

    assert_equal "tenant-parent", conn.headers["X-Tenant"]
    assert_equal "tenant-isolated-branch", dup_conn.headers["X-Tenant"]
    refute_same conn.headers, dup_conn.headers
  end

  def test_middleware_request_order_and_response_on_complete_unwinding
    tracer = []
    conn = ConnectionFactory.create_connection do |f|
      f.use ConnectionFactory::ExecutionTracer, "Outer", tracer
      f.use ConnectionFactory::ExecutionTracer, "Inner", tracer
      f.adapter :test, @stubs
    end

    conn.get("/api/data")

    # Request phase executes outer -> inner; on_complete executes inner -> outer
    expected_trace = [
      "Outer:request",
      "Inner:request",
      "Inner:on_complete",
      "Inner:post_call",
      "Outer:on_complete",
      "Outer:post_call"
    ]
    assert_equal expected_trace, tracer
  end
end

Origin Seeder

csx-seed