kino 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +5 -0
  3. data/CHANGELOG.md +281 -0
  4. data/Cargo.lock +164 -95
  5. data/README.md +269 -438
  6. data/doc/README.md +27 -2
  7. data/doc/architecture.md +862 -43
  8. data/doc/benchmarks.md +444 -214
  9. data/doc/configuration.md +215 -0
  10. data/doc/operations.md +258 -0
  11. data/doc/rails-on-ractors.md +161 -49
  12. data/doc/streaming.md +52 -0
  13. data/doc/websockets.md +469 -0
  14. data/doc/why-kino.md +6 -6
  15. data/doc/worker-loop.md +462 -0
  16. data/ext/kino/Cargo.toml +17 -1
  17. data/ext/kino/build.rs +32 -1
  18. data/ext/kino/clippy.toml +10 -0
  19. data/ext/kino/src/access_log.rs +70 -92
  20. data/ext/kino/src/control.rs +26 -685
  21. data/ext/kino/src/counters.rs +132 -0
  22. data/ext/kino/src/cpus.rs +1 -18
  23. data/ext/kino/src/dispatch/tests.rs +731 -0
  24. data/ext/kino/src/dispatch.rs +276 -0
  25. data/ext/kino/src/doorbell.rs +108 -0
  26. data/ext/kino/src/env_strings.rs +26 -30
  27. data/ext/kino/src/framing.rs +110 -0
  28. data/ext/kino/src/gvl.rs +292 -66
  29. data/ext/kino/src/hijack/tests.rs +416 -0
  30. data/ext/kino/src/hijack.rs +471 -0
  31. data/ext/kino/src/inline/answer.rs +488 -0
  32. data/ext/kino/src/inline/conn.rs +1124 -0
  33. data/ext/kino/src/inline/deadline.rs +421 -0
  34. data/ext/kino/src/inline/encode.rs +119 -0
  35. data/ext/kino/src/inline/io.rs +487 -0
  36. data/ext/kino/src/inline/mod.rs +766 -0
  37. data/ext/kino/src/inline/parity.rs +862 -0
  38. data/ext/kino/src/inline/parse.rs +131 -0
  39. data/ext/kino/src/inline/spin.rs +428 -0
  40. data/ext/kino/src/inline/testing.rs +628 -0
  41. data/ext/kino/src/io_shards.rs +240 -192
  42. data/ext/kino/src/lane_room.rs +99 -0
  43. data/ext/kino/src/lib.rs +139 -77
  44. data/ext/kino/src/listen.rs +180 -12
  45. data/ext/kino/src/log.rs +12 -47
  46. data/ext/kino/src/logsink.rs +3 -9
  47. data/ext/kino/src/mono.rs +12 -17
  48. data/ext/kino/src/pin.rs +3 -3
  49. data/ext/kino/src/queue/mod.rs +54 -0
  50. data/ext/kino/src/queue/take.rs +503 -0
  51. data/ext/kino/src/queue/testing.rs +107 -0
  52. data/ext/kino/src/queue/tests.rs +581 -0
  53. data/ext/kino/src/queue/worker.rs +501 -0
  54. data/ext/kino/src/registry.rs +168 -379
  55. data/ext/kino/src/request.rs +834 -235
  56. data/ext/kino/src/response.rs +532 -94
  57. data/ext/kino/src/server/accept.rs +322 -0
  58. data/ext/kino/src/server/config.rs +138 -0
  59. data/ext/kino/src/server/handle.rs +247 -0
  60. data/ext/kino/src/server/intake.rs +217 -0
  61. data/ext/kino/src/server/mod.rs +157 -0
  62. data/ext/kino/src/server/natives.rs +223 -0
  63. data/ext/kino/src/server/serve/intake_tests.rs +458 -0
  64. data/ext/kino/src/server/serve.rs +436 -0
  65. data/ext/kino/src/server/tests.rs +532 -0
  66. data/ext/kino/src/shared_gvl.rs +50 -0
  67. data/ext/kino/src/slot/lane.rs +138 -0
  68. data/ext/kino/src/slot/life.rs +111 -0
  69. data/ext/kino/src/slot/load.rs +193 -0
  70. data/ext/kino/src/slot/mod.rs +494 -0
  71. data/ext/kino/src/slot/park.rs +82 -0
  72. data/ext/kino/src/stats.rs +936 -0
  73. data/ext/kino/src/symbols.rs +66 -0
  74. data/ext/kino/src/test_support.rs +24 -14
  75. data/ext/kino/src/testing.rs +409 -0
  76. data/ext/kino/src/ticker.rs +87 -0
  77. data/ext/kino/src/timer.rs +4 -7
  78. data/ext/kino/src/tls.rs +101 -131
  79. data/ext/kino/src/typed_data.rs +131 -0
  80. data/ext/kino/src/upgrade.rs +77 -0
  81. data/ext/kino/src/ws/codec.rs +470 -0
  82. data/ext/kino/src/ws/drive.rs +600 -0
  83. data/ext/kino/src/ws/handshake.rs +267 -0
  84. data/ext/kino/src/ws/mod.rs +317 -0
  85. data/ext/kino/src/ws/server_tests.rs +759 -0
  86. data/ext/kino/src/ws/socket.rs +279 -0
  87. data/ext/kino/src/ws/stats.rs +88 -0
  88. data/ext/kino/src/ws/testing.rs +156 -0
  89. data/ext/kino/src/ws/topics.rs +550 -0
  90. data/lib/kino/cli.rb +100 -9
  91. data/lib/kino/configuration.rb +32 -10
  92. data/lib/kino/crash_backoff.rb +56 -0
  93. data/lib/kino/input.rb +36 -17
  94. data/lib/kino/log.rb +8 -1
  95. data/lib/kino/monitor.rb +1 -1
  96. data/lib/kino/pool.rb +169 -0
  97. data/lib/kino/pool_scaler.rb +12 -13
  98. data/lib/kino/quarantine_monitor.rb +3 -3
  99. data/lib/kino/ractor_supervisor.rb +201 -161
  100. data/lib/kino/server.rb +291 -185
  101. data/lib/kino/slot_bank.rb +21 -9
  102. data/lib/kino/stream.rb +2 -2
  103. data/lib/kino/teardown.rb +33 -0
  104. data/lib/kino/templates/kino.rb.tt +41 -6
  105. data/lib/kino/threaded_pool.rb +87 -102
  106. data/lib/kino/version.rb +1 -1
  107. data/lib/kino/web_socket.rb +125 -0
  108. data/lib/kino/worker/loop.rb +319 -0
  109. data/lib/kino/worker.rb +345 -79
  110. data/lib/kino/worker_hooks.rb +7 -1
  111. data/lib/kino/worker_row.rb +15 -0
  112. data/lib/kino.rb +27 -3
  113. data/lib/rackup/handler/kino.rb +1 -1
  114. data/sig/kino.rbs +93 -10
  115. metadata +66 -3
  116. data/ext/kino/src/queue.rs +0 -333
  117. data/ext/kino/src/server.rs +0 -1785
