Skip to content

feat(scontext)!: add clear helpers and presence masks - #139

Merged
Suhaibinator merged 3 commits into
mainfrom
codex/context-clear-helpers
Sep 24, 2026
Merged

Suhaibinator merged 3 commits into
mainfrom
codex/context-clear-helpers

Conversation

@Suhaibinator

@Suhaibinator Suhaibinator commented Sep 24, 2026 •

Copy link
Copy Markdown
Owner

Clearing request identity now removes both its stored values and presence, so callers can clone a context and run actor-free follow-up work without inheriting an authenticated user. Adds all clear helpers requested in #138, including atomic ClearIdentity and ClearClientInfo, with exact generic-type matching, in-place mutation, and no wrapper creation.

child := scontext.CopySRouterContext[T, U](ctx, ctx)
child = scontext.ClearIdentity[T, U](child)

Correlation clears invalidate the request logger; existing logger snapshots remain immutable. ClearRequestLogger removes the source and cache. Documentation and a runnable identity-context example explain clone-first isolation and logger reacquisition.

The 13 private context presence booleans are packed into a mutex-protected uint16 mask. Correlation snapshots now copy only their four relevant presence bits into a private mask instead of expanding them into booleans. Existing context setter/getter signatures and explicitly present zero/nil semantics are preserved.

Breaking API change

Replace c.TraceIDSet, c.BuildIDSet, c.ConfigIDSet, and c.UserIDSet with c.HasTraceID(), c.HasBuildID(), c.HasConfigID(), and c.HasUserID(). The value fields remain exported. Populate snapshots through GetCorrelation; struct literals can no longer set presence. Default struct serialization no longer includes the removed presence fields. The context guide documents migration and includes a runnable public API example.

The zero snapshot has no values present. Snapshots retain their values and presence after later writes/clears, and unrelated client/route metadata does not affect snapshot equality. Tests cover all 16 presence combinations and these invariants.

Validation

  • go test ./..., go vet ./..., and go build ./examples/... pass.
  • go test -race -coverpkg=./pkg/...,./internal/requestlog -coverprofile=/tmp/srouter-clear-coverage.out ./... passes; aggregate coverage 97.8%.
  • go test ./internal/doccheck, go run ./examples/identity-context, and golangci-lint run --timeout=5m pass (0 lint issues).
  • Regression coverage includes zero/nil values, repeated clears, mismatched/missing wrappers, re-setting, unrelated-state preservation, both copy helpers, shared mutation, concurrent reads/writes/copies, logger field removal, and clears during blocked logger derivation.

Context-mask measurements

Go 1.27.1, darwin/arm64. Compared base c4d1d92 with the context-mask commit b750dc9 using identical benchmark code, three runs each; timings below are medians. Timing samples are descriptive, not a statistical speedup claim.

Context size decreases by 16 bytes: int IDs 288 → 272 bytes; string and [16]byte IDs 296 → 280 bytes. The measured int context allocation stays in the same allocator size class.

Benchmark Before ns/op After ns/op B/op (unchanged) allocs/op (unchanged)
Context create 66.32 55.67 288 1
Context copy 70.86 68.21 384 3
Correlation + fields, depth 0 65.00 63.63 256 1
Correlation + fields, depth 5 65.59 64.77 256 1
Cached logger 6.139 6.240 0 0
Logger derivation, default encoder 379.5 393.4 1618 6
Logger derivation, explicit encoder 374.3 396.6 1618 6
Logger derivation, zap.Any 725.7 711.0 2935 12

Reproduce with go test ./pkg/scontext -run TestContextSize -v -bench 'Benchmark(Context|Correlation|GetLoggerFastPath|GetLoggerDerivation)' -benchmem -count=3.

Correlation-mask measurements

Compared 2d120d6 (context mask with boolean Correlation fields) against the additional Correlation mask change. Go 1.27.1, darwin/arm64; five runs per version, medians below. Allocation sizes and counts are unchanged in all measured paths.

Benchmark Before ns/op After ns/op
GetCorrelation alone 25.89 23.01
Correlation + fields, depth 0 63.74 61.82
Correlation + fields, depth 5 65.49 63.15
Cached logger 6.253 6.332
Logger derivation, default encoder 384.1 381.2
Logger derivation, explicit encoder 389.2 392.7
Logger derivation, zap.Any 671.9 699.1

The isolated snapshot read measured about 11% lower latency, with zero allocations before and after. Broader logger results are mixed, so this is not a general throughput claim. Alignment keeps Correlation size unchanged: 64 bytes for int IDs, 72 bytes for string/[16]byte IDs. The earlier 16-byte context-size reduction remains.

Reproduce with go test ./pkg/scontext -run TestCorrelationSize -v -bench 'Benchmark(GetCorrelation|Correlation|GetLoggerFastPath|GetLoggerDerivation)' -benchmem -count=5.

Closes #138

Replace the manual index-based iteration over `typ.NumField()` and
`typ.Field(i)` with the more idiomatic `range typ.Fields()` loop
introduced in Go 1.23.
@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.92%. Comparing base (c4d1d92) to head (498a0c4).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #139      +/-   ##
==========================================
+ Coverage   99.79%   99.92%   +0.12%     
==========================================
  Files          25       26       +1     
  Lines        2484     2604     +120     
==========================================
+ Hits         2479     2602     +123     
+ Misses          5        2       -3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Suhaibinator Suhaibinator changed the title feat(scontext): add clear helpers and pack presence flags feat(scontext)!: add clear helpers and presence masks Sep 24, 2026
@Suhaibinator
Suhaibinator merged commit f384154 into main Sep 24, 2026
11 checks passed
@Suhaibinator
Suhaibinator deleted the codex/context-clear-helpers branch September 24, 2026 06:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

scontext: add ClearX functions for every settable SRouterContext field

1 participant