Go Services & Networking
20 lessons from merged PRs in Caddy, Prometheus and etcd, summarized in our own words. Real concurrency, HTTP, TLS and storage fixes.
brain_seed_starter(instance_id="<your-brain-id>", stack="go")20 fixes from merged PRs
Every lesson below is a short summary in our own words and links to its upstream GitHub pull request in a permissive-licensed repository. Seed them into your Brain so your coding agent can find them when a similar problem comes up.
- Symptom
After Caddy 2.8, a try_files based single-page-app setup breaks for requests to the root path because the root request is no longer routed as before.
Cause and fixCause: SanitizePathJoin's filepath.IsLocal check returned early for a request consisting only of a slash, before the trailing slash that other requests keep was re-added. Fix: SanitizePathJoin now runs the filepath.IsLocal check only when the cleaned request path is non-empty, and its existing tests were updated.
- Symptom
The hash action of Caddy's query log filter gives the same hash for every query parameter value, regardless of what was in the request.
Cause and fixCause: The filter hashed the action's Value field, which a hash action never fills, so each value became the hash of an empty string. Fix: The filter now hashes each real query parameter value, matching the cookie filter, and the multi-value test uses distinct inputs to verify different hashes.
- Symptom
Caddy panics with SIGSEGV when a header block combines conditional headers (? prefix) with an explicit defer, or when JSON config has an empty response object in headers or reverse_proxy.
Cause and fixCause: An empty response object creates a RespHeaderOps whose embedded *HeaderOps pointer is nil, and calling ApplyTo on it dereferences nil. Fix: ApplyTo was made nil-safe, following the same pattern already applied earlier to Provision.
- Symptom
Caddy redirects plain HTTP requests to an HTTPS address carrying an unexpected custom port instead of the default one, when a wildcard with explicit port and an exact host coexist.
Cause and fixCause: Automatic HTTPS groups domains by address in a map, and iterating that map in random order made the order of generated redirect routes unpredictable, so a wildcard route could win. Fix: Added a sort step in autohttps.go over the generated redirect routes so their order is deterministic, with an integration test covering the mixed wildcard and exact host setup.
- Symptom
Caddy's encode handler always picks gzip for Accept-Encoding: deflate, gzip, br, zstd, even though zstd or br would be preferable.
Cause and fixCause: When encodings share the same q-factor, ordering fell back to the left-to-right order in the header, and browsers list gzip first. Fix: encode.AcceptedEncodings now applies a built-in default priority of zstd, then br, then gzip, then deflate to break ties, unless the administrator set a preference order.
- Symptom
In Caddy, requiring client certificates for a wildcard hostname also demands them on a more specific subdomain site that never enabled mutual TLS.
Cause and fixCause: TLS connection policies are matched in order by server name, so the wildcard policy with client auth catches the specific hostname, which had no policy of its own to match earlier. Fix: The Caddyfile adapter now emits an empty connection policy for such hostnames, placed just above the first client-auth policy whose wildcard covers them, so first-match exempts them.
- Symptom
With Caddy's forward_auth and copy_headers, a request header is set to the raw placeholder text when the auth backend does not return that header.
Cause and fixCause: The request_header handler uses ReplaceKnown for placeholders, so a missing response header turned into the literal placeholder string instead of being skipped. Fix: The copy_headers shortcut now adds a 'not vars' matcher that checks the response header placeholder is non-empty before copying, producing more verbose JSON config.
- Symptom
TestOTLPWriteHandler in Prometheus fails intermittently in CI, with expected and actual timestamps differing by one millisecond.
Cause and fixCause: The test computed its input and its expected output from separate time.Now() calls, so the two values could differ by a few nanoseconds. Fix: In storage/remote/write_test.go the input and the expected output now use the same timestamp value.
- Symptom
After upgrading to a Prometheus release on AWS SDK v2, EC2 and Lightsail service discovery returns no targets when using the default credential chain, such as IAM roles.
Cause and fixCause: The code always created a StaticCredentialsProvider, even with empty access_key and secret_key, and AWS SDK v2 then errors with static credentials are empty instead of falling back. Fix: The static credentials provider is now created only when access_key and secret_key are actually configured, so the SDK's default credential chain applies otherwise.
- Symptom
The tsdb stale series compaction check can trigger compaction on an empty head because it divides by the head's series count, which can be zero.
Cause and fixCause: With zero series and some stale series the ratio becomes +Inf and passes the threshold; with zero of both it becomes NaN, which only happens to compare false. Fix: In tsdb/db.go the condition now checks numSeries > 0 first and computes the ratio inside that block; TestStaleSeriesCompactionWithZeroSeries covers an empty head.
- Symptom
Prometheus logs 'Failed to calculate size of wal dir' errors when WAL cleanup runs at the same moment as a metrics scrape.
Cause and fixCause: The WAL directory size is computed asynchronously on scrape, and files removed by concurrent cleanup produce not-exist errors during the directory walk. Fix: DirSize in tsdb/fileutil/dir.go now ignores os.ErrNotExist errors, which are expected during WAL cleanup, while other errors still propagate.
- Symptom
The PromQL error 'found duplicate series for the match group' shows its two series in a different order on repeated runs of the same query on the same data.
Cause and fixCause: The two label strings were formatted in the order the duplicate pair arrived from rightSigs, which depends on Go map iteration randomization upstream in rangeEval. Fix: VectorBinop in promql/engine.go now sorts the two label strings before building the error message; the rest of the text and semantics stay unchanged.
- Symptom
The Prometheus text-format and OpenMetrics parsers panic on a line like {A}0 with an unquoted name inside braces, which crashes the whole process during a scrape.
Cause and fixCause: After a label-name position followed by a comma or closing brace, the parser accepted any token as a metric-name shorthand, including bare identifiers that must be followed by an equals sign. Fix: The parsers now treat that position as a metric-name shorthand only when the token is a double-quoted string; bare identifiers must be followed by an equals sign, and tests for such inputs were added.
- Symptom
promtool tsdb create-blocks-from rules panics when the rule file contains a second YAML document.
Cause and fixCause: NewManager installed its no-op logger only once the default FileLoader had been built and had captured a nil logger, and the multi-document warning in rulefmt.Parse later dereferenced it. Fix: The logger defaulting in NewManager was moved earlier, ahead of everything that captures the logger, so the file loader receives a valid logger even when ManagerOptions.Logger is unset.
- Symptom
Several etcd servers repeatedly crash with a panic saying the commit index is beyond the last log index, after earlier network trouble and reconnects.
Cause and fixCause: A member accepted raft messages that were addressed to a different member ID, likely delivered wrongly by faulty network hardware, and then tried to apply their commit index. Fix: The etcd server now discards incoming raft messages whose destination field does not equal the local member ID, in server.go, with a unit test.
- Symptom
The etcd test TestMaintenanceSnapshotCancel panics in UnsafeRange during shutdown because the backend is already closed.
Cause and fixCause: Unlike SnapshotWithVersion, client.Snapshot does not wait for a first response, so the test could close the connection or stop the server before the server had opened boltdb. Fix: The integration test in maintenance_test.go now reads a few bytes from the snapshot stream first to be sure the server has opened boltdb.
- Symptom
In etcd's post-submit coverage job, flaky test failures prevent any coverage upload, so later pull requests fail Codecov checks on stale reports.
Cause and fixCause: The coverage reporting job stopped on a workflow failure and never uploaded a partial report, a behavior introduced when the job moved from GitHub workflows to Prow. Fix: The Makefile was changed so a partial coverage report is still uploaded when the workflow fails, for example because of flaky tests.
- Symptom
etcd logs a warning for every TLS handshake that ends in EOF, flooding logs in deployments where clients routinely close connections early.
Cause and fixCause: The TLS handshake error handler in the logging setup logged every error at warning level, including harmless EOF. Fix: In server/embed/config_logging.go an EOF during the TLS handshake is now logged at debug level only.
- Symptom
etcd's trace log entries have a different message string each time, such as trace[12345678] range, which prevents grouping and alerting in log platforms.
Cause and fixCause: logInfo() in pkg/traceutil/trace.go put a random number from rand.Int31() into the message, and the same random ID also appeared inside each step string. Fix: The message is now the constant string 'trace' and the random trace identifier is emitted as a separate structured field; trace_test.go was updated.
- Symptom
When adding an etcd member with a malicious peer URL, existing members can be redirected to arbitrary internal URLs while fetching the new member's version, a server-side request forgery risk.
Cause and fixCause: The HTTP client used for peer communication in cluster_util.go followed redirects returned by the peer. Fix: The change in server/etcdserver/cluster_util.go disables following redirects for peer HTTP requests.