@@ -0,0 +1,215 @@
1
+ # Configuring Kino
2
+
3
+ Every server option, the config file and the CLI, the modes,
4
+ `kino --check`, timeouts and intake limits, `on_error`, the lifecycle
5
+ hooks, sharded I/O and HTTP/2. The [README](../README.md) has the short
6
+ version of each; [operations.md](operations.md) covers signals, stats,
7
+ logging, the elastic pool and quarantine.
8
+
9
+ ## Server options
10
+
11
+ `Kino::Server.new` takes every option as a keyword argument. Embedded,
12
+ with everything spelled out:
13
+
14
+ ```ruby
15
+ server = Kino::Server.new(app,
16
+ bind: "127.0.0.1", # or "unix:///run/kino.sock" behind a proxy
17
+ port: 9292, # 0 = ephemeral; read back via server.port
18
+ workers: 8, # ractors (parallelism); default: CPUs, capped at RUBY_MAX_CPU
19
+ max_workers: nil, # experimental: grow past workers under load (see Elastic pool)
20
+ scale_down_after: 30, # seconds idle before an extra worker retires
21
+ threads: 1, # per worker; ractor default 1, threaded default 3
22
+ mode: :auto, # :auto | :ractor | :threaded
23
+ queue_depth: 1024, # bounded queue; overflow → 503
24
+ queue_timeout: 5.0, # seconds before 503 on a full queue
25
+ request_timeout: nil, # seconds before a slow response becomes a 504 (nil = off)
26
+ max_connections: 8192, # cap concurrent connections; default: most of ulimit -n
27
+ max_body_size: 50 * 1024 * 1024, # bytes before a 413; nil = let a proxy handle it
28
+ on_error: ->(e, env) { ErrorTracker.capture(e) }, # after the client got its 500
29
+ shutdown_timeout: 30, # drain deadline
30
+ control_bind: "127.0.0.1:9293", # monitoring: /stats /metrics /ready /live; port 0 reads back via server.control_port
31
+ control_token: ENV["KINO_CONTROL_TOKEN"], # optional Bearer auth for /stats + /metrics
32
+ tls: { cert: "cert.pem", key: "key.pem" }, # file paths or inline PEM
33
+ http2: true, # ALPN h2 on TLS + plaintext h2c; false = HTTP/1 only
34
+ )
35
+ server.start
36
+ server.shutdown # graceful: drain → deadline → abort stragglers
37
+ ```
38
+
39
+ ## Config file and CLI
40
+
41
+ Settings can live in a Puma-style Ruby DSL file: `kino.rb` in the
42
+ working directory, or `config/kino.rb` (the Rails layout), is picked up
43
+ automatically; `-C PATH` names any other. Precedence: explicit kwargs
44
+ and CLI flags > config file > defaults.
45
+
46
+ ```ruby
47
+ # kino.rb
48
+ port 9292
49
+ workers 8
50
+ threads 1
51
+ mode :ractor
52
+ ```
53
+
54
+ ```sh
55
+ kino --init # write a fully commented sample kino.rb
56
+ kino # config.ru + kino.rb, port 9292
57
+ kino --check # explain whether the app can run in :ractor mode
58
+ kino -C config/kino.rb -p 3000 -w 4 -m ractor my_app.ru
59
+ ```
60
+
61
+ The generated sample documents every directive, including the Rails
62
+ settings and the performance notes.
63
+
64
+ ## Modes
65
+
66
+ - **`:ractor`**: `workers` Ractors × `threads` Threads each. The app must
67
+ be `Ractor.shareable?` (frozen middleware, `shareable_proc` endpoints).
68
+ Forcing `:ractor` with an unshareable app raises
69
+ `Kino::UnshareableAppError`. A crashed worker thread returns 500 to
70
+ its in-flight requests right away and is replaced; the other threads
71
+ of its ractor serve on.
72
+ - **`:threaded`**: the same machinery on `workers × threads` plain
73
+ Threads. Runs **any** Rack app, including all of Rails. Parallel for
74
+ I/O, serialized by the GVL for CPU. A crashed worker thread is
75
+ replaced the same way.
76
+ - **`:auto`** (default): `:ractor` when the app is shareable, otherwise
77
+ a warning and `:threaded`. One caveat: a *class* used as a Rack app
78
+ always counts as "shareable" (classes are), even if calling it touches
79
+ unshareable state. Force `:threaded` for those.
80
+
81
+ A crash is an exception that is not a `StandardError` (a `StandardError`
82
+ only fails its request, unless `Thread#raise` sends it into a worker
83
+ waiting for its next request), or a worker thread that ends short of its
84
+ loop's end, `Thread#kill` included. With lanes, the requests waiting for
85
+ a crashed worker go to the other workers as new arrivals, their
86
+ `queue_timeout` starting over, so behind workers that keep crashing a
87
+ client can wait longer than `queue_timeout`. A worker that keeps
88
+ crashing within a second of starting, before it served a request (in
89
+ `after_worker_boot` too), is respawned after a delay doubling from 0.1 s
90
+ up to 5 s; any other crash respawns it at once. More in
91
+ [Failure handling](architecture.md#failure-handling).
92
+
93
+ ## `kino --check`
94
+
95
+ When an app cannot run in `:ractor` mode, Kino can tell you why, instead
96
+ of leaving you with a bare `Ractor::IsolationError`. The check changes
97
+ nothing (it does not freeze your objects) and names each blocker:
98
+ captured variables with the place they were defined, instance variables
99
+ by path, and the class-level instance variable trap that catches
100
+ class-style apps:
101
+
102
+ ```
103
+ $ kino --check
104
+ check: app is NOT Ractor-shareable
105
+ - app (Proc at app.rb:12)—captures `cache` = {} (Hash) (unshareable)
106
+ - app (HelloApp).@instance—class-level ivar holds #<HelloApp…>—classes
107
+ pass Ractor.shareable?, but reading this from a worker ractor raises
108
+ Ractor::IsolationError on the first request
109
+ hints: freeze config at boot; build endpoints with Ractor.shareable_proc;
110
+ keep per-worker resources in Ractor.store_if_absent; or run mode :threaded.
111
+ ```
112
+
113
+ Exit status is 0/1, so it works in CI. The programmatic form is
114
+ `Kino::Check.report(app)`.
115
+
116
+ ## Request timeouts
117
+
118
+ `request_timeout: seconds` (or `request_timeout 30` in `kino.rb`) limits
119
+ how long the app may take to produce a response. Past the deadline the
120
+ client gets an immediate **504** while the handler keeps running; its
121
+ late response is dropped without harm. Off by default. The handler is
122
+ deliberately *not* killed, because interrupting arbitrary Ruby mid-flight
123
+ is unsafe. A stuck handler still occupies its worker slot until it
124
+ returns, so set the deadline above your slowest legitimate endpoint and
125
+ watch `stats[:timeouts]`.
126
+
127
+ ## Intake limits
128
+
129
+ Timeouts guard your app; the network intake guards itself. New
130
+ connections past `max_connections` (default: most of `ulimit -n`) wait
131
+ in the kernel's accept queue, as long a queue as the kernel allows
132
+ ([more](architecture.md#backpressure-in-both-directions)); request
133
+ bodies past `max_body_size` (default 50 MB, `nil` delegates to a
134
+ fronting proxy) get a **413**; and fixed deadlines drop a client whose
135
+ first bytes are not in 15 s after it connected (with HTTP/2, the whole
136
+ preface; on an inline connection, the whole first head), or whose
137
+ request head is not whole 15 s after it began, stalled TLS handshakes
138
+ (10 s), uploads stalled mid-body (30 s), and an HTTP/2 peer that leaves
139
+ a ping unanswered (see
140
+ [Intake deadlines](architecture.md#intake-deadlines)). A client that
141
+ ends its side of the connection once its request is sent is taken as
142
+ gone, as nginx takes it.
143
+
144
+ ## Error reporting: `on_error`
145
+
146
+ When a worker catches an app or delivery error,
147
+ `on_error ->(error, env) { ErrorTracker.capture(error) }` is called
148
+ after the client got its 500—the only place a tracker sees errors
149
+ raised while the response was being written (in `:ractor` mode, build
150
+ the handler with `Ractor.shareable_proc`). For what a WebSocket callback
151
+ or a wake hook raised, `env` is a small frozen Hash naming the callback
152
+ (`"kino.callback"`), not a Rack env.
153
+
154
+ ## Lifecycle hooks
155
+
156
+ Kino fires four lifecycle hooks alongside `on_error`, split by firing context.
157
+
158
+ **Worker-context hooks** run inside the worker and are available to all workers:
159
+ - `after_worker_boot { |worker_id| }`: runs once before the worker begins serving, with its slot id. In `:ractor` mode it runs inside the worker ractor and must be `Ractor.shareable_proc`.
160
+ - `after_request_complete { |env, status| }`: fires inside the worker after each successful response. This is the hot path—leave it unset for zero cost. In `:ractor` mode it must be `Ractor.shareable_proc`. It fires once an accepted WebSocket handshake's 101 is out (status 101) and after a partial hijack, but not after a full `rack.hijack`, where the app owns the connection and its response.
161
+
162
+ **Main-context hooks** run on the main thread, outside workers, and are plain procs:
163
+ - `after_boot { }`: fires once after the worker pool is up. Wire readiness here—sd_notify, a "server ready" metric, and so on.
164
+ - `on_worker_exit { |worker_index, error| }`: fires when a worker exits, with its index and the crash cause (or nil on a clean exit). In `:ractor` mode it fires for each worker thread that crashed, with the ractor's index and a copy of the cause (a `Kino::Error` naming it when it cannot be copied out of the ractor).
165
+
166
+ `after_worker_boot`'s argument is the worker's slot id, while in `:ractor` mode `on_worker_exit`'s argument identifies the exited ractor (`0`..`workers - 1`)—a different number space—so don't correlate boot and exit by that number in `:ractor` mode.
167
+
168
+ A raising hook is logged and never kills a worker.
169
+
170
+ ## Sharded I/O
171
+
172
+ `io_shards true` (off by default) moves HTTP I/O from Tokio's shared
173
+ multi-thread runtime onto current-thread shards: one thread accepts and
174
+ hands each connection to the least-loaded shard (open WebSockets and
175
+ hijacked connections count), which then owns it for its lifetime—no
176
+ work-stealing, no cross-thread wakeups on the hot path.
177
+ On the 2026-09 reference box (a c7a.2xlarge) fast handlers gained +1-3%
178
+ (best with `io_threads 8`); the win grows with scheduler contention, so measure on
179
+ your own core count. Ruby-bound endpoints are unchanged. Orthogonal to
180
+ `mode`: it reshapes the Rust side only.
181
+
182
+ ```ruby
183
+ # kino.rb
184
+ io_shards true
185
+ io_threads 8 # optional; default: half the available CPUs
186
+ ```
187
+
188
+ The measurements are in
189
+ [benchmarks.md](benchmarks.md#sharded-io-io_shards-true).
190
+
191
+ ## HTTP/2
192
+
193
+ On by default, on both transports, with nothing to configure:
194
+
195
+ - **TLS binds** advertise `h2` via ALPN, so browsers and h2-capable
196
+ clients negotiate HTTP/2 and everything else stays on HTTP/1.1.
197
+ - **Plaintext binds** serve prior-knowledge h2c: a client that opens
198
+ with the HTTP/2 preface (an h2-preferring load balancer, a gRPC-style
199
+ backend hop, `curl --http2-prior-knowledge`) gets HTTP/2; ordinary
200
+ clients are HTTP/1.1 exactly as before. Browsers never do h2 on
201
+ plaintext, so a certificate-less kino behaves identically for them.
202
+
203
+ The Rack side is spec-complete on h2: `SERVER_PROTOCOL` is `"HTTP/2"`,
204
+ `HTTP_HOST`/`SERVER_NAME`/`SERVER_PORT` come from the `:authority`
205
+ pseudo-header (h2 requests carry no Host header), split cookie headers
206
+ are rejoined with `"; "`, and streamed uploads flow through the same
207
+ backpressured body channel as HTTP/1. Streams multiplex into the same
208
+ worker slots as keep-alive requests—`workers × threads` bounds
209
+ concurrency either way. (`rack.hijack` and WebSockets stay on HTTP/1:
210
+ h2 multiplexes streams on one connection, so no request has a
211
+ connection of its own to hand over.) `http2 false` pins the server to
212
+ HTTP/1 and drops `h2` from ALPN.
213
+
214
+ How it works inside is in [architecture.md](architecture.md#http2),
215
+ and the numbers are in [benchmarks.md](benchmarks.md#http2).
data/doc/operations.md ADDED
@@ -0,0 +1,258 @@
1
+ # Operating Kino
2
+
3
+ Signals and shutdown, live stats and the control plane, logging, the
4
+ elastic pool and stuck-worker quarantine. Every other option is in
5
+ [configuration.md](configuration.md).
6
+
7
+ ## Signals and shutdown
8
+
9
+ `Kino::Server.run` and the `kino` command trap INT and TERM: the first
10
+ drains gracefully, a second force-exits. `kill -USR1 <pid>` logs a
11
+ [stats](#stats) line. An embedded server drains with `server.shutdown`:
12
+ drain, then the deadline (`shutdown_timeout`), then abort the
13
+ stragglers. Every step of the drain is in
14
+ [Graceful shutdown](architecture.md#graceful-shutdown).
15
+
16
+ ## Stats
17
+
18
+ `server.stats` returns a live snapshot: the configuration plus counters
19
+ from the native layer (one relaxed atomic per request, no measurable
20
+ cost):
21
+
22
+ ```ruby
23
+ server.stats
24
+ # => {mode: :ractor, lanes: false, workers: 8, threads: 1, batch: 1,
25
+ # respawns: 0, queued: 0, in_flight: 2, served: 1041, rejected: 0,
26
+ # timeouts: 0, worker_status: [...], …}
27
+ # plus lane_depths: [...] when lane dispatch is on
28
+ ```
29
+
30
+ From the outside, `kill -USR1 <pid>` logs the same snapshot as one line
31
+ (pair it with `pidfile` to find the pid):
32
+
33
+ ```
34
+ kino[4213] main: stats mode=:ractor lanes=false workers=8 threads=1 batch=1 respawns=0 queued=0 in_flight=2 served=1041 rejected=0 timeouts=0 …
35
+ ```
36
+
37
+ ## The control plane
38
+
39
+ For pull-based monitoring, `control_bind "127.0.0.1:9293"` (or a
40
+ `unix://` path) serves a read-only **control plane** from the native
41
+ layer on its own thread—it keeps answering even while every Ruby worker
42
+ is busy or stuck, and reports `draining` through a graceful shutdown:
43
+
44
+ - `GET /stats`—the same snapshot as `server.stats`, as JSON (plus
45
+ `state` and `version`).
46
+ - `GET /metrics`—Prometheus text format (`kino_requests_served_total`,
47
+ `kino_queue_depth`, `kino_ready`, …).
48
+
49
+ Both `/stats` and `/metrics` also break the counters down per dispatch
50
+ slot: `/stats` carries a `worker_status` array (`index`, `served`,
51
+ `in_flight`, `busy_ms`, `quarantined`, `retired`, `websockets_open`,
52
+ `hijacked_connections`, `inline_connections`) and `/metrics` emits
53
+ `kino_worker_*{worker="N"}` series, one entry per execution slot
54
+ (`workers × threads`). A crashed or retired worker's slot goes to a
55
+ later worker, its counters starting over, once its sockets, hijacked
56
+ connections and inline connections are gone. `busy_ms` is how long the
57
+ slot's current request, WebSocket callback or wake hook has been running
58
+ (0 when idle; under a
59
+ [`worker_loop`](worker-loop.md#stats-and-logs), how long its thread
60
+ has stayed away from its loop), so a single slot climbing while the rest
61
+ sit at 0 is your stuck worker.
62
+
63
+ The `/stats` response and `server.stats` carry `queue_time` (count and
64
+ summed seconds), and `/metrics` exposes `kino_request_queue_seconds`—a
65
+ Prometheus histogram of queue-wait time, the worker-saturation signal.
66
+ Counts admitted requests only; a 503 after queue wait goes to `rejected`,
67
+ not `queue_time`.
68
+
69
+ A hijacked request leaves `in_flight` when the app takes it over and
70
+ counts in `hijacked_connections` until its connection closes; `wakes`
71
+ counts wake hook runs (under a
72
+ [`worker_loop`](worker-loop.md#stats-and-logs), every wake its loop
73
+ takes). `responses_cut` counts, for the whole process,
74
+ [streamed responses](streaming.md#streaming-responses) that ended early, by cause:
75
+ `client_gone`, `shutdown` (the drain's deadline) and `crash`. The
76
+ process's WebSocket counters sit under `websockets`;
77
+ [websockets.md](websockets.md#stats) lists them and their
78
+ `/metrics` series. Inline connections count under `inline` (nil on a
79
+ server that serves none), listed with their `/metrics` series in
80
+ [worker-loop.md](worker-loop.md#stats-and-logs).
81
+
82
+ - `GET /ready`—`200` when serving, `503` while booting or draining:
83
+ wire it to your load balancer or Kubernetes readiness probe.
84
+ - `GET /live`—`200` whenever the process is alive: the liveness probe.
85
+
86
+ `control_token "..."` puts `/stats` and `/metrics` behind
87
+ `Authorization: Bearer`; the probes stay open.
88
+
89
+ ## Logging
90
+
91
+ With one log line per request, `Kino::Logger` sustained **1.7× the
92
+ throughput of a shared `::Logger`** (155k vs 90k req/s on the 2026-09
93
+ c7a.2xlarge benchmark box). There are two native pieces. Both write through a lock-free
94
+ channel to a Rust flusher thread, so request threads never take a log
95
+ mutex and never make a write syscall:
96
+
97
+ - **Access log** (`log_requests true`): two records per request to
98
+ stdout, including the 503s that never reach your app. The arrival line
99
+ is queued before the app runs, so a request that hangs shows as an
100
+ arrow with no answer; the completion line carries the status, the
101
+ total, and a timing breakdown: `ruby` is the time the request spent in
102
+ Ruby (with the GC pause and the objects allocated during it), `kino`
103
+ the server's own overhead, `wait` the queue time before a worker took
104
+ it. Recommended in development; cheap enough for production. On color
105
+ terminals the completion line is tinted by status class: 2xx green,
106
+ 3xx yellow, 4xx maroon, 5xx bright red:
107
+
108
+ ```
109
+ 2026-08-22 14:03:11 +0300 → GET /users?q=1 from 127.0.0.1
110
+ 2026-08-22 14:03:11 +0300 ← 200 GET /users?q=1 12.4ms (ruby 9.1ms [gc 0.8ms; 1.5k obj]; kino 3.2ms; wait 0.1ms)
111
+ ```
112
+
113
+ The GC and allocation figures come from the VM's process-wide
114
+ counters, so they appear only where one request at a time can own
115
+ them: in `:threaded` mode, or in `:ractor` mode with `workers 1`, and
116
+ never under a [`worker_loop`](worker-loop.md#stats-and-logs),
117
+ whose requests interleave. Parallel ractors would bill each other's
118
+ work, so there the breakdown is `(ruby; kino; wait)` alone.
119
+
120
+ - **`Kino::Logger`**: a `::Logger` over the same async sink, for your
121
+ app's own logging (`Kino::Logger.new("log/production.log")`, or no
122
+ argument for stdout). The raw IO-like device is `Kino::Logger::Device`,
123
+ for integrations that want bytes without `::Logger` formatting. The
124
+ device is frozen and Ractor-shareable, so one device serves every
125
+ worker.
126
+
127
+ `Kino::Logger` in a **Rails** app: it is a real `::Logger` subclass, so
128
+ it fits anywhere Rails expects a logger:
129
+
130
+ ```ruby
131
+ # config/environments/production.rb, simplest forms:
132
+ config.logger = Kino::Logger.new # stdout
133
+ config.logger = Kino::Logger.new("log/production.log") # file
134
+ # both file and stdout:
135
+ config.logger = ActiveSupport::BroadcastLogger.new(
136
+ Kino::Logger.new("log/production.log"), Kino::Logger.new
137
+ )
138
+ # tagged logging wraps it like any ::Logger:
139
+ config.logger = ActiveSupport::TaggedLogging.new(Kino::Logger.new)
140
+ ```
141
+
142
+ From a plain **Rack** app, give middleware the logger, or hand
143
+ `Rack::CommonLogger` the raw device (it just calls `write`):
144
+
145
+ ```ruby
146
+ # config.ru
147
+ use Rack::CommonLogger, Kino::Logger::Device.new # access-style app log
148
+ run MyApp
149
+ ```
150
+
151
+ (If you only want request lines, prefer Kino's own `log_requests true`.
152
+ It is free for your Ruby threads, and it also sees the 503s that never
153
+ reach Rack.)
154
+
155
+ Graceful shutdown drains both logs fully. A hard crash can lose the tail
156
+ of the buffer, and when you log faster than the disk can take (over 100k
157
+ lines/s), the sink drops lines instead of blocking request threads.
158
+ These trade-offs are measured in
159
+ [benchmarks.md](benchmarks.md#logging-costs).
160
+
161
+ **Server lines.** Everything Kino says about itself (draining, a crash
162
+ and its respawn, a hook that raised, quarantine, the stats line,
163
+ `rack.errors`) reads `kino[<pid>] <source>: message`, the source being
164
+ the worker that spoke, `worker-3` (or `worker-3/thread-2` in a
165
+ multi-threaded ractor), or `main`. On color terminals the label is dim
166
+ for notes, yellow for warnings, red for errors; the message stays plain.
167
+ A failed request gets a report instead of a bare backtrace: the request
168
+ line, the error, and where it raised in your code, then the trace with
169
+ your frames first, relative to the working directory, and the rest
170
+ folded:
171
+
172
+ ```
173
+ kino[4213] worker-2: 500 GET /boom · RuntimeError: kaboom (app.rb:12:in 'explode')
174
+ app.rb:12:in 'explode'
175
+ /usr/lib/ruby/gems/4.0.0/gems/rack-3.2.7/lib/rack/builder.rb:...
176
+ … 38 more
177
+ ```
178
+
179
+ Hooks can log through the same channel with `Kino::Log.info`, `.warn`,
180
+ and `.error`; it is safe inside worker ractors.
181
+
182
+ ## Elastic pool (experimental)
183
+
184
+ Size the pool for the quiet hours and let it grow for the busy ones:
185
+
186
+ ```ruby
187
+ # kino.rb
188
+ workers 4 # always running
189
+ max_workers 16 # reached only under load
190
+ scale_down_after 30 # seconds idle before an extra worker retires
191
+ ```
192
+
193
+ Or `Kino::Server.new(app, workers: 4, max_workers: 16)`. Leave
194
+ `max_workers` unset and the pool is fixed at `workers`, as before.
195
+
196
+ While requests wait in the queue, Kino adds a worker every 100 ms until
197
+ the queue clears or the pool hits `max_workers`. When the load passes,
198
+ workers above `workers` retire one at a time after `scale_down_after`
199
+ seconds idle, each finishing its current request first. Same behavior
200
+ in `:ractor` and `:threaded` mode. A worker with open WebSockets or
201
+ hijacked connections counts as busy.
202
+
203
+ **Use it when your app waits**: on databases, upstream services, slow
204
+ clients. With `workers` at your core count, all workers can be blocked
205
+ on I/O while cores sit idle; a higher ceiling puts those cores to work,
206
+ and a ractor starts in microseconds, so the pool follows load closely.
207
+ Pure CPU work gains nothing past the core count. In `:ractor` mode Ruby
208
+ itself runs at most `RUBY_MAX_CPU` ractors' Ruby code at once (default
209
+ 8). The default `workers` in `:ractor` mode is the CPU count capped at
210
+ that limit, so a default boot never warns; Kino warns only when an
211
+ explicit `workers` or `max_workers` exceeds it. On a bigger box:
212
+
213
+ ```sh
214
+ RUBY_MAX_CPU=16 kino
215
+ ```
216
+
217
+ **Watch it breathe** in `server.stats`, `GET /stats` and `GET /metrics`:
218
+
219
+ ```sh
220
+ $ curl -s localhost:9293/stats | jq '{workers, max_workers, active_workers, scale_ups, scale_downs}'
221
+ {
222
+ "workers": 4,
223
+ "max_workers": 16,
224
+ "active_workers": 9,
225
+ "scale_ups": 12,
226
+ "scale_downs": 7
227
+ }
228
+ ```
229
+
230
+ Prometheus gets `kino_max_workers`, `kino_active_workers`,
231
+ `kino_scale_ups_total` and `kino_scale_downs_total`. `after_worker_boot`
232
+ fires for every worker the pool adds, `on_worker_exit` (with a nil
233
+ cause) for every one it retires.
234
+
235
+ ## Stuck-worker quarantine
236
+
237
+ `quarantine_timeout: seconds` (or `quarantine_timeout 60` in `kino.rb`)
238
+ quarantines a dispatch slot whose request (or WebSocket callback, or wake
239
+ hook) has run longer than the deadline (under a
240
+ [`worker_loop`](worker-loop.md#stuck-workers-and-quarantine), whose
241
+ thread has stayed away from its loop that long) and spawns a replacement
242
+ worker to restore capacity—distinct from
243
+ `request_timeout`, which gives the client a 504 but leaves the slot
244
+ occupied. `quarantine_max` (default: the worker count in `:ractor` mode,
245
+ workers × threads in `:threaded`) caps the total number of replacement
246
+ events over the process lifetime—past it the monitor stops replacing and
247
+ the server runs at reduced capacity.
248
+
249
+ The wedged worker is never interrupted or force-killed, and its slot stays
250
+ quarantined for good. In `:threaded` mode, if the blocked thread
251
+ eventually returns, it keeps serving requests on that same slot—but the
252
+ slot itself stays flagged quarantined (busy_ms reported as 0) for the rest
253
+ of the process; in `:ractor` mode the wedged ractor (and its supervisor
254
+ thread) leaks until the process exits, since a wedged ractor cannot be
255
+ safely interrupted. Monitor quarantine activity via `server.stats`
256
+ (top-level `quarantined` count and per-slot `worker_status[].quarantined`
257
+ flag), `GET /stats` (same), and `GET /metrics` (`kino_quarantined_workers`
258
+ gauge and `kino_quarantine_replacements_total` counter).