Repository navigation
fix(logging): keep Redis off the request path for log writes - #1363
Conversation
With Redis configured, every captured slog record and every request
through the activity middleware ran a synchronous RPUSH on the caller's
goroutine. When the push failed, the writer logged a warning through the
slog default, which is the operational log handler, so the warning was
pushed through the same writer. While Redis refused connections one
slog.Info never returned and every request that logged stalled.
Every node now uses the path single-node installs already had: operational
and activity entries go into a bounded in-memory buffer
(logstream.Buffer), and a consumer on the same node inserts them into
Postgres in batches and publishes each row to the admin live tail.
Writers never block or log. A full buffer or a failed batch insert is
counted in silo_log_writer_dropped_total{stream,reason}.
The opslog consumer's own warnings go to stderr and OTLP only, so a
failing batch cannot queue entries about itself. Cross-node publishes for
a batch share a two-second deadline, so an unreachable Redis cannot stall
the consumer row by row. The consumers outlive appCtx and flush from
deferred calls in main, so records logged during graceful shutdown are
persisted. The Redis writers, the Redis drain loops and their dedicated
Redis clients are removed.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
… the drain
Review of the first revision found that a Redis outage still throttled
Postgres persistence and that a Postgres blip dropped whole batches.
The consumer published each inserted row to other nodes inline, under a
two-second budget per batch. With Redis refusing connections or
unreachable, one consumer persisted only 25 to 35 entries per second, so
any busy node overflowed its buffer. logstream.Hub now hands rows to local
subscribers inline and queues them (1,024 rows) for its own goroutine,
which publishes to the event bus with a two-second deadline per publish.
The consumer never waits on Redis. Rows that miss other nodes' live tails
are counted in silo_log_tail_publish_dropped_total{stream,reason}, and the
hub logs only when publishing starts failing and when it recovers. main
closes the hub after the log consumers flush and before the event bus
closes.
A failed batch insert was dropped on the first attempt. logstream.Drain
now retries connection and availability errors with backoff from one to
ten seconds while the node runs, so the buffer holds entries through a
Postgres restart or failover. A batch the server rejects is dropped at
once, a stopping node makes one attempt per batch, and every attempt has
a ten-second deadline.
The metric help and the observability doc no longer claim that stderr
and OTLP receive every record: audit entries have no other copy. The doc
also covers the lost log.Fatalf record on exit and the leftover Redis
list keys from earlier versions.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Without the Redis JSON round trip, raw strings reached the multi-row INSERT, so one request with a 0xFF byte in its path or User-Agent made Postgres reject the whole batch and dropped up to 100 other audit entries. Both consumers now replace invalid UTF-8 and NUL bytes in text fields, and \u0000 escapes in attrs JSON, with U+FFFD. When Postgres still rejects a value (SQLSTATE class 22, such as a client address that is not an inet), the drain inserts that batch one row at a time so only the rejected rows are dropped and counted. opslog.Handler now encodes non-scalar attribute values when the record is logged. The consumer encoded them seconds later on its own goroutine, so a caller that changed a logged map could race that encode. A write refused as read-only (25006) after a switchover is now retried. The request pipeline test serves 100 requests. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
|
Warning Review limit reachedNext included review available in 1 minute. View limit detailsLimit details: You’ve used all 2 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (24)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Problem
Related issue: N/A
Validation tasks: reaches #1217 C2 and #1218 C2 (audit entries and their live delivery; both not run yet). No passed case changes.
When Redis is configured, both database log writers push to Redis on the caller's goroutine.
opslog.RedisWriterruns oneRPUSHfor every capturedslogrecord at the capture level (info by default), andactivitylog.RedisWriterruns one for every request through the activity middleware. A logged request therefore waits on two Redis round trips before it returns.When a push fails, the writer calls
slog.Warn. The operational handler is theslogdefault, so that warning is captured and pushed through the same writer. If Redis refuses connections, each failed push logs another warning and tries another push. Oneslog.Infonever returns, so every request that logs stalls for as long as Redis is down. This affects any deployment with a Redis URL, which includes every multi-node cluster.Approach
Every node now takes the path that installs without Redis already used. Each node queues operational (
app) and activity (audit) entries in its own bounded in-memory buffer, 10,000 entries per stream. A consumer on that node inserts them into Postgres in batches of 100, or every two seconds.logstream.Hubthen hands each inserted row to local live-tail subscribers and queues it for a goroutine that publishes it to other nodes through the Redis event bus, as before. Redis is off both the logging path and the persistence path.logstream.Bufferreplaces the two copies ofMemoryWriter, andlogstream.Drainreplaces the two batching loops.Writenever blocks and never logs. A full buffer drops the entry and counts it insilo_log_writer_dropped_total{stream, reason}(buffer_full).Drainretries the batch with backoff from one to ten seconds, and new entries wait in the buffer. Each attempt has a ten-second deadline. When the node is stopping, each batch gets one attempt. A batch that is given up is counted asinsert_failed. For comparison, the Redis path made three attempts over about six seconds, and the old in-memory path made one.User-Agentheaders, file names. Postgres rejects NUL and invalid UTF-8 in text and the\u0000escape injsonb, and one such value fails the whole multi-row insert. Both consumers now replace those bytes with U+FFFD before inserting. The old Redis path's JSON round trip replaced invalid UTF-8 as a side effect; a NUL byte failed the batch on every old path.inet),Draininserts that batch one row at a time, so only the rejected rows are dropped and counted. Any other batch the server rejects is dropped at once, so it cannot hold up the stream.opslog.Handlerencodes non-scalar attribute values (maps, slices, structs, pointers) to JSON when the record is logged. The consumer builds rows later on its own goroutine, and a caller that changed a logged map in the meantime would race that encode, which is a fatal error for maps. The Redis writer encoded on the logging goroutine, so cluster deployments keep that behavior.silo_log_tail_publish_dropped_total{stream, reason}(queue_full,publish_failed). The hub logs when publishing starts failing and when it recovers, not for each row, because each of those records is itself persisted and published.opslog.Handlerpasses to stderr and OTLP only. Without it, a warning about a failed insert would be queued into the next batch, and while Postgres is down the consumer would keep producing entries about itself.mainafter the HTTP servers drain, with a five-second limit on the final flush. The hub then sends its queue, with a two-second limit, before the event bus closes. Records logged during graceful shutdown still reach Postgres and other nodes' live tails.opslog.RedisWriter,activitylog.RedisWriter, both Redis drain loops, and the Redis clients created only for them are removed.App records also go to stderr and OTLP. Audit entries do not: the request logger skips
/api/v2, so an audit entry that is dropped has no other copy. That is why failed inserts are retried and a rejected value costs only its own row.Alternatives considered:
docs/architecture/observability.mdrecords the persistence path, retries, byte replacement, row-by-row fallback, both drop counters, the shutdown order, and the leftover Redis keys.Before and after
slog.Infothrough the production handler chain, Redis refusing connectionsRPUSHcalls, each failed push logging another warning.TestOperationalLoggingReturnsWhileRedisIsDown; Redis operations counted fromsilo_dependency_operations_totalRPUSH×2); 200 over 100 requestsTestLoggedRequestIssuesNoRedisCommands: 100 requests through the activity middleware whose handler logs at info, against a stub Redis server that counts every commandRPUSHfails, so no entry reaches the Redis list that the consumer drainsappentries drained into the test database through a real Redis event bus pointed at a refused port and at a non-routable address, on a shared host at load average about 1000xFFUser-Agent, a NUL in the path, and one client address that is not aninetTestConsumerKeepsEntriesBesideInvalidTextDB(activitylog; the opslog test does the same for message, component and attrs), run on the previous revision of this branch for the before valueBenchmarkLoggedInfoallocationsBenchmarkLoggedInfotimeThe before numbers come from the base commit with the same tests adapted to the old wiring, where
configureOperationalLoggingtook a Redis config and the activity writer was built inline inmain. Neither that harness nor the throughput harness is committed. The throughput and benchmark rows were measured after the rebase, on a busy host. Earlier runs at load average 15 to 20 gave 20,100 to 26,600 entries/s with Redis refused or unreachable against 19,400 to 23,000 with no event bus, and 27.6 to 34.1 µs/op before against 1.46 to 1.56 µs/op after forBenchmarkLoggedInfo.The base commit also loses the invalid-byte batch above: its Redis JSON round trip replaced the
0xFFbut not the NUL, and the bad address failed the batch on every path (from reading the code). In the after benchmark the consumer cannot reach Postgres, so the buffer fills and most iterations take the drop path, which costs the same channel select as a successful send. Benchmark allocations count every goroutine.Encoding non-scalar attributes at log time costs 2 allocations, 33 bytes, and about 0.1 µs for each such attribute, such as an
error(a one-off benchmark of the handler alone against the previous revision).BenchmarkLoggedInfologs scalars only, so its numbers do not include this.Total Redis traffic falls too, based on reading the code rather than an end-to-end count. Before, each logged request cost two
RPUSHcalls on the request goroutine, each consumer polled withEVALSHAevery two seconds, and each persisted row cost onePUBLISH. After, each persisted row still costs onePUBLISH, sent from the hub's goroutine.Validation
All checks below ran on the branch after rebasing onto the current base. The rebase had no conflicts, and the branch touches no generated artifacts.
make embed-stub,go build ./...,gofmt -l .(empty),go vet ./...: pass.make lint-changed: 0 issues.GOFLAGS=-p=6 make test-go: 159 of 160 packages pass.internal/policyfailedTestResolveViewerScopeParityonce, on a 25 ms policy-evaluation timeout while the host load average was above 150. That package imports none of the packages this branch changes, and the test and the whole package pass when run alone.SILO_TEST_DATABASE_URLset, after applying migrations:./cmd/silo,./internal/opslog/...,./internal/activitylog/...,./internal/logstream/...,./internal/api, and theLog|Audit|Operational|Sockettests in./internal/apiv2and./internal/api/handlers: pass.go test -raceon./internal/logstream,./internal/opslogand./internal/activitylog(with the database), and on the two pipeline tests in./cmd/silo: pass.make verify-settings-bindings-all verify-playback-fixtures verify-route-inventory verify-migration-ledger verify-scenario-catalogs verify-offline-routes verify-apiv2-openapi verify-apiv2-contract verify-apiv2-fixtures verify-local-pathsandTestCommittedArtifactMatchesRouter: pass.logstreambuffer and drain: a full buffer drops and counts without blocking; batching by size and interval; the final flush keeps context values without the cancellation, and every attempt has a deadline; a batch that fails twice with a refused connection is persisted on the third attempt with nothing counted as dropped; a batch the server rejects as a whole is dropped after one attempt; a batch with one rejected value keeps the other rows and counts one drop; a batch waiting between retries gets one last attempt when the drain stops; a hung insert is cut off by the deadline and retried; error classification, including read-only refusals and the errors a realpgxpoolreturns for a refused connection and a closed pool.logstreamtext: invalid UTF-8 and NUL become U+FFFD, clean text is returned without allocating, and\u0000escapes are replaced without touching an escaped backslash followed byu0000.logstreamhub:PublishAppendsreturns without waiting while every publish hangs, local subscribers still receive rows, and the queue overflow is counted; queued rows reach the event bus in order beforeClosereturns; a failing event bus is logged once, not per row.opslog: a stopping consumer that cannot reach Postgres counts the dropped batch, reports it on the console, and writes nothing back into the pipeline; a logged map and slice changed after the call keep their logged values; a value JSON cannot encode is kept as text.opslogandactivitylog(database-backed): a consumer stopped with 60 entries buffered persists all 60 and delivers them to a local live-tail subscriber; a batch with invalid bytes and one bad client address keeps every row but the bad address. Both invalid-byte tests fail on the previous revision (0 rows kept). Inopslog, a consumer persists 1,000 entries in 54 to 59 ms while every cross-node publish hangs (77 to 133 ms after the rebase, on a busier host); the first revision of this change took 26 s.SILO_TEST_DATABASE_URLfor these packages, so the database-backed consumer tests skip there.Risks
ops_log:bufferandactivity_log:bufferRedis lists. An old node drains both lists once, when its shutdown begins, and stops as soon as they are empty. It keeps pushing for the rest of its shutdown: the HTTP drain (up to 30 s), playback cleanup, and the remaining deferred stops. During a rolling upgrade, other old nodes still drain those entries. The entries the last old node logs during its own shutdown stay in Redis and never reach Postgres, and so does any backlog it had not drained, for example after Postgres trouble. On a single-node upgrade that covers the whole shutdown of the old node. App entries among them also went to stderr and OTLP; audit entries have no other copy. The keys have no TTL. Release notes should say: once no pre-upgrade node is running, runDEL ops_log:buffer activity_log:buffer.log.Fatalfwrites just before the process exits. Before, the synchronousRPUSHkept that record for another node, or the restarted node, to persist, so the reason for a fatal exit appeared in the admin log view. Now it reaches stderr and OTLP only. Graceful shutdown flushes the buffer.buffer_full. The Redis path had no size limit on its list but dropped each batch after three attempts over about six seconds. Dropped audit entries are lost for good.inet, is dropped and counted on its own. A batch with such a row costs up to 100 single-row inserts. A NUL or invalid byte in a stored entry now shows as U+FFFD.Checklist
AI Disclosure
Harness: Claude Code, running in T3 Code
Tool(s): Claude Code built-in tools (shell, file read/edit, Workflow subagents), GitHub CLI (gh)
Model(s): claude-opus-5-5[1m] for the main session and all subagents
Involvement: Fully AI-generated; maintainer review pending
Adversarial review: a separate reviewer subagent (claude-opus-5-5) reviewed the full diff twice. Each round re-ran the before and after measurements in scratch worktrees of the base commit and the branch, and checked shutdown order, the multi-node live tail, the validation-task line, and the lint and test gates.
Round 1 reviewed the first revision. It confirmed the recursion hang on the base commit (171 connection attempts and 6
RPUSHin 10 s), both pipeline tests failing there and passing on the branch, and that revision's 2 → 0 Redis-command and 41 → 13 allocation numbers. Findings and resolutions:/api/v2requests. Fixed in the metric help, the doc, and this description.DELstep for release notes and in the doc.log.Fatalfreason no longer reaches the database log. Added to Risks and the doc.slog.Infodid not reproduce on a loaded host (52 µs to 1.45 ms). The table now gives a bound with the observed range.Round 2 reviewed the second revision. It reproduced every number in the table:
slog.Infowith Redis refused went from no return within 2 s (20 Redis operations) to 472 µs (0), a logged request from 200 to 0 Redis commands over 100 requests,BenchmarkLoggedInfofrom 41 to 6 allocs/op, and persistence with Redis refused or unreachable at about 10,600 entries/s against 12,300 with no bus, on a busier host. Findings and resolutions:0xFFbyte in its path orUser-Agentmade Postgres reject the whole batch, losing up to 100 other audit entries. The reviewer reproduced it against the test database (0 of 3 rows kept). Fixed: both consumers replace invalid UTF-8 and NUL bytes in text fields and\u0000escapes in attrs JSON, and a batch with a rejected value (class 22) is inserted row by row. New database-backed tests keep 4 of 5 rows where the previous revision kept 0.KindAnyattributes were encoded on the consumer goroutine, up to seconds after the call, so a caller that changed a logged map could crash the node. Fixed: the handler encodes them when the record is logged. New handler tests cover it; the cost is measured above.🤖 Generated with Claude Code