Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ 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.

- **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:
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 hierarchy to `sentinel_ancestors`.

```go
var (
Expand Down Expand Up @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions errx.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
20 changes: 20 additions & 0 deletions errx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
12 changes: 12 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
11 changes: 9 additions & 2 deletions json/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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"}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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**: Parent sentinels are included in the `sentinel_ancestors` field; the `sentinels` field continues to contain only direct classifications.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: document the remaining loss of hierarchy information

The additive format is appropriate for the v1 option in #59, but this limitations entry should explicitly say that it preserves a flattened set of ancestor texts, not parent-child relationships. With multiple direct sentinels, a consumer cannot determine which ancestor belongs to which direct sentinel; intermediate edges and distinct identities sharing the same text are also not represented.

Please retain that limitation here and distinguish it from the future work in #37: a registry can resolve known texts to local sentinel values for matching, but this payload alone cannot reconstruct the original graph. No schema redesign is needed for this PR.

- **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.
59 changes: 59 additions & 0 deletions json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`

Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -362,6 +366,61 @@ 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 {
if !isPureSentinel(parent) {
continue
}
Comment on lines +412 to +415

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid rewalking every parent's subtree during ancestor collection

isPureSentinel calls errx.IsDisplayable, which performs a chain-wide errors.As search. Calling it for every parent re-traverses each remaining subtree; the visited map only guards addSentinelParents, not those nested searches.

A concrete valid DAG is built by repeatedly assigning current = errx.NewSentinel(label, leaf, current), with a shared leaf sentinel as the first parent. A single purity check is linear on this shape, but checking every remaining ancestor's subtree makes the new collection pass quadratic. WithMaxDepth does not bound this work when the hierarchy is attached as a classification to a plain error.

Please avoid recursive displayability detection at every parent. Once the root has passed the chain-wide displayable check, propagate that result and use shallow attribute/trace-kind filtering during descent, or compute the relevant properties in one traversal. Add a scaling benchmark for this DAG shape to guard against repeated subtree scans.

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
Expand Down
48 changes: 48 additions & 0 deletions json/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,48 @@ 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)
Comment on lines +213 to +216

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: extend coverage for the new ancestor contract

This diamond tests deduplication of a shared parent object, but not deduplication by text across distinct objects. Please add two different NewSentinel("same", ...) parents, one pointing to a and the other to b; the expected ancestors are [same, a, b]. Both subtrees must still be visited even though their parent texts coincide.

Please also cover Marshal(child) directly, which exercises the separate node path in sentinelAncestorsForLevel, and mixed sentinel/attribute/trace/displayable parents to lock down the new field's filtering behavior. Existing assertions about Sentinels do not verify SentinelAncestors. These are regression-coverage requests, not claims that the current implementation fails those cases.

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_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")
Expand Down Expand Up @@ -249,9 +291,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" {
Expand Down
2 changes: 1 addition & 1 deletion json/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
//
Expand Down
Loading