diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 126accc..4be8e60 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -35,7 +35,7 @@ jobs: uses: golangci/golangci-lint-action@v9 with: args: --timeout=30m - version: v2.13.2 + version: v2.15.0 - name: Run govulncheck run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index b86add8..6c891d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **JSON serializes hierarchical sentinel parents** ([#59]) — adds the public + `SentinelParents` accessor and an additive `sentinel_ancestors` JSON field containing + flattened, deduplicated parent sentinel texts while preserving the existing `sentinels` field. + The new field preserves ancestor membership, not the parent-child graph. + - **Repository community health and security governance** ([#67]) — adds `SECURITY.md` defining supported release lines and private vulnerability reporting, adds `CODE_OF_CONDUCT.md` (Contributor Covenant v2.1), and updates `CONTRIBUTING.md` references. - **Conditional stack capture in `stacktrace`** ([#40]) — new helpers capture a stack trace only when the cause chain does not already carry one, mirroring `emperror.dev/errors`'s `WrapIf`/`WithStackIf` pattern without pulling traces into the zero-dependency core: diff --git a/README.md b/README.md index ae2bbf4..fcc944d 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,9 @@ need to tag it; use `Wrap` when you also want to add context about where/why it #### Hierarchical sentinels Pass parent sentinels to build a taxonomy. A child matches itself *and* every parent. +`errx.SentinelParents(child)` returns its direct parents for inspection; treat the returned +slice as read-only. The JSON serializer keeps direct values in `sentinels` and writes the +flattened, deduplicated parent texts to `sentinel_ancestors`. ```go var ( @@ -636,6 +639,8 @@ when you need to pass plain `error` values. ### Inspection +- **`SentinelParents(c Classified) []Classified`** — direct parents of an errx sentinel; + returns nil for other classifications. Treat the returned slice as read-only. - **`IsDisplayable(err error) bool`** / **`DisplayText(err error) string`** - **`DisplayTextDefault(err error, def string) string`** — fallback on a miss. - **`DisplayTextOrEmpty(err error) string`** — `""` on a miss; safe for user surfaces. diff --git a/errx.go b/errx.go index f9d6199..42831fc 100644 --- a/errx.go +++ b/errx.go @@ -270,6 +270,18 @@ func NewSentinel(text string, parents ...Classified) Classified { return &sentinel{text: text, parents: parents} } +// SentinelParents returns the direct parents of c when c is an errx sentinel. +// It returns nil when c is nil or is not a sentinel. +// +// The returned slice aliases internal storage and must be treated as read-only. +func SentinelParents(c Classified) []Classified { + s, ok := c.(*sentinel) + if !ok || s == nil { + return nil + } + return s.parents +} + // Wrap wraps an error with additional context text and optional classification sentinels. // The attached classification sentinels can be used later to identify the error using errors.Is, // as well as add displayable errors. diff --git a/errx_test.go b/errx_test.go index 96b7705..6752079 100644 --- a/errx_test.go +++ b/errx_test.go @@ -20,6 +20,26 @@ func TestNewSentinel(t *testing.T) { } } +func TestSentinelParents(t *testing.T) { + root := errx.NewSentinel("root") + parent := errx.NewSentinel("parent", root) + child := errx.NewSentinel("child", parent) + + parents := errx.SentinelParents(child) + if len(parents) != 1 || parents[0] != parent { + t.Fatalf("SentinelParents(child) = %v, want [parent]", parents) + } + if got := errx.SentinelParents(root); got != nil { + t.Errorf("SentinelParents(root) = %v, want nil", got) + } + if got := errx.SentinelParents(errx.NewDisplayable("display")); got != nil { + t.Errorf("SentinelParents(displayable) = %v, want nil", got) + } + if got := errx.SentinelParents(nil); got != nil { + t.Errorf("SentinelParents(nil) = %v, want nil", got) + } +} + // TestWrapWithTag tests wrapping with a classification tag func TestWrapWithTag(t *testing.T) { tag := errx.NewSentinel("tag error") diff --git a/example_test.go b/example_test.go index 9fb29fb..3624cbe 100644 --- a/example_test.go +++ b/example_test.go @@ -30,6 +30,18 @@ func Example() { // Error is classified as not found } +func ExampleSentinelParents() { + ErrDatabase := errx.NewSentinel("database") + ErrTimeout := errx.NewSentinel("timeout", ErrDatabase) + + for _, parent := range errx.SentinelParents(ErrTimeout) { + fmt.Println(parent.Error()) + } + + // Output: + // database +} + // ExampleWrap demonstrates wrapping errors with context and tags func ExampleWrap() { ErrDatabase := errx.NewSentinel("database error") diff --git a/json/README.md b/json/README.md index 6aadbd0..0822959 100644 --- a/json/README.md +++ b/json/README.md @@ -108,7 +108,8 @@ jsonBytes, _ := errxjson.Marshal(err, errxjson.WithAttributes(false)) ### WithSentinels Include sentinel text in the output. The default is `true`; pass `false` to omit the -`sentinels` field when those messages are internal implementation details. +`sentinels` and `sentinel_ancestors` fields when those messages are internal +implementation details. ```go jsonBytes, _ := errxjson.Marshal(err, errxjson.WithSentinels(false)) @@ -165,6 +166,7 @@ The serialized error has the following structure: "message": "error message from Error()", "display_text": "user-facing message (if displayable error present)", "sentinels": ["list", "of", "sentinel", "texts"], + "sentinel_ancestors": ["parent", "grandparent"], "attributes": [ {"key": "user_id", "value": 123}, {"key": "action", "value": "delete"} @@ -196,6 +198,11 @@ Sentinels with attributed or traced parents keep their own sentinel text; classifications with a displayable anywhere in their chain remain excluded from `sentinels` and provide `display_text` instead. +The `sentinel_ancestors` field contains pure-sentinel parents of the direct sentinels +at that serialized error level. It traverses parents depth-first in declaration order +and deduplicates by text; parents attached to a cause appear on that cause rather +than leaking into the outer error. `WithSentinels(false)` omits both sentinel fields. + ## Examples ### Displayable Error @@ -292,5 +299,5 @@ json.Unmarshal(jsonBytes, &serialized) ## Limitations - **No Deserialization**: This package does not provide deserialization (JSON to error) functionality. Errors are runtime constructs and cannot be meaningfully reconstructed from JSON. -- **Sentinel Hierarchy**: Parent sentinels in hierarchical relationships are not serialized - only direct sentinels are included. +- **Sentinel Hierarchy**: `sentinel_ancestors` preserves a flattened, deduplicated list of parent texts, while `sentinels` contains direct classifications. The JSON does not identify which direct sentinel owns each parent, preserve parent-child edges, or distinguish sentinels with the same text. A future registry-backed decoder could resolve known texts to local sentinels, but this payload cannot reconstruct the original graph. - **Attribute Ordering**: The order of attributes in the JSON output is stable for a given error but should not be relied upon for semantic meaning. diff --git a/json/json.go b/json/json.go index 10037df..6b54576 100644 --- a/json/json.go +++ b/json/json.go @@ -43,6 +43,9 @@ type SerializedError struct { // Sentinels lists all classification sentinel texts found in this error Sentinels []string `json:"sentinels,omitempty"` + // SentinelAncestors lists the deduplicated parent sentinel texts for this error level. + SentinelAncestors []string `json:"sentinel_ancestors,omitempty"` + // Attributes contains structured key-value pairs attached to this error Attributes []SerializedAttr `json:"attributes,omitempty"` @@ -271,6 +274,7 @@ func toSerializedError(err error, cfg *config, visited *visitedSet, depth int) * // classifications and the node itself (if it's a pure sentinel) count. if cfg.includeSentinels { result.Sentinels = sentinelsForLevel(levelCls, node) + result.SentinelAncestors = sentinelAncestorsForLevel(levelCls, node) } // Attributes: chain-wide (errx.ExtractAttrs walks the chain). @@ -362,6 +366,64 @@ func sentinelsForLevel(classifications []errx.Classified, node error) []string { return sentinels } +// sentinelAncestorsForLevel returns the pure-sentinel parents of the +// classifications attached to this error level or represented by its node. +// Parents are traversed depth-first in declaration order and deduplicated by text. +func sentinelAncestorsForLevel(classifications []errx.Classified, node error) []string { + var ancestors []string + var seenTexts map[string]bool + var visited map[errx.Classified]bool + + for _, cls := range classifications { + if isPureSentinel(cls) { + addSentinelParents(cls, &ancestors, &seenTexts, &visited) + } + } + if cls, ok := node.(errx.Classified); ok && isPureSentinel(cls) { + addSentinelParents(cls, &ancestors, &seenTexts, &visited) + } + + return ancestors +} + +// addSentinelParents appends pure-sentinel parents and their ancestors, +// guarding against repeated sentinels and malformed cycles. +func addSentinelParents( + cls errx.Classified, + ancestors *[]string, + seenTexts *map[string]bool, + visited *map[errx.Classified]bool, +) { + parents := errx.SentinelParents(cls) + if len(parents) == 0 { + return + } + + // SentinelParents only returns a non-empty slice for the internal, + // pointer-backed sentinel type, which is safe to use as a map key. + if *visited == nil { + *visited = make(map[errx.Classified]bool) + } + if (*visited)[cls] { + return + } + (*visited)[cls] = true + + for _, parent := range parents { + // The root passed the chain-wide displayable check before this walk. + // Every reachable parent is therefore non-displayable, so checking + // its own kind is enough and avoids rescanning its entire subtree. + if !isPureSentinelKind(parent) { + continue + } + text := parent.Error() + if !rememberSentinel(text, seenTexts) { + *ancestors = append(*ancestors, text) + } + addSentinelParents(parent, ancestors, seenTexts, visited) + } +} + // serializeAttributes extracts and serializes attributes from an error. // Attribute values whose JSON encoding fails (e.g. a func() value) are // replaced with a fmt.Sprintf("%+v", v) fallback string so a single bad @@ -541,20 +603,26 @@ func addPureSentinels(classifications []errx.Classified, sentinels *[]string, se } } -// isPureSentinel excludes attribute and trace carriers by their own type, +// isPureSentinelKind excludes attribute and trace carriers by their own type, // including empty external implementations. An attributed or traced parent -// does not change a sentinel's kind. Displayable detection remains chain-wide -// because errx does not yet expose a displayable-kind interface. -func isPureSentinel(cls errx.Classified) bool { +// does not change a sentinel's kind. +func isPureSentinelKind(cls errx.Classified) bool { // Use the public attribute interface here when issue #63 introduces it. switch cls.(type) { case interface{ Attrs() []errx.Attr }, stacktrace.Tracer: return false default: - return !errx.IsDisplayable(cls) + return true } } +// isPureSentinel also excludes classifications with a displayable anywhere in +// their chain. Detection remains chain-wide because errx does not yet expose +// a displayable-kind interface. +func isPureSentinel(cls errx.Classified) bool { + return isPureSentinelKind(cls) && !errx.IsDisplayable(cls) +} + // addSelfAsPureSentinel checks if the error itself is a pure sentinel and adds it. func addSelfAsPureSentinel(err error, sentinels *[]string, seen *map[string]bool) { cls, ok := err.(errx.Classified) diff --git a/json/json_bench_test.go b/json/json_bench_test.go index 7167ffe..e4dd10b 100644 --- a/json/json_bench_test.go +++ b/json/json_bench_test.go @@ -71,3 +71,24 @@ func BenchmarkMarshal_FreshStackTrace(b *testing.B) { _, _ = errxjson.Marshal(err) } } + +// BenchmarkMarshal_SentinelAncestorDAG guards against repeatedly searching +// each parent's subtree while collecting ancestors. The shared leaf is the +// first parent, and each new sentinel also points to the previous one. +func BenchmarkMarshal_SentinelAncestorDAG(b *testing.B) { + for _, depth := range []int{32, 64, 128} { + b.Run(fmt.Sprintf("depth_%d", depth), func(b *testing.B) { + leaf := errx.NewSentinel("leaf") + current := leaf + for i := 0; i < depth; i++ { + current = errx.NewSentinel(fmt.Sprintf("node_%d", i), leaf, current) + } + err := errx.Classify(errors.New("base"), current) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + _, _ = errxjson.Marshal(err) + } + }) + } +} diff --git a/json/json_test.go b/json/json_test.go index 52e8714..4194ce2 100644 --- a/json/json_test.go +++ b/json/json_test.go @@ -209,6 +209,111 @@ func TestMarshal_HierarchicalSentinels(t *testing.T) { } } +func TestMarshal_HierarchicalSentinelAncestors(t *testing.T) { + shared := errx.NewSentinel("shared") + left := errx.NewSentinel("left", shared) + right := errx.NewSentinel("right", shared) + child := errx.NewSentinel("child", left, right) + testErr := errx.Classify(errors.New("hierarchical error"), child) + + data, err := errxjson.Marshal(testErr) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + var result errxjson.SerializedError + if err := json.Unmarshal(data, &result); err != nil { + t.Fatalf("Unmarshal error: %v", err) + } + if got, want := fmt.Sprint(result.Sentinels), "[child]"; got != want { + t.Errorf("Sentinels = %s, want %s", got, want) + } + if got, want := fmt.Sprint(result.SentinelAncestors), "[left shared right]"; got != want { + t.Errorf("SentinelAncestors = %s, want %s", got, want) + } +} + +func TestMarshal_SentinelAncestorsDeduplicateTextWithoutSkippingBranches(t *testing.T) { + a := errx.NewSentinel("a") + b := errx.NewSentinel("b") + left := errx.NewSentinel("same", a) + right := errx.NewSentinel("same", b) + child := errx.NewSentinel("child", left, right) + + result := errxjson.ToSerializedError(errx.Classify(errors.New("base"), child)) + if got, want := fmt.Sprint(result.Sentinels), "[child]"; got != want { + t.Errorf("Sentinels = %s, want %s", got, want) + } + if got, want := fmt.Sprint(result.SentinelAncestors), "[same a b]"; got != want { + t.Errorf("SentinelAncestors = %s, want %s", got, want) + } +} + +func TestMarshal_HierarchicalSentinelNode(t *testing.T) { + root := errx.NewSentinel("root") + child := errx.NewSentinel("child", root) + + data, err := errxjson.Marshal(child) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + var result errxjson.SerializedError + if err := json.Unmarshal(data, &result); err != nil { + t.Fatalf("Unmarshal error: %v", err) + } + if got, want := fmt.Sprint(result.Sentinels), "[child]"; got != want { + t.Errorf("Sentinels = %s, want %s", got, want) + } + if got, want := fmt.Sprint(result.SentinelAncestors), "[root]"; got != want { + t.Errorf("SentinelAncestors = %s, want %s", got, want) + } +} + +func TestMarshal_SentinelAncestorsFilterMetadataParents(t *testing.T) { + root := errx.NewSentinel("root") + child := errx.NewSentinel("child", root, errx.Attrs("key", "value"), stacktrace.Here()) + + result := errxjson.ToSerializedError(errx.Classify(errors.New("base"), child)) + if got, want := fmt.Sprint(result.Sentinels), "[child]"; got != want { + t.Errorf("Sentinels = %s, want %s", got, want) + } + if got, want := fmt.Sprint(result.SentinelAncestors), "[root]"; got != want { + t.Errorf("SentinelAncestors = %s, want %s", got, want) + } +} + +func TestMarshal_SentinelAncestorsExcludeDisplayableChain(t *testing.T) { + root := errx.NewSentinel("root") + displayable := errx.NewDisplayable("public message") + child := errx.NewSentinel("child", root, displayable) + + result := errxjson.ToSerializedError(errx.Classify(errors.New("base"), child)) + if len(result.Sentinels) != 0 || len(result.SentinelAncestors) != 0 { + t.Errorf("sentinel fields = %v, %v; want empty", result.Sentinels, result.SentinelAncestors) + } + if result.DisplayText != "public message" { + t.Errorf("DisplayText = %q, want public message", result.DisplayText) + } +} + +func TestMarshal_WithSentinelsFalseOmitsAncestors(t *testing.T) { + root := errx.NewSentinel("root") + child := errx.NewSentinel("child", root) + data, err := errxjson.Marshal( + errx.Classify(errors.New("error"), child), + errxjson.WithSentinels(false), + ) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + var result errxjson.SerializedError + if err := json.Unmarshal(data, &result); err != nil { + t.Fatalf("Unmarshal error: %v", err) + } + if len(result.Sentinels) != 0 || len(result.SentinelAncestors) != 0 { + t.Errorf("sentinel fields should be omitted, got sentinels=%v ancestors=%v", result.Sentinels, result.SentinelAncestors) + } +} + func TestMarshal_ComplexError(t *testing.T) { // Create a complex error with all features baseErr := errors.New("connection failed") @@ -249,9 +354,15 @@ func TestMarshal_ComplexError(t *testing.T) { if len(result.Sentinels) != 0 { t.Errorf("top-level Sentinels = %v, want empty (sentinel attached at inner level)", result.Sentinels) } + if len(result.SentinelAncestors) != 0 { + t.Errorf("top-level SentinelAncestors = %v, want empty (sentinel attached at inner level)", result.SentinelAncestors) + } if result.Cause == nil { t.Fatal("Cause is nil; sentinel should be reported at this level") } + if got, want := fmt.Sprint(result.Cause.SentinelAncestors), "[database retryable]"; got != want { + t.Errorf("Cause.SentinelAncestors = %s, want %s", got, want) + } gotTimeout := false for _, s := range result.Cause.Sentinels { if s == "timeout" { diff --git a/json/options.go b/json/options.go index c902cd6..562b12f 100644 --- a/json/options.go +++ b/json/options.go @@ -116,7 +116,7 @@ func WithAttributes(include bool) Option { // // Use WithSentinels(false) when the sentinel text is considered internal // implementation detail that should not appear in serialized output. Suppresses -// the "sentinels" field. +// the "sentinels" and "sentinel_ancestors" fields. // // Example: //