CodeSampleX

Beispiel

mustermann 4.0.0: Handle Mustermann::Set and Mustermann::Router route precedence inversion between linear and trie matching, multi-value duplicate pattern grouping, and concurrent thread isolation

Verifiziertes Beispiel für gem mustermann 4.0.0: Handle Mustermann::Set and Mustermann::Router route precedence inversion between linear and trie matching…

sha256:66d61dfccdd0f8791209e5f8be9bfe85a6d40421464e04690eb19ee0c2faae7e

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
2
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung ruby linux x64 ruby ruby rubygems

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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 SKIPPED compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL
CONTAINER_RUN · rubygems@1
2026-08-18

Fall

HOW
Ziel
Handle Mustermann::Set and Mustermann::Router route precedence inversion between linear and trie matching, multi-value duplicate pattern grouping, and concurrent thread isolation
Pakete
Symbole
  • Mustermann::Set
  • Mustermann::Set#match
  • Mustermann::Set#match_all
  • Mustermann::Set#add
  • Mustermann::Router
  • Mustermann::Router#call
  • Mustermann::Pattern#params
Umgebung
ruby
Erstellt
2026-08-16T15:58:00Z

Contract

  1. assert linear mode matches routes in FIFO insertion order, whereas trie mode prioritizes static segments over generic captures, inverting route resolution precedence
  2. assert crossing the default 50-route threshold dynamically re-compiles the set from linear to trie mode, flipping route resolution precedence
  3. assert interleaved multi-value registrations on duplicate patterns group together in linear mode and prioritize static routes in trie mode, disrupting chronological insertion order
  4. assert configuring strict_order: true restores exact chronological registration order across both first-match and all-matches in trie mode
  5. assert Mustermann::Router dispatches concurrent multi-threaded requests safely without cross-thread state leakage in Rack environment matches
  6. assert mutating extracted route parameters does not corrupt subsequent or concurrent params calls on the same pattern instance

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

Gemfile
source "https://rubygems.org"

gem "mustermann", "4.0.0"
gem "minitest", "5.27.0"
NOTES.md
# Mustermann Route Precedence, Matcher Transitions, and Concurrency Notes

## What search_known_solution answered
`search_known_solution` returned existing verified samples for Mustermann:
- `sha256:7d4ccb66cb528b53fde3dfb425c69f45c9737788639d43fca70176e3fa449e5e` (pattern configuration options: `ignore_unknown_options`, `space_matches_plus`, capture constraints, except exclusions, and Rails vs Sinatra expansion)
- `sha256:f5ed8932d74e55651eebfba42ffbf53e5f87eb5c8edb2c4e96ef4d1c71159ab1` (avoiding hash collisions when indexing patterns in Ruby Hashes or Sets following `Pattern#hash` XOR changes)
- `sha256:0664dc967dea92790848687bf9a0cd0df4c4256198916a238c609e258e44b68c` (Mustermann 4.0 `Mustermann::Match` 0-indexed captures and AST union flattening)
- `sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b` (Sinatra 4 in-process rack-test integration)

This sample addresses a different runtime architecture: `Mustermann::Set` and `Mustermann::Router` route resolution ordering across linear and prefix-trie matchers, automatic transition at the default 50-route threshold, duplicate pattern multi-value grouping, and concurrent thread isolation.

## How the wrong version fails
Silently delivers requests to unintended handlers at runtime when routing tables cross the 50-route threshold or when multi-value handlers execute out of chronological registration order, without raising any error.
csx.json
{"case":{"believed":"A Mustermann pattern set matches routes in FIFO registration order, preserving chronological evaluation across both linear and trie matcher modes regardless of route volume.","caseId":"case:sha256:e2b59f90ae0a04d5f10d2155ad8e2950d67a4d387a1f1668c9771c99d14e3761","contract":["assert linear mode matches routes in FIFO insertion order, whereas trie mode prioritizes static segments over generic captures, inverting route resolution precedence","assert crossing the default 50-route threshold dynamically re-compiles the set from linear to trie mode, flipping route resolution precedence","assert interleaved multi-value registrations on duplicate patterns group together in linear mode and prioritize static routes in trie mode, disrupting chronological insertion order","assert configuring strict_order: true restores exact chronological registration order across both first-match and all-matches in trie mode","assert Mustermann::Router dispatches concurrent multi-threaded requests safely without cross-thread state leakage in Rack environment matches","assert mutating extracted route parameters does not corrupt subsequent or concurrent params calls on the same pattern instance"],"goal":"Handle Mustermann::Set and Mustermann::Router route precedence inversion between linear and trie matching, multi-value duplicate pattern grouping, and concurrent thread isolation","kind":"HOW","packages":["pkg:gem/mustermann@4.0.0"],"schemaVersion":1,"symbols":["Mustermann::Set","Mustermann::Set#match","Mustermann::Set#match_all","Mustermann::Set#add","Mustermann::Router","Mustermann::Router#call","Mustermann::Pattern#params"]},"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/mustermann@4.0.0"],"schemaVersion":1,"symbols":["Mustermann::Set","Mustermann::Set#match","Mustermann::Set#match_all","Mustermann::Set#add","Mustermann::Router","Mustermann::Router#call","Mustermann::Pattern#params"],"verifierAdapter":"rubygems@1"}
src/routing_service.rb
# frozen_string_literal: true

require "mustermann"
require "mustermann/set"
require "mustermann/router"

module RoutingService
  # Creates a route set configured for specific matching semantics
  def self.build_set(strict_order: false, use_trie: 50, use_cache: true)
    Mustermann::Set.new(strict_order: strict_order, use_trie: use_trie, use_cache: use_cache)
  end

  # Creates a Rack-compatible router
  def self.build_router(&block)
    Mustermann::Router.new(&block)
  end
