diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..e46e2ec --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,19 @@ +name: Test +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + services: + redis: + image: redis:7-alpine + ports: ['6379:6379'] + options: --health-cmd "redis-cli ping" --health-interval 5s --health-retries 5 + env: + SIDEKIQ_FIBER_TEST_REDIS_URL: redis://127.0.0.1:6379/0 + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '3.4.10' + bundler-cache: true + - run: bundle exec rspec diff --git a/Gemfile b/Gemfile index 6899169..c1a95f7 100644 --- a/Gemfile +++ b/Gemfile @@ -2,5 +2,4 @@ source "https://rubygems.org" gemspec -gem "sidekiq", ">= 7.0" -gem "async", ">= 2.0" +gem "excon", "= 0.112.0" diff --git a/README.md b/README.md index 6a2f541..34e592f 100644 --- a/README.md +++ b/README.md @@ -1,188 +1,69 @@ -# sidekiq-fiber +# sidekiq-fiber +Experimental capsule-level fiber execution for Sidekiq. Not yet validated for +production. No application performance claims follow from the standalone +`bench/throughput.rb` example: it bypasses Sidekiq, Redis, and Rails. -Fiber-based concurrency for IO-bound Sidekiq jobs. +## Supported runtime -If your jobs mostly wait on network calls — LLM APIs, HTTP requests, S3 — threads are the wrong tool. A thread blocks completely during IO. With 20 threads and 1500 queued jobs, you're processing 20 at a time and the rest sit idle. +CRuby 3.4, Sidekiq 8.0.10, Async 2.45.0, io-event 1.22.0, and +connection_pool 2.5.5. When present, ActiveRecord must be 8.1.3.1 and +Sidekiq Pro/Enterprise must both be 8.0.3. Compatibility checks reject other +loaded versions; commercial integration requires separate private tests. -This gem helps you solve this by using Ruby Fibers which take up a few kb per fiber and can help process 100s of fibers per thread. - -## How it works - -Normal Sidekiq: -``` -Thread → fetch job → perform (blocks on IO) → fetch next -``` - -With sidekiq-fiber: -``` -Thread → fetch job 1 → schedule as fiber → hits IO, suspends - → fetch job 2 → schedule as fiber → hits IO, suspends - → fetch job 3 → schedule as fiber → running - → job 1 resumes (IO done) → completes → fetch job 4 -``` - -One thread. Many concurrent fibers. No blocking. - -## Requirements - -- Ruby 3.2+ -- Sidekiq 7.0+ -- Jobs must use fiber-aware IO clients (see table below) - -## Installation +Require the gem only in the dedicated worker process. Rails applications must +set `config.active_support.isolation_level = :fiber` before initialization. +The gem does not patch ActiveRecord connection ownership. ```ruby -gem "sidekiq-fiber" -``` - -## Usage - -**1. Configure a dedicated fiber capsule** - -```ruby -# config/initializers/sidekiq.rb require "sidekiq-fiber" Sidekiq.configure_server do |config| - config[:fiber_concurrency] = 50 # max concurrent fibers per thread - - config.capsule("fiber") do |cap| - cap.concurrency = 20 # threads - cap.queues = ["llm_jobs", "api_calls"] - cap.processor_class = Sidekiq::Fiber::Processor - end -end -``` - -**2. Opt in per job** - -```ruby -class MyLlmJob - include Sidekiq::Worker - include Sidekiq::Fiber::Worker # opt in — you are responsible for fiber-safe IO - - def perform(id) - # Net::HTTP is fiber-aware in Ruby 3.2+ — yields during socket wait - response = Net::HTTP.get(URI("https://api.openai.com/...")) - process(response) + config.capsule("front") do |capsule| + capsule.queues = %w[front front_bulk] + capsule.concurrency = 16 + Sidekiq::Fiber.configure(capsule, scheduler_threads: 1) end end ``` -**3. Add the Web UI tab (optional)** +Capsule concurrency is the total number of in-flight jobs, not a multiplier +per scheduler thread. HTTP and database pools remain separately bounded. +Fetch follows the configured fetcher's queue priority; it does not preempt +running jobs. Every job on a selected capsule runs in a fiber, without markers +or fallback. Other capsules keep Sidekiq's normal manager. -```ruby -# config/routes.rb -require "sidekiq/fiber/web" - -Sidekiq::Web.configure do |config| - config.register Sidekiq::Fiber::Web, - name: "sidekiq-fiber", - tab: "Fibers", - index: "fiber-stats", - root_dir: Gem.loaded_specs["sidekiq-fiber"].gem_dir -end -``` +## Execution contract -## Fiber-safe IO +Each runner owns a fresh job fiber and an upstream processor instance. Sidekiq +retains middleware, retry, dead-job handling, and acknowledgment. Job bodies +must use scheduler-compatible I/O and must join any child work. Child fibers +inherit capsule and Redis routing, never checked-out connections. -You're responsible for using fiber-aware clients. Blocking IO freezes the whole thread. +Ruby's `Fiber#raise` does not honor `Thread.handle_interrupt`. Shutdown is +therefore injected only into job bodies, never fetch, middleware accounting, +retry handling, or acknowledgment. ConnectionPool checkout/checkin are also +protected. Jobs must not rely on additional thread interrupt masks. -| Client | Fiber-aware in Ruby 3.2? | -|---|---| -| `Net::HTTP` | ✅ Yes — via fiber scheduler | -| `Faraday` (net-http adapter) | ✅ Yes | -| `HTTParty` | ✅ Yes (uses Net::HTTP) | -| `ActiveRecord` queries | ✅ Yes — with our connection pool patch | -| `Typhoeus` | ❌ No — uses libcurl | +Quiet stops fetching. At the deadline, the supervisor invokes the configured +fetcher's recovery, requests interruption at safe job boundaries, and allows +up to three seconds for cleanup. The owning Sidekiq process must then exit; +this is not an in-process restart interface. Delivery remains at least once. -### ActiveRecord connection pool +Standard Sidekiq work/busy and processed/failed reporting use distinct +process-qualified runner identities and Sidekiq's periodic publication. There +is no custom dashboard or per-job custom Redis statistics. -sidekiq-fiber patches `ActiveRecord::ConnectionPool` to use `Fiber.current` as the connection cache key instead of `Thread.current`. Each fiber gets its own connection slot. +## Verification -Keep this in mind when sizing your DB pool: - -``` -max DB connections = threads × fiber_concurrency +```sh +bundle exec rspec ``` -If your DB pool is 100 and you have 20 threads, set `fiber_concurrency` to 5 or lower. The Web UI will warn you when you're over this limit - -## Capacity planning - -``` -max concurrent fibers = capsule.concurrency × fiber_concurrency -max DB connections = capsule.concurrency × fiber_concurrency -peak memory (HTTP) ≈ max concurrent fibers × ~50KB per connection -``` - -## Benchmark - -Measured on Ruby 3.2.2, MacBook Air M2. -**Thread model:** 20 threads, one job at a time (max 20 concurrent) -**Fiber model:** 20 threads × 50 fibers (max 1000 concurrent) - -### Part 1 — sleep() simulation (fixed latency) - -`sleep()` is fiber-scheduler aware in Ruby 3.2. In a thread it blocks completely. In a fiber it yields, so other fibers can run. Results are clean and predictable here. - -| Scenario | Jobs | IO wait | Threads | Fibers | Speedup | -|---|---|---|---|---|---| -| Light | 50 | 0.1s | 0.32s | 0.10s | **3.0x** | -| Medium | 200 | 0.5s | 5.04s | 0.51s | **9.9x** | -| Heavy | 500 | 1.0s | 25.10s | 1.02s | **24.7x** | - -### Part 2 — Real HTTP calls (variable latency) - -Jobs make actual `Net::HTTP` requests to a local WEBrick server that responds after a random delay. Real socket IO. `Net::HTTP` in Ruby 3.2 hooks into the fiber scheduler — the socket read suspends the fiber and resumes it when data arrives. - -| Scenario | Jobs | Latency range | Threads | Fibers | Speedup | -|---|---|---|---|---|---| -| Fast API | 50 | 0.05s–0.3s | 0.63s | 0.31s | **2.1x** | -| Medium API | 100 | 0.5s–2.0s | 7.64s | 2.06s | **3.7x** | -| LLM-like | 50 | 2.0s–8.0s | 16.40s | 7.84s | **2.1x** | -| **Real burst** | **1500** | **0.5s–2.0s** | **95.46s** | **17.44s** | **5.5x** | - -### Inference - -**Speedup scales with job_count / thread_count.** The more jobs you have relative to threads, the more fibers help. The Heavy scenario hits 24.7x because 500 jobs / 20 threads = 25 serial batches — fibers collapse that to 1. (Best usecase) - -**The LLM-like scenario (50 jobs, 2-8s) is only 2.1x** because with 50 jobs and 1000 fiber slots, all 50 start immediately. Both approaches then wait for the slowest request (~8s). Fibers don't make requests faster — they stop threads from sitting idle during IO. - -**The Real burst scenario (1500 jobs, 0.5-2.0s) is the honest one** — closest to high traffic production LLM workloads. Threads: 95s. Fibers: 17s. Threads process 20 at a time across 75 serial batches. Fibers process up to 1000 across 2 batches. - -**Memory:** the Real burst run peaked at +52.9MB for fibers vs +3.3MB for threads. 1000 concurrent HTTP connections means 1000 open sockets with buffers and response objects in memory. Set `fiber_concurrency` based on your memory budget, not just throughput. - -To reproduce: - -```bash -bundle exec ruby bench/throughput.rb -``` - -## Web UI - -The optional "Fibers" tab shows: - -- **Global health** — active fibers, semaphore utilization, DB connection warning -- **Per-thread breakdown** — semaphore fill, throughput, blocking IO detection -- **In-flight fibers** — long-running fiber alerts (> 30s) - -**Blocking IO detection:** if a thread has active fibers but zero completions for > 60 seconds, the UI flags it. This catches jobs accidentally using non-fiber-aware clients that freeze the whole thread. - -## Design decisions - -**Why a dedicated capsule, not mixed with normal jobs?** -Fiber and non-fiber jobs on the same processor share thread-level interrupt handling and connection pool state in ways that are subtle to reason about. A dedicated capsule makes the boundary structural and hence avoid accidental issues. - -**Why the `async` gem for the event loop?** -The fiber scheduler interface in Ruby 3.2 has edge cases around IO readiness, timeout handling, and signal interrupts. `async` is battle tested and I didn't want to reinvent the wheel for this. - -**Why patch `connection_cache_key` instead of a custom pool?** -The patch is 3 lines and uses the pool's designed extension point. A custom pool would duplicate hundreds of lines of connection management logic and diverge from ActiveRecord's battle-tested implementation. - -**Why opt-in per job instead of per queue?** -Writing fiber-safe code requires deliberate choices about which IO clients you use. Making it explicit at the job class level enforces that — a queue declaration hides it. If you use a blocking client inside a fiber job, the whole thread stalls silently. Explicit opt-in helps the developers make accidental mistakes. +Boundary tests cover capacity, acknowledgment, protected shutdown phases, +connection handoff, and recovery. Before deployment, additionally verify real +Redis/SuperFetch, Rails transactions and executor cleanup, commercial +middleware, HTTPS timeouts, and equal-resource workload benchmarks. ## License diff --git a/demo/Gemfile b/demo/Gemfile index 029ab72..c1b3c91 100644 --- a/demo/Gemfile +++ b/demo/Gemfile @@ -1,9 +1,7 @@ source "https://rubygems.org" -ruby "3.2.2" +ruby "3.4.10" -gem "sidekiq", "~> 7.0" -gem "async", ">= 2.0" gem "sidekiq-fiber", path: ".." gem "puma" gem "rack" diff --git a/demo/config.ru b/demo/config.ru index 3a67989..b75ed71 100644 --- a/demo/config.ru +++ b/demo/config.ru @@ -1,21 +1,11 @@ require "sidekiq" require "sidekiq/web" -require "sidekiq-fiber" -require "sidekiq/fiber/web" require "rack/session" Sidekiq.configure_client do |config| config.redis = { url: "redis://localhost:6379/0" } end -Sidekiq::Web.configure do |config| - config.register Sidekiq::Fiber::Web, - name: "sidekiq-fiber", - tab: "Fibers", - index: "fiber-stats", - root_dir: File.expand_path("../web", __dir__) -end - use Rack::Session::Cookie, secret: File.read(".session.key").strip, same_site: true, diff --git a/demo/jobs.rb b/demo/jobs.rb index cd29e18..b463500 100644 --- a/demo/jobs.rb +++ b/demo/jobs.rb @@ -7,7 +7,6 @@ # Uses sleep() which is fiber-aware in Ruby 3.2+. class FakeLlmJob include Sidekiq::Job - include Sidekiq::Fiber::Worker def perform(id, delay) puts "[fiber] job #{id} started (will sleep #{delay}s)" @@ -16,7 +15,7 @@ def perform(id, delay) end end -# A normal job with no fiber opt-in — runs inline on the thread. +# Runs on the processor selected by its queue's capsule. class NormalJob include Sidekiq::Job diff --git a/demo/worker.rb b/demo/worker.rb index c673af1..03214af 100644 --- a/demo/worker.rb +++ b/demo/worker.rb @@ -3,14 +3,11 @@ Sidekiq.configure_server do |config| config.redis = { url: "redis://localhost:6379/0" } - # fiber_concurrency controls max concurrent fibers per thread - config[:fiber_concurrency] = 20 - # dedicated fiber capsule — separate from normal jobs config.capsule("fiber") do |cap| - cap.concurrency = 2 # 2 threads × 20 fibers = 40 concurrent fiber jobs + cap.concurrency = 16 cap.queues = ["fiber"] - cap.processor_class = Sidekiq::Fiber::Processor + Sidekiq::Fiber.configure(cap, scheduler_threads: 1) end end diff --git a/lib/sidekiq-fiber.rb b/lib/sidekiq-fiber.rb index e4ba315..06875b5 100644 --- a/lib/sidekiq-fiber.rb +++ b/lib/sidekiq-fiber.rb @@ -2,7 +2,6 @@ require "async" require_relative "sidekiq/fiber/version" -require_relative "sidekiq/fiber/worker" -require_relative "sidekiq/fiber/processor" -require_relative "sidekiq/fiber/connection_pool_patch" -require_relative "sidekiq/fiber/manager_patch" +require_relative "sidekiq/fiber/supervisor" +require_relative "sidekiq/fiber/routing" +require_relative "sidekiq/fiber/compatibility" diff --git a/lib/sidekiq/fiber/compatibility.rb b/lib/sidekiq/fiber/compatibility.rb new file mode 100644 index 0000000..8db4217 --- /dev/null +++ b/lib/sidekiq/fiber/compatibility.rb @@ -0,0 +1,63 @@ +require "sidekiq/manager" +require "sidekiq/capsule" + +module Sidekiq + module Fiber + module Compatibility + VERSIONS = { + "sidekiq" => "8.0.10", + "async" => "2.45.0", + "io-event" => "1.22.0", + "connection_pool" => "2.5.5", + "activerecord" => "8.1.3.1", + "sidekiq-pro" => "8.0.3", + "sidekiq-ent" => "8.0.3" + }.freeze + + def self.verify! + unless RUBY_ENGINE == "ruby" && RUBY_VERSION.start_with?("3.4.") + raise ArgumentError, "sidekiq-fiber requires CRuby 3.4" + end + + VERSIONS.each do |name, version| + actual = Gem.loaded_specs[name]&.version + next unless actual + next if actual.to_s == version + + raise ArgumentError, "sidekiq-fiber requires #{name} #{version}; loaded #{actual}" + end + + if defined?(ActiveSupport::IsolatedExecutionState) && ActiveSupport::IsolatedExecutionState.isolation_level != :fiber + raise ArgumentError, "sidekiq-fiber requires config.active_support.isolation_level = :fiber" + end + end + + module Capsule + attr_accessor :fiber_scheduler_threads + end + + # Sidekiq 8.0.10 has no manager factory hook. Intercept construction + # before allocating stock processors, leaving normal capsules untouched. + module ManagerFactory + def new(capsule, ...) + return super unless capsule.fiber_scheduler_threads + + Compatibility.verify! + Supervisor.new(capsule, scheduler_threads: capsule.fiber_scheduler_threads) + end + end + end + + def self.configure(capsule, scheduler_threads: 1) + Compatibility.verify! + unless scheduler_threads.is_a?(Integer) && scheduler_threads.positive? && scheduler_threads <= capsule.concurrency + raise ArgumentError, "scheduler_threads must be between 1 and capsule concurrency" + end + + capsule.fiber_scheduler_threads = scheduler_threads + end + end +end + +Sidekiq::Capsule.include(Sidekiq::Fiber::Compatibility::Capsule) +Sidekiq::Manager.singleton_class.prepend(Sidekiq::Fiber::Compatibility::ManagerFactory) diff --git a/lib/sidekiq/fiber/connection_pool_patch.rb b/lib/sidekiq/fiber/connection_pool_patch.rb deleted file mode 100644 index 3af9187..0000000 --- a/lib/sidekiq/fiber/connection_pool_patch.rb +++ /dev/null @@ -1,27 +0,0 @@ -module Sidekiq - module Fiber - # Patches ActiveRecord's connection pool to use Fiber.current as the - # cache key instead of Thread.current. - # - # Without this patch, all fibers on the same thread share one connection - # slot — causing either connection sharing (data corruption) or unbounded - # connection checkout (one per fiber). - # - # With this patch, each fiber gets its own connection slot. The developer - # must still bound fiber concurrency via fiber_concurrency config to avoid - # exhausting the database connection limit. - # - # Only applied when ActiveRecord is present. - module ConnectionPoolPatch - def connection_cache_key(_thread) - ::Fiber.current - end - end - end -end - -if defined?(ActiveRecord::ConnectionAdapters::ConnectionPool) - ActiveRecord::ConnectionAdapters::ConnectionPool.prepend( - Sidekiq::Fiber::ConnectionPoolPatch - ) -end diff --git a/lib/sidekiq/fiber/manager_patch.rb b/lib/sidekiq/fiber/manager_patch.rb deleted file mode 100644 index 290cd32..0000000 --- a/lib/sidekiq/fiber/manager_patch.rb +++ /dev/null @@ -1,46 +0,0 @@ -require "sidekiq/manager" -require "sidekiq/capsule" - -module Sidekiq - module Fiber - # Extends Sidekiq::Capsule with a per-capsule processor_class attribute. - # We can't use capsule[:processor_class] because capsule delegates [] to - # the global config — setting it would affect all capsules. - module CapsulePatch - def processor_class=(klass) - @processor_class = klass - end - - def processor_class - @processor_class - end - end - - # Patches Sidekiq::Manager to respect the per-capsule processor_class. - module ManagerPatch - def initialize(capsule) - super - klass = capsule.respond_to?(:processor_class) && capsule.processor_class - @processor_class = klass || Sidekiq::Processor - @workers.clear - @count.times do - @workers << @processor_class.new(@config, &method(:processor_result)) - end - end - - def processor_result(processor, reason = nil) - @plock.synchronize do - @workers.delete(processor) - unless @done - p = @processor_class.new(@config, &method(:processor_result)) - @workers << p - p.start - end - end - end - end - end -end - -Sidekiq::Capsule.prepend(Sidekiq::Fiber::CapsulePatch) -Sidekiq::Manager.prepend(Sidekiq::Fiber::ManagerPatch) diff --git a/lib/sidekiq/fiber/processor.rb b/lib/sidekiq/fiber/processor.rb deleted file mode 100644 index 2055487..0000000 --- a/lib/sidekiq/fiber/processor.rb +++ /dev/null @@ -1,155 +0,0 @@ -require "async" -require "sidekiq/processor" -require_relative "stats" - -module Sidekiq - module Fiber - # A Sidekiq::Processor replacement that runs fiber-aware jobs as fibers - # inside a per-thread Async event loop. - # - # One event loop runs per thread. Each fiber job is scheduled as a child - # task inside that loop. The thread fetches jobs continuously, scheduling - # each as a fiber without waiting for previous fibers to finish. - # - # A semaphore bounds concurrent fibers per thread. This directly controls - # how many DB connections this processor can consume: - # max_connections = threads * fiber_concurrency - # - # On normal shutdown (@done = true), the fetch loop exits but the event - # loop waits for all in-flight fibers to complete before returning. - # - # On hard shutdown (Sidekiq::Shutdown raised), in-flight fibers that have - # not completed are requeued — identical to Sidekiq's default behaviour. - class Processor < Sidekiq::Processor - def initialize(capsule, &block) - super - @fiber_concurrency = capsule.config[:fiber_concurrency] || 100 - @active_fibers = 0 - @active_fibers_lock = Mutex.new - stats_pool = capsule.config.new_redis_pool(@fiber_concurrency, "sidekiq-fiber-stats") - @stats = Stats.new(stats_pool) - end - - private - - # Replaces the default run loop with a fixed pool of fiber workers. - # - # We spawn exactly fiber_concurrency persistent fibers. Each fiber owns - # its own fetch-process loop: it fetches one job, processes it, then - # fetches the next. This means jobs stay in Redis until there is actual - # capacity — we never drain the queue into memory ahead of processing. - # - # The previous design (single fetch loop + semaphore) fetched unboundedly - # fast, pulling all queued jobs into pending async tasks before any fiber - # started working. With 5000 jobs enqueued that meant 5000 tasks created - # instantly, all invisible to the Sidekiq UI. - def run - Thread.current[:sidekiq_capsule] = @capsule - - thread_id = Thread.current.object_id.to_s - - @stats.register_thread(thread_id: thread_id, fiber_concurrency: @fiber_concurrency) - - Async do |task| - workers = @fiber_concurrency.times.map do - task.async do - until @done - uow = fetch - unless uow - task.yield # nothing in queue — yield so other fibers can run - next - end - - klass_name = begin - Sidekiq.load_json(uow.job)["class"] - rescue - nil - end - - is_fiber_job = klass_name && - Object.const_get(klass_name).include?(Sidekiq::Fiber::Worker) - - if is_fiber_job - active = @active_fibers_lock.synchronize { @active_fibers += 1 } - @stats.update_thread_stats( - thread_id: thread_id, - semaphore_size: @fiber_concurrency, - semaphore_acquired: active - ) - process_in_fiber(uow, thread_id: thread_id) - active = @active_fibers_lock.synchronize { @active_fibers -= 1 } - @stats.update_thread_stats( - thread_id: thread_id, - semaphore_size: @fiber_concurrency, - semaphore_acquired: active - ) - else - process(uow) - end - end - end - end - - workers.each(&:wait) - end - - @stats.deregister_thread(thread_id: thread_id) - @callback.call(self) - rescue Sidekiq::Shutdown - @stats.deregister_thread(thread_id: Thread.current.object_id.to_s) - @callback.call(self) - rescue Exception => ex - @stats.deregister_thread(thread_id: Thread.current.object_id.to_s) - @callback.call(self, ex) - end - - # Runs a single job unit of work inside the current fiber. - # Mirrors Sidekiq::Processor#process but with per-fiber ack tracking - # so that hard shutdown can requeue incomplete jobs correctly. - def process_in_fiber(uow, thread_id:) - jobstr = uow.job - queue = uow.queue_name - job_hash = nil - - begin - job_hash = Sidekiq.load_json(jobstr) - rescue => ex - handle_exception(ex, { context: "Invalid JSON for job", jobstr: jobstr }) - return uow.acknowledge - end - - jid = job_hash["jid"] - job_class = job_hash["class"] - ack = false - - @stats.fiber_started(jid: jid, job_class: job_class, thread_id: thread_id) - - begin - dispatch(job_hash, queue, jobstr) do |instance| - @capsule.config.server_middleware.invoke(instance, job_hash, queue) do - execute_job(instance, job_hash["args"]) - end - end - ack = true - rescue Sidekiq::Shutdown - # Fiber was stopped before job completed. Do not acknowledge. - # Job will be requeued by the capsule fetcher on shutdown. - rescue Sidekiq::JobRetry::Skip => s - ack = true - raise s - rescue Sidekiq::JobRetry::Handled => h - ack = true - e = h.cause || h - handle_exception(e, { context: "Job raised exception", job: job_hash }) - raise e - rescue Exception => ex - handle_exception(ex, { context: "Internal exception!", job: job_hash, jobstr: jobstr }) - raise ex - ensure - @stats.fiber_completed(jid: jid, thread_id: thread_id) - uow.acknowledge if ack - end - end - end - end -end diff --git a/lib/sidekiq/fiber/routing.rb b/lib/sidekiq/fiber/routing.rb new file mode 100644 index 0000000..074d94b --- /dev/null +++ b/lib/sidekiq/fiber/routing.rb @@ -0,0 +1,22 @@ +module Sidekiq + module Fiber + # Ruby's inheritable fiber storage carries ownership, not connection leases. + # Sidekiq still reads fiber-local Thread[] routing; copy only that routing + # when a running job creates a child fiber. + module Routing + KEYS = %i[sidekiq_capsule sidekiq_redis_pool sidekiq_client_class].freeze + + def new(*args, **options, &block) + return super unless Runner.current + + routing = KEYS.to_h { |key| [key, Thread.current[key]] } + super(*args, **options) do |*values| + routing.each { |key, value| Thread.current[key] = value } + block.call(*values) + end + end + end + end +end + +::Fiber.singleton_class.prepend(Sidekiq::Fiber::Routing) diff --git a/lib/sidekiq/fiber/runner.rb b/lib/sidekiq/fiber/runner.rb new file mode 100644 index 0000000..1aac36a --- /dev/null +++ b/lib/sidekiq/fiber/runner.rb @@ -0,0 +1,109 @@ +require "sidekiq/processor" +require "connection_pool" +require "delegate" + +module Sidekiq + module Fiber + # Owns one fetched job. Sidekiq still owns dispatch, retry and acknowledgment. + # Only the job body may be interrupted; resource handoff and middleware + # accounting must finish without fiber-raised exceptions. + class Runner < Sidekiq::Processor + attr_reader :outstanding_job + attr_reader :down + + class Receipt < SimpleDelegator + attr_reader :acknowledged + + def acknowledge + super + @acknowledged = true + end + end + + def self.current + ::Fiber[:sidekiq_fiber_runner] + end + + def initialize(capsule, id:, down: false) + super(capsule) {} + @id = id + @down = down + @protected = 0 + @executing = false + end + + def run_once + return if stopping? + + @fiber = ::Fiber.current + ::Fiber[:sidekiq_fiber_runner] = self + Thread.current[:sidekiq_capsule] = capsule + Thread.current[:sidekiq_tid] = @id + process_one + ensure + ::Fiber[:sidekiq_fiber_runner] = nil + Thread.current[:sidekiq_capsule] = nil + Thread.current[:sidekiq_tid] = nil + Thread.current["sfuow"] = nil + @fiber = nil + end + + def interrupt + return false if @interrupted + return false unless @executing && @protected.zero? && @fiber&.alive? + + @interrupted = true + ::Fiber.scheduler.raise(@fiber, Sidekiq::Shutdown) + true + end + + def protect + @protected += 1 + yield + ensure + @protected -= 1 + end + + private + + def process(work) + @outstanding_job = work + receipt = Receipt.new(work) + super(receipt) + ensure + @outstanding_job = nil if receipt&.acknowledged + end + + def tid + @id + end + + def execute_job(instance, args) + @executing = true + super + ensure + @executing = false + end + end + + # ConnectionPool's Thread.handle_interrupt guards do not cover Fiber#raise. + # Defer shutdown across checkout/checkin without changing non-fiber callers. + module PoolHandoff + def checkout(...) + runner = Runner.current + return super unless runner + + runner.protect { super } + end + + def checkin(...) + runner = Runner.current + return super unless runner + + runner.protect { super } + end + end + end +end + +ConnectionPool.prepend(Sidekiq::Fiber::PoolHandoff) diff --git a/lib/sidekiq/fiber/stats.rb b/lib/sidekiq/fiber/stats.rb deleted file mode 100644 index c05f8f7..0000000 --- a/lib/sidekiq/fiber/stats.rb +++ /dev/null @@ -1,136 +0,0 @@ -module Sidekiq - module Fiber - # Writes fiber execution stats to Redis. - # Called from the processor at key lifecycle points: - # - fiber starts → record in-flight fiber - # - fiber completes → remove in-flight, increment completed counter - # - semaphore changes → update utilization - # - # All keys are namespaced under "sidekiq-fiber:" and expire automatically - # so stale data doesn't accumulate after a worker restarts. - class Stats - NAMESPACE = "sidekiq-fiber" - FIBER_TTL = 600 # 10 minutes — long-running fiber alert threshold - THREAD_TTL = 120 # 2 minutes — thread stats expire if worker dies - GLOBAL_TTL = 120 - - def initialize(redis_pool) - @redis = redis_pool - end - - # Called when a fiber starts executing a job. - def fiber_started(jid:, job_class:, thread_id:) - safe_redis do |conn| - key = fiber_key(jid) - conn.hset(key, - "job_class", job_class, - "thread_id", thread_id, - "started_at", Time.now.to_f - ) - conn.expire(key, FIBER_TTL) - end - end - - def fiber_completed(jid:, thread_id:) - safe_redis do |conn| - conn.del(fiber_key(jid)) - conn.hincrby(thread_key(thread_id), "completed_total", 1) - conn.hset(thread_key(thread_id), "last_completed_at", Time.now.to_f) - conn.expire(thread_key(thread_id), THREAD_TTL) - end - end - - def update_thread_stats(thread_id:, semaphore_size:, semaphore_acquired:) - safe_redis do |conn| - conn.hset(thread_key(thread_id), - "semaphore_size", semaphore_size, - "semaphore_acquired", semaphore_acquired - ) - conn.expire(thread_key(thread_id), THREAD_TTL) - end - end - - def register_thread(thread_id:, fiber_concurrency:) - safe_redis do |conn| - conn.sadd(threads_index_key, thread_id) - conn.expire(threads_index_key, GLOBAL_TTL) - conn.hset(thread_key(thread_id), - "semaphore_size", fiber_concurrency, - "semaphore_acquired", 0, - "completed_total", 0, - "last_completed_at", "" - ) - conn.expire(thread_key(thread_id), THREAD_TTL) - end - end - - def deregister_thread(thread_id:) - safe_redis do |conn| - conn.srem(threads_index_key, thread_id) - conn.del(thread_key(thread_id)) - end - end - - # ── Readers (used by Web UI) ───────────────────────────────────────────── - - def all_thread_stats - @redis.with do |conn| - thread_ids = conn.smembers(threads_index_key) - thread_ids.filter_map do |tid| - stats = conn.hgetall(thread_key(tid)) - next if stats.empty? - stats.merge("thread_id" => tid) - end - end - end - - def all_in_flight_fibers - @redis.with do |conn| - keys = conn.keys("#{NAMESPACE}:fiber:*") - keys.filter_map do |key| - data = conn.hgetall(key) - next if data.empty? - jid = key.split(":").last - data.merge( - "jid" => jid, - "running_for" => (Time.now.to_f - data["started_at"].to_f).round(1) - ) - end - end - end - - def global_summary - @redis.with do |conn| - thread_ids = conn.smembers(threads_index_key) - total_active = 0 - total_max = 0 - - thread_ids.each do |tid| - stats = conn.hgetall(thread_key(tid)) - total_active += stats["semaphore_acquired"].to_i - total_max += stats["semaphore_size"].to_i - end - - { - thread_count: thread_ids.size, - total_active: total_active, - total_max: total_max - } - end - end - - private - - def safe_redis(&block) - @redis.with(&block) - rescue ConnectionPool::TimeoutError, StandardError - # Stats writes are best-effort. A timeout or Redis blip should never - # propagate into the fiber and fail the job. - end - - def fiber_key(jid) = "#{NAMESPACE}:fiber:#{jid}" - def thread_key(thread_id) = "#{NAMESPACE}:thread:#{thread_id}" - def threads_index_key = "#{NAMESPACE}:threads" - end - end -end diff --git a/lib/sidekiq/fiber/supervisor.rb b/lib/sidekiq/fiber/supervisor.rb new file mode 100644 index 0000000..0ce305b --- /dev/null +++ b/lib/sidekiq/fiber/supervisor.rb @@ -0,0 +1,145 @@ +require "async" +require "set" +require_relative "runner" + +module Sidekiq + module Fiber + # Supervises bounded job runners independently of their scheduler threads. + # A stalled scheduler cannot extend the shutdown deadline. The owning + # Sidekiq process must exit after stop, as with Sidekiq's threaded manager. + class Supervisor + include Sidekiq::Component + + attr_reader :capsule + + def initialize(capsule, scheduler_threads:) + @config = @capsule = capsule + @scheduler_threads = scheduler_threads + @workers = Set.new + @orphaned = [] + @lock = Mutex.new + @threads = [] + @done = false + @hard_shutdown = false + @scheduler_ticks = Array.new(scheduler_threads) { monotonic } + capsule.config.on(:beat) { publish_metrics } + end + + def workers + @lock.synchronize { @workers.dup } + end + + def start + capsule.fetcher + @scheduler_threads.times do |index| + slots = capsule.concurrency / @scheduler_threads + slots += 1 if index < capsule.concurrency % @scheduler_threads + @threads << safe_thread("#{identity}/#{capsule.name}/scheduler-#{index}") do + schedule(index, slots) + end + end + end + + def quiet + @done = true + workers.each(&:terminate) + end + + def stopped? + @done + end + + def stop(deadline) + return if @stopped + + @stopped = true + quiet + join_until(deadline) + + if @threads.any?(&:alive?) + unfinished = @lock.synchronize { @orphaned + @workers.filter_map(&:job) } + capsule.fetcher.bulk_requeue(unfinished.uniq) + @hard_shutdown = true + join_until(monotonic + 3) + elsif !@orphaned.empty? + capsule.fetcher.bulk_requeue(@orphaned) + end + ensure + capsule.stop unless @capsule_stopped + @capsule_stopped = true + end + + private + + def monotonic + ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + end + + def publish_metrics + busy, oldest_tick, unacknowledged = @lock.synchronize do + [@workers.count(&:job), @scheduler_ticks.min, @orphaned.size] + end + logger.info( + event: "sidekiq.fiber.runtime", + capsule: capsule.name, + in_flight: busy, + scheduler_count: @threads.count(&:alive?), + scheduler_lag_ms: ((monotonic - oldest_tick) * 1000).round, + unacknowledged: unacknowledged, + quiet: @done + ) + rescue StandardError + # Telemetry is best-effort and never owns job acknowledgment/recovery. + nil + end + + def join_until(deadline) + @threads.each do |thread| + remaining = deadline - monotonic + thread.join(remaining) if remaining.positive? + end + end + + def schedule(index, slots) + Async do |root| + active = Set.new + loops = slots.times.map do |slot| + root.async do |loop_task| + down = false + until @done + runner = Runner.new(capsule, id: "#{identity}:#{capsule.name}:#{index}:#{slot}", down: down) + @lock.synchronize do + runner.terminate if @done + @workers.add(runner) + end + active.add(runner) + begin + loop_task.async do + runner.run_once + rescue Exception + # The upstream processor has already reported the error. + end.wait + ensure + down = runner.down + active.delete(runner) + @lock.synchronize do + @workers.delete(runner) + @orphaned << runner.outstanding_job if runner.outstanding_job + end + end + loop_task.sleep(0.001) unless @done + end + end + end + + until loops.all?(&:finished?) + @lock.synchronize { @scheduler_ticks[index] = monotonic } + active.each(&:interrupt) if @hard_shutdown + root.sleep(0.01) + end + loops.each(&:wait) + end.wait + end + end + end +end diff --git a/lib/sidekiq/fiber/web.rb b/lib/sidekiq/fiber/web.rb deleted file mode 100644 index bfecc0e..0000000 --- a/lib/sidekiq/fiber/web.rb +++ /dev/null @@ -1,59 +0,0 @@ -require "sidekiq/web" -require_relative "stats" - -module Sidekiq - module Fiber - # Sidekiq Web UI extension for fiber stats. - # - # Registers a "Fibers" tab that shows: - # - Global summary (active fibers, semaphore utilization, DB connection warning) - # - Per-thread breakdown (semaphore fill, throughput, blocking IO detection) - # - In-flight fibers (long-running fiber alert) - # - # Usage in config/routes.rb or rack config: - # - # require "sidekiq/fiber/web" - # Sidekiq::Web.configure do |config| - # config.register Sidekiq::Fiber::Web, - # name: "sidekiq-fiber", - # tab: "Fibers", - # index: "fiber-stats", - # root_dir: File.expand_path("../../../..", __FILE__) - # end - module Web - VIEWS = File.expand_path("../../../web/views", __dir__) - ROOT = File.expand_path("../../../", __dir__) - - def self.registered(app) - app.get "/fiber-stats" do - pool = Sidekiq.default_configuration.redis_pool - stats = Sidekiq::Fiber::Stats.new(pool) - - @global = stats.global_summary - @thread_stats = stats.all_thread_stats.sort_by { |t| t["thread_id"] } - @in_flight = stats.all_in_flight_fibers.sort_by { |f| -f["running_for"].to_f } - - # DB connection warning threshold - @db_pool_size = begin - ActiveRecord::Base.connection_pool.size - rescue - nil - end - - render(:erb, File.read(File.join(VIEWS, "fiber_stats.html.erb"))) - end - - app.get "/fiber-stats/thread/:thread_id" do - pool = Sidekiq.default_configuration.redis_pool - stats = Sidekiq::Fiber::Stats.new(pool) - - thread_id = route_params(:thread_id) - @thread_stats = stats.all_thread_stats.find { |t| t["thread_id"] == thread_id } - @in_flight = stats.all_in_flight_fibers.select { |f| f["thread_id"] == thread_id } - - render(:erb, File.read(File.join(VIEWS, "fiber_thread.html.erb"))) - end - end - end - end -end diff --git a/lib/sidekiq/fiber/worker.rb b/lib/sidekiq/fiber/worker.rb deleted file mode 100644 index 6adeda5..0000000 --- a/lib/sidekiq/fiber/worker.rb +++ /dev/null @@ -1,24 +0,0 @@ -module Sidekiq - module Fiber - # Marker module. Including this in a Sidekiq job class signals to - # SidekiqFiber::Processor that this job should run as a fiber. - # - # The developer is responsible for ensuring all IO inside the job - # uses fiber-aware clients. Blocking IO (e.g. a non-patched HTTP - # client) will block the entire thread, defeating the purpose. - # - # Example: - # - # class MyJob - # include Sidekiq::Worker - # include Sidekiq::Fiber::Worker - # - # def perform(id) - # # only fiber-aware IO here - # Net::HTTP.get(URI("https://api.example.com/#{id}")) - # end - # end - module Worker - end - end -end diff --git a/sidekiq-fiber.gemspec b/sidekiq-fiber.gemspec index 1bdad6f..250f87d 100644 --- a/sidekiq-fiber.gemspec +++ b/sidekiq-fiber.gemspec @@ -14,12 +14,14 @@ Gem::Specification.new do |spec| DESC spec.homepage = "https://github.com/yashdave00/sidekiq-fiber" spec.license = "MIT" - spec.required_ruby_version = ">= 3.0.0" + spec.required_ruby_version = "~> 3.4.0" spec.files = Dir["lib/**/*.rb", "LICENSE", "README.md"] - spec.add_dependency "sidekiq", ">= 7.0" - spec.add_dependency "async", ">= 2.0" + spec.add_dependency "sidekiq", "= 8.0.10" + spec.add_dependency "async", "= 2.45.0" + spec.add_dependency "io-event", "= 1.22.0" + spec.add_dependency "connection_pool", "= 2.5.5" spec.add_development_dependency "rspec", "~> 3.0" end diff --git a/spec/compatibility_spec.rb b/spec/compatibility_spec.rb new file mode 100644 index 0000000..83c42cd --- /dev/null +++ b/spec/compatibility_spec.rb @@ -0,0 +1,27 @@ +require "spec_helper" + +RSpec.describe Sidekiq::Fiber do + let(:config) { Sidekiq::Config.new } + let(:capsule) { config.capsule("front") } + + it "selects fiber execution only for its configured capsule" do + described_class.configure(capsule) + + expect(Sidekiq::Manager.new(capsule)).to be_a(Sidekiq::Fiber::Supervisor) + expect(Sidekiq::Manager.new(config.default_capsule)).to be_a(Sidekiq::Manager) + end + + it "rejects more schedulers than in-flight capacity" do + capsule.concurrency = 2 + + expect { described_class.configure(capsule, scheduler_threads: 3) } + .to raise_error(ArgumentError, /scheduler_threads/) + end + + it "rejects an unsupported dependency before starting a worker" do + allow(Gem.loaded_specs.fetch("async")).to receive(:version).and_return(Gem::Version.new("2.25.0")) + + expect { described_class.configure(capsule) } + .to raise_error(ArgumentError, /requires async 2.45.0/) + end +end diff --git a/spec/execution_boundary_spec.rb b/spec/execution_boundary_spec.rb new file mode 100644 index 0000000..9626e10 --- /dev/null +++ b/spec/execution_boundary_spec.rb @@ -0,0 +1,178 @@ +require "spec_helper" +require "async/queue" +require_relative "support/execution_boundary" + +RSpec.describe Sidekiq::Fiber::Runner do + let(:work) { BoundaryWork.new } + let(:config) do + Sidekiq::Config.new.tap do |config| + config.logger = Logger.new(IO::NULL) + config.error_handlers.clear + end + end + let(:capsule) { Sidekiq::Capsule.new("front", config) } + let(:runner) { described_class.new(capsule, id: "#{Process.pid}:front:1") } + + before do + allow(capsule).to receive(:fetcher).and_return(double(retrieve_work: work)) + BoundaryJob.body = -> {} + BoundaryMiddleware.after_job = -> {} + end + + def interleave + Async do |root| + entered = Async::Queue.new + release = Async::Queue.new + yield root, entered, release + end.wait + end + + it "acknowledges successful jobs through the upstream processor" do + Async { runner.run_once }.wait + expect(work.acknowledged).to be(true) + end + + it "interrupts a running job without acknowledging or reporting a job failure" do + deaths = [] + config.death_handlers << ->(*args) { deaths << args } + + interleave do |root, entered, release| + BoundaryJob.body = -> { entered.enqueue(true); release.dequeue } + running = root.async { runner.run_once } + entered.dequeue + expect(runner.interrupt).to be(true) + running.wait + end + + expect(work.acknowledged).to be_nil + expect(deaths).to be_empty + end + + it "finishes middleware accounting before acknowledgment during shutdown" do + accounted = false + capsule.server_middleware.add(BoundaryMiddleware) + + interleave do |root, entered, release| + BoundaryMiddleware.after_job = lambda do + entered.enqueue(true) + release.dequeue + accounted = true + end + running = root.async { runner.run_once } + entered.dequeue + expect(runner.interrupt).to be(false) + release.enqueue(true) + running.wait + end + + expect(accounted).to be(true) + expect(work.acknowledged).to be(true) + end + + it "does not interrupt cleanup a second time" do + cleaned = false + interleave do |root, entered, release| + BoundaryJob.body = lambda do + begin + entered.enqueue(:running) + release.dequeue + ensure + entered.enqueue(:cleanup) + release.dequeue + cleaned = true + end + end + running = root.async { runner.run_once } + expect(entered.dequeue).to eq(:running) + expect(runner.interrupt).to be(true) + expect(entered.dequeue).to eq(:cleanup) + expect(runner.interrupt).to be(false) + release.enqueue(true) + running.wait + end + + expect(cleaned).to be(true) + expect(work.acknowledged).to be_nil + end + + it "protects connection checkin while discarding a connection" do + interleave do |root, entered, release| + pool = ConnectionPool.new(size: 1) { Object.new } + BoundaryJob.body = lambda do + pool.with do + pool.discard_current_connection do + entered.enqueue(true) + release.dequeue + end + end + end + running = root.async { runner.run_once } + entered.dequeue + expect(runner.interrupt).to be(false) + release.enqueue(true) + running.wait + expect(pool.available).to eq(1) + end + + expect(work.acknowledged).to be(true) + end + + it "finishes acknowledgment during shutdown" do + interleave do |root, entered, release| + work.before_ack = -> { entered.enqueue(true); release.dequeue } + running = root.async { runner.run_once } + entered.dequeue + expect(runner.interrupt).to be(false) + release.enqueue(true) + running.wait + end + + expect(work.acknowledged).to be(true) + end + + it "protects connection checkout and returns the connection after job interruption" do + pool = nil + interleave do |root, entered, release| + pool = ConnectionPool.new(size: 1, timeout: 1) do + entered.enqueue(:creating) + release.dequeue + Object.new + end + BoundaryJob.body = lambda do + pool.with do + entered.enqueue(:using) + release.dequeue + end + end + running = root.async { runner.run_once } + expect(entered.dequeue).to eq(:creating) + expect(runner.interrupt).to be(false) + release.enqueue(true) + expect(entered.dequeue).to eq(:using) + expect(runner.interrupt).to be(true) + running.wait + end + + expect(pool.available).to eq(1) + expect(work.acknowledged).to be_nil + end + + it "returns a fetched job when quiet begins during fetch" do + interleave do |root, entered, release| + allow(capsule.fetcher).to receive(:retrieve_work) do + entered.enqueue(true) + release.dequeue + work + end + running = root.async { runner.run_once } + entered.dequeue + runner.terminate + expect(runner.interrupt).to be(false) + release.enqueue(true) + running.wait + end + + expect(work.requeued).to be(true) + expect(work.acknowledged).to be_nil + end +end diff --git a/spec/https_scheduler_spec.rb b/spec/https_scheduler_spec.rb new file mode 100644 index 0000000..7c71e28 --- /dev/null +++ b/spec/https_scheduler_spec.rb @@ -0,0 +1,96 @@ +require "spec_helper" +require "excon" +require "openssl" +require "socket" + +RSpec.describe "HTTPS scheduler compatibility" do + def tls_server + key = OpenSSL::PKey::RSA.new(2048) + certificate = OpenSSL::X509::Certificate.new + certificate.version = 2 + certificate.serial = 1 + certificate.subject = certificate.issuer = OpenSSL::X509::Name.parse("/CN=localhost") + certificate.public_key = key.public_key + certificate.not_before = Time.now - 60 + certificate.not_after = Time.now + 3600 + certificate.sign(key, OpenSSL::Digest.new("SHA256")) + context = OpenSSL::SSL::SSLContext.new + context.cert = certificate + context.key = key + tcp = TCPServer.new("127.0.0.1", 0) + server = OpenSSL::SSL::SSLServer.new(tcp, context) + requests = Queue.new + replies = Queue.new + sockets = [] + handlers = [] + acceptor = Thread.new do + loop do + socket = server.accept + sockets << socket + handlers << Thread.new(socket) do |connection| + while connection.gets + while (line = connection.gets) && line != "\r\n" + end + requests << true + replies.pop + connection.write("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: keep-alive\r\n\r\nok") + end + rescue IOError, SystemCallError, OpenSSL::SSL::SSLError + nil + end + end + rescue IOError, SystemCallError, OpenSSL::SSL::SSLError + nil + end + yield "https://127.0.0.1:#{tcp.addr[1]}", requests, replies, sockets + ensure + tcp&.close + sockets&.each(&:close) + acceptor&.join(1) + handlers&.each do |handler| + handler.kill if handler.alive? + handler.join + end + end + + it "overlaps HTTPS waits on one thread and reuses exclusive persistent connections" do + tls_server do |url, requests, replies, sockets| + pool = ConnectionPool.new(size: 2) do + Excon.new(url, persistent: true, thread_safe_sockets: false, ssl_verify_peer: false, read_timeout: 5) + end + responses = [] + threads = [] + Async do |root| + clients = 2.times.map do + root.async do + threads << Thread.current.object_id + 2.times do + pool.with { |connection| responses << connection.request(method: :get, path: "/").body } + end + end + end + 2.times do + 2.times { expect(requests.pop(timeout: 5)).to be(true) } + 2.times { replies << true } + end + clients.each(&:wait) + end.wait + + expect(responses).to eq(%w[ok ok ok ok]) + expect(threads.uniq.size).to eq(1) + expect(sockets.size).to eq(2) + pool.shutdown(&:reset) + end + end + + it "raises the existing Excon timeout while the server withholds its response" do + tls_server do |url, _requests, _replies, _sockets| + connection = Excon.new(url, persistent: true, thread_safe_sockets: false, ssl_verify_peer: false, read_timeout: 0.05) + Async do + expect { connection.request(method: :get, path: "/") }.to raise_error(Excon::Errors::Timeout) + end.wait + ensure + connection&.reset + end + end +end diff --git a/spec/redis_lifecycle_spec.rb b/spec/redis_lifecycle_spec.rb new file mode 100644 index 0000000..9b420e4 --- /dev/null +++ b/spec/redis_lifecycle_spec.rb @@ -0,0 +1,110 @@ +require "spec_helper" +require "securerandom" + +class RedisBoundaryJob + include Sidekiq::Job + + class << self + attr_accessor :body + end + + def perform(id) + self.class.body.call(id) + end +end + +RSpec.describe "Redis lifecycle" do + let(:prefix) { "fiber-spec-#{SecureRandom.hex(12)}" } + let(:queues) { ["#{prefix}-front", "#{prefix}-bulk"] } + let(:started) { Queue.new } + let(:release) { Queue.new } + let(:failures) { Queue.new } + let(:payloads) { [] } + let(:config) do + Sidekiq::Config.new.tap do |config| + config.logger = Logger.new(IO::NULL) + config.redis = {url: ENV.fetch("SIDEKIQ_FIBER_TEST_REDIS_URL")} + config.error_handlers.clear + config.error_handlers << ->(_error, context, _config) { failures << context } + end + end + let(:capsule) do + config.capsule("front") do |capsule| + capsule.concurrency = 1 + capsule.queues = queues + Sidekiq::Fiber.configure(capsule) + end + end + let(:manager) { Sidekiq::Manager.new(capsule) } + + before do + skip "set SIDEKIQ_FIBER_TEST_REDIS_URL to an isolated test database" unless ENV["SIDEKIQ_FIBER_TEST_REDIS_URL"] + RedisBoundaryJob.body = ->(id) { started << id } + end + + after do + if ENV["SIDEKIQ_FIBER_TEST_REDIS_URL"] + manager.quiet + 4.times { release << true } + manager.stop(Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5) + config.redis do |redis| + queues.each { |queue| redis.del("queue:#{queue}") } + %w[retry dead].each do |set| + redis.zrange(set, 0, -1).each do |payload| + redis.zrem(set, payload) if payload.include?(prefix) + end + end + end + capsule.local_redis_pool.shutdown(&:close) + config.local_redis_pool.shutdown(&:close) + end + end + + def enqueue(queue, id, retry_job: false) + payload = Sidekiq.dump_json( + "class" => "RedisBoundaryJob", "args" => [id], "jid" => "#{prefix}-#{id}", + "queue" => queue, "retry" => retry_job + ) + payloads << payload + config.redis { |redis| redis.lpush("queue:#{queue}", payload) } + end + + it "fetches front before already queued bulk work" do + enqueue(queues.last, "bulk") + enqueue(queues.first, "front") + manager.start + + expect(started.pop(timeout: 5)).to eq("front") + expect(started.pop(timeout: 5)).to eq("bulk") + end + + it "creates the upstream retry entry after a job failure" do + RedisBoundaryJob.body = ->(_id) { raise "request failed" } + enqueue(queues.first, "retry", retry_job: true) + manager.start + expect(failures.pop(timeout: 5)).to include(context: "Job raised exception") + retries = config.redis { |redis| redis.zrange("retry", 0, -1) } + retry_job = retries.map { |item| Sidekiq.load_json(item) }.find { |item| item["jid"] == "#{prefix}-retry" } + + expect(retry_job).to include("retry_count" => 0, "queue" => queues.first, "error_message" => "request failed") + end + + it "sends malformed payloads to the dead set" do + malformed = "#{prefix}-not-json" + config.redis { |redis| redis.lpush("queue:#{queues.first}", malformed) } + manager.start + expect(failures.pop(timeout: 5)).to include(context: "Invalid JSON for job") + + expect(config.redis { |redis| redis.zrange("dead", 0, -1) }).to include(malformed) + end + + it "requeues a running job at the deadline" do + RedisBoundaryJob.body = ->(id) { started << id; release.pop } + enqueue(queues.first, "interrupted") + manager.start + expect(started.pop(timeout: 5)).to eq("interrupted") + manager.stop(Process.clock_gettime(Process::CLOCK_MONOTONIC)) + + expect(config.redis { |redis| redis.lrange("queue:#{queues.first}", 0, -1) }).to eq(payloads) + end +end diff --git a/spec/routing_spec.rb b/spec/routing_spec.rb new file mode 100644 index 0000000..bb61f83 --- /dev/null +++ b/spec/routing_spec.rb @@ -0,0 +1,37 @@ +require "spec_helper" +require_relative "support/execution_boundary" + +RSpec.describe "Child fiber routing" do + it "inherits capsule and Redis overrides without sharing checked-out connections" do + config = Sidekiq::Config.new + config.logger = Logger.new(IO::NULL) + capsule = Sidekiq::Capsule.new("front", config) + work = BoundaryWork.new + allow(capsule).to receive(:fetcher).and_return(double(retrieve_work: work)) + runner = Sidekiq::Fiber::Runner.new(capsule, id: "#{Process.pid}:front:1") + routed = Object.new + pool = ConnectionPool.new(size: 2) { Object.new } + contexts = [] + connections = [] + BoundaryJob.body = lambda do + Thread.current[:sidekiq_redis_pool] = routed + pool.with do |parent_connection| + connections << parent_connection + Async::Task.current.async do + contexts << Thread.current[:sidekiq_capsule] + contexts << Thread.current[:sidekiq_redis_pool] + pool.with { |child_connection| connections << child_connection } + Thread.current[:sidekiq_redis_pool] = :child_override + end.wait + contexts << Thread.current[:sidekiq_redis_pool] + end + end + + Async { runner.run_once }.wait + + expect(contexts).to eq([capsule, routed, routed]) + expect(connections.uniq.size).to eq(2) + expect(work.acknowledged).to be(true) + expect(Thread.current[:sidekiq_redis_pool]).to be_nil + end +end diff --git a/spec/sidekiq/fiber/connection_pool_patch_spec.rb b/spec/sidekiq/fiber/connection_pool_patch_spec.rb deleted file mode 100644 index 40588cd..0000000 --- a/spec/sidekiq/fiber/connection_pool_patch_spec.rb +++ /dev/null @@ -1,42 +0,0 @@ -require "spec_helper" - -RSpec.describe Sidekiq::Fiber::ConnectionPoolPatch do - context "when ActiveRecord is not present" do - it "does not raise on load" do - expect { require "sidekiq-fiber" }.not_to raise_error - end - end - - context "when ActiveRecord is present" do - before do - # Simulate a minimal ActiveRecord ConnectionPool with the method we patch - stub_const("ActiveRecord::ConnectionAdapters::ConnectionPool", Class.new do - prepend Sidekiq::Fiber::ConnectionPoolPatch - - def connection_cache_key(thread) - thread - end - end) - end - - it "returns Fiber.current as the cache key instead of the thread" do - pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new - - current_fiber = ::Fiber.current - expect(pool.connection_cache_key(Thread.current)).to eq(current_fiber) - end - - it "returns different cache keys for different fibers" do - pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new - - keys = [] - f1 = ::Fiber.new { keys << pool.connection_cache_key(Thread.current) } - f2 = ::Fiber.new { keys << pool.connection_cache_key(Thread.current) } - f1.resume - f2.resume - - expect(keys.size).to eq(2) - expect(keys.uniq.size).to eq(2) - end - end -end diff --git a/spec/sidekiq/fiber/manager_patch_spec.rb b/spec/sidekiq/fiber/manager_patch_spec.rb deleted file mode 100644 index 0a53c41..0000000 --- a/spec/sidekiq/fiber/manager_patch_spec.rb +++ /dev/null @@ -1,39 +0,0 @@ -require "spec_helper" - -RSpec.describe Sidekiq::Fiber::ManagerPatch do - let(:config) do - Sidekiq::Config.new.tap do |c| - c[:concurrency] = 2 - end - end - - context "when no processor_class is set on the capsule" do - it "uses Sidekiq::Processor by default" do - capsule = Sidekiq::Capsule.new("default", config) - manager = Sidekiq::Manager.new(capsule) - - expect(manager.workers).to all(be_a(Sidekiq::Processor)) - end - end - - context "when processor_class is set to Sidekiq::Fiber::Processor" do - it "instantiates the custom processor class" do - capsule = Sidekiq::Capsule.new("fiber", config) - capsule[:processor_class] = Sidekiq::Fiber::Processor - - manager = Sidekiq::Manager.new(capsule) - - expect(manager.workers).to all(be_a(Sidekiq::Fiber::Processor)) - end - - it "creates the correct number of processors" do - capsule = Sidekiq::Capsule.new("fiber", config) - capsule[:processor_class] = Sidekiq::Fiber::Processor - capsule.concurrency = 3 - - manager = Sidekiq::Manager.new(capsule) - - expect(manager.workers.size).to eq(3) - end - end -end diff --git a/spec/sidekiq/fiber/processor_spec.rb b/spec/sidekiq/fiber/processor_spec.rb deleted file mode 100644 index e766b4e..0000000 --- a/spec/sidekiq/fiber/processor_spec.rb +++ /dev/null @@ -1,148 +0,0 @@ -require "spec_helper" - -RSpec.describe Sidekiq::Fiber::Processor do - let(:config) do - Sidekiq::Config.new.tap do |c| - c[:concurrency] = 1 - c[:fiber_concurrency] = 10 - end - end - - let(:capsule) { Sidekiq::Capsule.new("fiber", config) } - - # Minimal unit of work double that tracks whether it was acknowledged - def build_uow(job_class_name, args: []) - job_hash = { "class" => job_class_name, "args" => args, "jid" => SecureRandom.hex(12) } - double("uow", - job: JSON.generate(job_hash), - queue_name: "fiber_test", - acknowledge: true, - requeue: true - ) - end - - describe "fiber job detection" do - let(:fiber_job) do - stub_const("FiberTestJob", Class.new do - include Sidekiq::Job - include Sidekiq::Fiber::Worker - def perform; end - end) - "FiberTestJob" - end - - let(:normal_job) do - stub_const("NormalTestJob", Class.new do - include Sidekiq::Job - def perform; end - end) - "NormalTestJob" - end - - it "identifies fiber jobs correctly" do - klass = Object.const_get(fiber_job) - expect(klass.include?(Sidekiq::Fiber::Worker)).to be true - end - - it "identifies normal jobs correctly" do - klass = Object.const_get(normal_job) - expect(klass.include?(Sidekiq::Fiber::Worker)).to be false - end - end - - describe "semaphore" do - it "initialises with fiber_concurrency from config" do - processor = Sidekiq::Fiber::Processor.new(capsule) {} - # fiber_concurrency is 10 in our config - expect(processor.instance_variable_get(:@fiber_concurrency)).to eq(10) - end - - it "defaults to 100 when fiber_concurrency is not configured" do - bare_config = Sidekiq::Config.new.tap { |c| c[:concurrency] = 1 } - bare_capsule = Sidekiq::Capsule.new("fiber", bare_config) - processor = Sidekiq::Fiber::Processor.new(bare_capsule) {} - expect(processor.instance_variable_get(:@fiber_concurrency)).to eq(100) - end - end - - describe "job acknowledgement" do - it "acknowledges a job that completes successfully" do - stub_const("AckTestJob", Class.new do - include Sidekiq::Job - include Sidekiq::Fiber::Worker - def perform; end - end) - - uow = build_uow("AckTestJob") - processor = Sidekiq::Fiber::Processor.new(capsule) {} - - expect(uow).to receive(:acknowledge) - processor.send(:process_in_fiber, uow, thread_id: "test-thread") - end - - it "does not acknowledge a job that raises before completion" do - stub_const("FailingTestJob", Class.new do - include Sidekiq::Job - include Sidekiq::Fiber::Worker - def perform - raise "boom" - end - end) - - uow = build_uow("FailingTestJob") - processor = Sidekiq::Fiber::Processor.new(capsule) {} - - # Bypass the full retry middleware chain so we see the raw ack behaviour. - # The retry middleware catches errors and re-raises as Handled, which sets - # ack = true. Here we test our processor's own ack logic directly. - allow(processor).to receive(:dispatch).and_yield(FailingTestJob.new) - - expect(uow).not_to receive(:acknowledge) - expect { processor.send(:process_in_fiber, uow, thread_id: "test-thread") }.to raise_error(RuntimeError, "boom") - end - end - - describe "concurrency" do - it "runs multiple fiber jobs concurrently within the semaphore limit" do - execution_order = [] - - # Use a closure over execution_order rather than a class variable - # (class variables are forbidden in anonymous classes at toplevel in Ruby) - order_ref = execution_order - - stub_const("ConcurrentTestJob", Class.new do - include Sidekiq::Job - include Sidekiq::Fiber::Worker - - define_method(:perform) do |id| - order_ref << "start-#{id}" - Async::Task.current.sleep(0.01) - order_ref << "end-#{id}" - end - end) - - uows = (1..3).map { |i| build_uow("ConcurrentTestJob", args: [i]) } - processor = Sidekiq::Fiber::Processor.new(capsule) {} - - Async do |task| - semaphore = Async::Semaphore.new(10) - - tasks = uows.map do |uow| - task.async do - semaphore.acquire { processor.send(:process_in_fiber, uow, thread_id: "test-thread") } - end - end - - tasks.each(&:wait) - end - - starts = execution_order.select { |e| e.start_with?("start") } - ends = execution_order.select { |e| e.start_with?("end") } - - expect(starts.length).to eq(3) - expect(ends.length).to eq(3) - # All three jobs started before any ended — proving concurrent execution - expect(execution_order.index("start-3")).to be < execution_order.index("end-1") - end - end -end diff --git a/spec/sidekiq/fiber/worker_spec.rb b/spec/sidekiq/fiber/worker_spec.rb deleted file mode 100644 index fec44f6..0000000 --- a/spec/sidekiq/fiber/worker_spec.rb +++ /dev/null @@ -1,33 +0,0 @@ -require "spec_helper" - -RSpec.describe Sidekiq::Fiber::Worker do - let(:fiber_job_class) do - Class.new do - include Sidekiq::Job - include Sidekiq::Fiber::Worker - - def perform; end - end - end - - let(:normal_job_class) do - Class.new do - include Sidekiq::Job - - def perform; end - end - end - - it "marks a job class as a fiber worker" do - expect(fiber_job_class.ancestors).to include(Sidekiq::Fiber::Worker) - end - - it "does not affect job classes that do not include it" do - expect(normal_job_class.ancestors).not_to include(Sidekiq::Fiber::Worker) - end - - it "can be detected at runtime via include?" do - expect(fiber_job_class.include?(Sidekiq::Fiber::Worker)).to be true - expect(normal_job_class.include?(Sidekiq::Fiber::Worker)).to be false - end -end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 90ac644..ba5fd76 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,7 +1,4 @@ require "sidekiq-fiber" -require "sidekiq/testing" - -Sidekiq::Testing.fake! RSpec.configure do |config| config.expect_with :rspec do |c| diff --git a/spec/supervisor_boundary_spec.rb b/spec/supervisor_boundary_spec.rb new file mode 100644 index 0000000..bb69bf5 --- /dev/null +++ b/spec/supervisor_boundary_spec.rb @@ -0,0 +1,126 @@ +require "spec_helper" +require_relative "support/execution_boundary" +require_relative "../lib/sidekiq/fiber/supervisor" + +RSpec.describe Sidekiq::Fiber::Supervisor do + let(:config) do + Sidekiq::Config.new.tap do |config| + config.logger = Logger.new(IO::NULL) + config.error_handlers.clear + config.error_handlers << ->(*) {} + end + end + let(:capsule) { Sidekiq::Capsule.new("front", config).tap { |c| c.concurrency = 2 } } + let(:supervisor) { described_class.new(capsule, scheduler_threads: 1) } + let(:entered) { Queue.new } + let(:release) { Queue.new } + let(:pending) { Queue.new } + let(:recovered) { [] } + let(:fetcher) do + Class.new do + define_method(:initialize) { |pending, recovered| @pending, @recovered = pending, recovered } + define_method(:retrieve_work) { @pending.pop(true) rescue nil } + define_method(:bulk_requeue) { |jobs| @recovered.concat(jobs) } + end.new(pending, recovered) + end + + before do + allow(capsule).to receive(:fetcher).and_return(fetcher) + BoundaryJob.body = -> { entered << true; release.pop } + end + + after do + supervisor.quiet + 4.times { release << true } + supervisor.stop(Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5) + end + + it "fetches only its configured capacity and drains already-started jobs" do + jobs = Array.new(3) { BoundaryWork.new } + jobs.each { |job| pending << job } + supervisor.start + 2.times { expect(entered.pop(timeout: 5)).to be(true) } + supervisor.quiet + + expect(pending.size).to eq(1) + expect(Sidekiq::Processor::WORK_STATE.size).to eq(2) + 2.times { release << true } + supervisor.stop(Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5) + + expect(jobs.first(2).map(&:acknowledged)).to eq([true, true]) + expect(jobs.last.acknowledged).to be_nil + expect(recovered).to be_empty + end + + it "recovers every running job at the deadline without acknowledging it" do + jobs = Array.new(2) { BoundaryWork.new } + jobs.each { |job| pending << job } + supervisor.start + 2.times { expect(entered.pop(timeout: 5)).to be(true) } + supervisor.stop(Process.clock_gettime(Process::CLOCK_MONOTONIC)) + + expect(recovered).to contain_exactly(*jobs) + expect(jobs.map(&:acknowledged)).to eq([nil, nil]) + expect(Sidekiq::Processor::WORK_STATE.size).to eq(0) + end + + it "continues processing after a job raises outside StandardError" do + capsule.concurrency = 1 + calls = 0 + BoundaryJob.body = lambda do + calls += 1 + raise LoadError, "missing dependency" if calls == 1 + + entered << true + end + jobs = Array.new(2) { BoundaryWork.new } + jobs.each { |job| pending << job } + supervisor.start + expect(entered.pop(timeout: 5)).to be(true) + supervisor.stop(Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5) + + expect(jobs.map(&:acknowledged)).to eq([true, true]) + expect(recovered).to be_empty + end + + it "completes a job even when periodic metrics cannot be published" do + allow(config.logger).to receive(:info).and_call_original + allow(config.logger).to receive(:info).with(hash_including(event: "sidekiq.fiber.runtime")).and_raise(IOError) + work = BoundaryWork.new + pending << work + supervisor.start + expect(entered.pop(timeout: 5)).to be(true) + + config[:lifecycle_events][:beat].each(&:call) + supervisor.quiet + release << true + supervisor.stop(Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5) + + expect(work.acknowledged).to be(true) + expect(recovered).to be_empty + end + + it "reports a continuous fetch outage once and resumes when Redis returns" do + capsule.concurrency = 1 + errors = [] + config.error_handlers.clear + config.error_handlers << ->(error, *) { errors << error } + attempts = 0 + allow(fetcher).to receive(:retrieve_work).and_wrap_original do |original| + attempts += 1 + raise IOError, "Redis unavailable" if attempts <= 2 + + original.call + end + work = BoundaryWork.new + pending << work + supervisor.start + expect(entered.pop(timeout: 5)).to be(true) + supervisor.quiet + release << true + supervisor.stop(Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5) + + expect(errors.map(&:message)).to eq(["Redis unavailable"]) + expect(work.acknowledged).to be(true) + end +end diff --git a/spec/support/execution_boundary.rb b/spec/support/execution_boundary.rb new file mode 100644 index 0000000..7db8837 --- /dev/null +++ b/spec/support/execution_boundary.rb @@ -0,0 +1,44 @@ +class BoundaryJob + include Sidekiq::Job + + class << self + attr_accessor :body + end + + def perform + self.class.body.call + end +end + +class BoundaryMiddleware + class << self + attr_accessor :after_job + end + + def call(*) + yield + self.class.after_job.call + end +end + +class BoundaryWork + attr_reader :acknowledged, :requeued + attr_accessor :before_ack + + def job + Sidekiq.dump_json("class" => "BoundaryJob", "args" => [], "jid" => "boundary", "retry" => false) + end + + def queue_name + "front" + end + + def acknowledge + before_ack&.call + @acknowledged = true + end + + def requeue + @requeued = true + end +end diff --git a/web/views/fiber_stats.html.erb b/web/views/fiber_stats.html.erb deleted file mode 100644 index 85ff92d..0000000 --- a/web/views/fiber_stats.html.erb +++ /dev/null @@ -1,132 +0,0 @@ -
Active Fibers / Max
-Fiber Threads
-In-Flight Fibers
-Max Fiber Conns / DB Pool
- <% if @global[:total_max] > @db_pool_size %> -⚠ Exceeds DB pool size
- Reduce fiber_concurrency to ≤ <%= (@db_pool_size.to_f / [@global[:thread_count], 1].max).floor %>
No fiber threads registered. Is the fiber capsule running?
-<% else %> -| Thread | -Semaphore | -Utilization | -Completed (total) | -Last Completed | -Status | -
|---|---|---|---|---|---|
<%= t["thread_id"] %> |
- <%= acquired %> / <%= size %> | -
-
-
-
- |
- <%= t["completed_total"].to_i %> | -<%= idle_secs ? "#{idle_secs}s ago" : "—" %> | -- <% if stalled %> - ⚠ Possible blocking IO - <% elsif pct == 100 %> - Semaphore full - <% else %> - Healthy - <% end %> - | -
No fibers currently running.
-<% else %> -| JID | -Job Class | -Thread | -Running For | -Status | -
|---|---|---|---|---|
<%= f["jid"] %> |
- <%= f["job_class"] %> | -<%= f["thread_id"] %> |
- <%= f["running_for"] %>s | -- <% if f["running_for"].to_f > 120 %> - ⚠ Long running - <% elsif f["running_for"].to_f > 30 %> - Slow - <% else %> - Normal - <% end %> - | -
Thread not found or no longer active.
-<% else %> - -<%= @thread_stats["thread_id"] %>| Semaphore | <%= @thread_stats["semaphore_acquired"] %> / <%= @thread_stats["semaphore_size"] %> |
|---|---|
| Completed (total) | <%= @thread_stats["completed_total"].to_i %> |
| Last Completed | -- <% last_at = @thread_stats["last_completed_at"].to_f %> - <%= last_at > 0 ? "#{(Time.now.to_f - last_at).round}s ago" : "—" %> - | -
No fibers currently running on this thread.
-<% else %> -| JID | -Job Class | -Running For | -
|---|---|---|
<%= f["jid"] %> |
- <%= f["job_class"] %> | -<%= f["running_for"] %>s | -