end
test/contract.rb
# frozen_string_literal: true

require "minitest/autorun"
require "mustermann"
require "mustermann/set"
require "mustermann/router"
require_relative "../src/routing_service"

class MustermannOrderingAndConcurrencyContractTest < Minitest::Test
  def test_linear_vs_trie_precedence_inversion
    # Linear mode (< 50 routes, use_trie: false) matches FIFO in registration order:
    # A generic wildcard registered before a static route intercepts the matching URL.
    linear_set = RoutingService.build_set(use_trie: false)
    linear_set.add("/:category", :dynamic_category)
    linear_set.add("/status", :static_status)

    assert_equal :dynamic_category, linear_set.match("/status").value
    assert_equal "status", linear_set.match("/status").params["category"]

    # Trie mode (use_trie: true) compiles into a prefix tree prioritizing static segments
    # over wildcard parameters regardless of registration order.
    trie_set = RoutingService.build_set(use_trie: true)
    trie_set.add("/:category", :dynamic_category)
    trie_set.add("/status", :static_status)

    assert_equal :static_status, trie_set.match("/status").value
    assert_empty trie_set.match("/status").params
  end

  def test_dynamic_threshold_auto_switch_flips_precedence
    # By default, use_trie is set to 50. Below 50 routes, linear matching is active.
    set = RoutingService.build_set(use_trie: 50)
    set.add("/:category", :dynamic_category)
    set.add("/status", :static_status)

    assert_equal :dynamic_category, set.match("/status").value

    # Adding routes to cross the 50-route threshold triggers internal trie re-compilation
    50.times { |i| set.add("/extra_route_#{i}", :extra) }

    # The same pattern set now resolves /status via trie matching, flipping to static_status
    assert_equal :static_status, set.match("/status").value
  end

  def test_interleaved_multivalue_registration_order_disruption
    # In linear mode without strict_order, adding multiple values to the same pattern
    # groups all values for that pattern together in @mapping, disrupting insertion order.
    linear = RoutingService.build_set(use_trie: false)
    linear.add("/:path", :handler_one)
    linear.add("/status", :handler_two)
    linear.add("/:path", :handler_three)

    # :handler_three executes before :handler_two despite being registered later
    assert_equal %i[handler_one handler_three handler_two], linear.match_all("/status").map(&:value)

    # In trie mode without strict_order, static segment matches precede dynamic matches
    trie = RoutingService.build_set(use_trie: true)
    trie.add("/:path", :handler_one)
    trie.add("/status", :handler_two)
    trie.add("/:path", :handler_three)

    assert_equal %i[handler_two handler_one handler_three], trie.match_all("/status").map(&:value)
  end

  def test_strict_order_restores_chronological_ordering
    # Enabling strict_order: true preserves exact insertion order across all matches
    strict = RoutingService.build_set(use_trie: true, strict_order: true)
    strict.add("/:path", :handler_one)
    strict.add("/status", :handler_two)
    strict.add("/:path", :handler_three)

    assert_equal :handler_one, strict.match("/status").value
    assert_equal %i[handler_one handler_two handler_three], strict.match_all("/status").map(&:value)
  end

  def test_concurrent_router_thread_isolation
    router = RoutingService.build_router do
      get "/api/v1/users/:id" do |env|
        match = env["mustermann.match"]
        [200, { "content-type" => "text/plain" }, ["user:#{match[:id]}"]]
      end

      get "/api/v1/posts/:slug" do |env|
        match = env["mustermann.match"]
        [200, { "content-type" => "text/plain" }, ["post:#{match[:slug]}"]]
      end

      get "/api/v1/status" do |_env|
        [200, { "content-type" => "text/plain" }, ["healthy"]]
      end
    end

    errors = []
    threads = 12.times.map do |thread_id|
      Thread.new do
        40.times do |iter|
          user_id = "u_#{thread_id}_#{iter}"
          res_user = router.call({ "REQUEST_METHOD" => "GET", "PATH_INFO" => "/api/v1/users/#{user_id}" })
          errors << "user mismatch in thread #{thread_id}" unless res_user[2] == ["user:#{user_id}"]

          slug = "post_#{thread_id}_#{iter}"
          res_post = router.call({ "REQUEST_METHOD" => "GET", "PATH_INFO" => "/api/v1/posts/#{slug}" })
          errors << "post mismatch in thread #{thread_id}" unless res_post[2] == ["post:#{slug}"]

          res_status = router.call({ "REQUEST_METHOD" => "GET", "PATH_INFO" => "/api/v1/status" })
          errors << "status mismatch in thread #{thread_id}" unless res_status[2] == ["healthy"]
        end
      end
    end

    threads.each(&:join)
    assert_empty errors
  end

  def test_params_isolation_and_reentrancy
    pattern = Mustermann.new("/orgs/:org/repos/:repo")
    first_params = pattern.params("/orgs/rails/repos/rails")
    assert_equal({ "org" => "rails", "repo" => "rails" }, first_params)

    # Mutating returned hash
    first_params["org"] = "tampered"
    first_params["repo"] = "tampered"
    first_params["injected"] = "bad"

    # Subsequent or nested params call produces fresh unaffected hash
    fresh_params = pattern.params("/orgs/rails/repos/rails")
    assert_equal({ "org" => "rails", "repo" => "rails" }, fresh_params)
    refute_includes fresh_params, "injected"
  end
end

Ursprungs-Seeder

csx-seed