From 98df98c9ad0321e05724934b882d49664499a89d Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:57:21 -0500 Subject: [PATCH 01/40] refactor(telemetry): define immutable trace identity and fallback Signed-off-by: Dharit Shah --- internal/telemetry/tracecontext/identity.go | 160 ++++++++ .../telemetry/tracecontext/identity_test.go | 358 ++++++++++++++++++ 2 files changed, 518 insertions(+) create mode 100644 internal/telemetry/tracecontext/identity.go create mode 100644 internal/telemetry/tracecontext/identity_test.go diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go new file mode 100644 index 0000000000..a8f69631ae --- /dev/null +++ b/internal/telemetry/tracecontext/identity.go @@ -0,0 +1,160 @@ +// Package tracecontext implements the versioned immutable work-item +// identity and signed trace-context envelope contract from ADR 0154. +// +// The package is pure: it performs no network I/O, reads no configuration, +// and never grants dispatch permission. It must stay importable from +// pkg/behaviourtest, so it must not depend on internal/cli, internal/repos, +// internal/layers, or the nested mintcore module. +package tracecontext + +import ( + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "net/url" + "strings" + "unicode/utf8" + + "go.opentelemetry.io/otel/trace" +) + +// EntityKind distinguishes the entity kinds that can share a forge +// container. GitLab issue and merge-request database IDs come from +// independent spaces, so the kind is part of every identity. +type EntityKind byte + +const ( + // KindWorkItem is an issue on GitHub, GitLab, or Jira. + KindWorkItem EntityKind = 0x01 + // KindChangeProposal is a GitHub pull request or a GitLab merge + // request. Jira has no change-proposal entity in this contract. + KindChangeProposal EntityKind = 0x02 +) + +// Valid reports whether k is a defined entity kind. +func (k EntityKind) Valid() bool { + return k == KindWorkItem || k == KindChangeProposal +} + +// Identity is the immutable binding of a forge entity (ADR 0154, D01): +// installation, forge instance, container, entity kind, and entity +// database ID. Display names, URLs, GitHub numbers, GitLab IIDs, and Jira +// keys are not identity components; docs/reference/trace-context.md holds +// the per-forge field mapping. +type Identity struct { + // Installation is the 128-bit installation identifier provisioned + // with the signing key pair. It is authenticated in envelopes but + // deliberately excluded from fallback derivation, per ADR 0154. + Installation [16]byte + // Instance is the normalized forge web base URL: lowercase + // scheme://host with no path and no trailing slash. Use + // NormalizeInstance to build it. + Instance string + // Container is the immutable repository or project database ID. + Container int64 + // Kind is the entity kind within the container. + Kind EntityKind + // Entity is the immutable entity database ID. + Entity int64 +} + +// Resolved reports whether the forge-side identity components are present +// and valid: a canonical instance, a container ID >= 1, a valid kind, and +// an entity ID >= 1. Installation is local configuration rather than event +// identity, so it is not part of resolution; admission checks it against +// the envelope separately. An unresolved identity must postpone dispatch +// (FR-002); it never derives a fallback. +func (id Identity) Resolved() bool { + return validInstance(id.Instance) && id.Container >= 1 && id.Kind.Valid() && id.Entity >= 1 +} + +// Fallback is the deterministic entity-derived context: a stable TraceID +// and a synthetic anchor SpanID. By contract, the anchor exists only as a +// parent reference, is never exported as a span, and is never repointed. +type Fallback struct { + TraceID trace.TraceID + AnchorSpanID trace.SpanID +} + +// identityDomain separates fallback derivation from every other use of +// SHA-256 in this package and in the envelope format. +const identityDomain = "fullsend.tracecontext.identity.v1" + +// DeriveFallback derives the v1 deterministic fallback context. The +// derivation covers the forge instance, container, kind, and entity — +// never the installation, per ADR 0154. It returns ok=false for an +// unresolved identity. The derivation is pure, so independent and +// concurrent first events converge on identical nonzero IDs. +func DeriveFallback(id Identity) (fb Fallback, ok bool) { + if !id.Resolved() { + return Fallback{}, false + } + h := sha256.New() + writeField := func(b []byte) { + var l [2]byte + binary.BigEndian.PutUint16(l[:], uint16(len(b))) + h.Write(l[:]) + h.Write(b) + } + writeField([]byte(identityDomain)) + writeField([]byte(id.Instance)) + var i64 [8]byte + binary.BigEndian.PutUint64(i64[:], uint64(id.Container)) + h.Write(i64[:]) + h.Write([]byte{byte(id.Kind)}) + binary.BigEndian.PutUint64(i64[:], uint64(id.Entity)) + h.Write(i64[:]) + + sum := h.Sum(nil) + copy(fb.TraceID[:], sum[0:16]) + copy(fb.AnchorSpanID[:], sum[16:24]) + // Deterministic nonzero guarantee: SHA-256 output is all-zero with + // probability 2^-128 (trace) / 2^-64 (span); substitute a documented + // nonzero value so callers never see an invalid ID. + if fb.TraceID == (trace.TraceID{}) { + fb.TraceID[15] = 0x01 + } + if fb.AnchorSpanID == (trace.SpanID{}) { + fb.AnchorSpanID[7] = 0x01 + } + return fb, true +} + +// NormalizeInstance canonicalizes a forge web base URL to the D01 instance +// form: lowercase scheme://host with no path, query, fragment, or user +// info. Only http and https are accepted; a bare "/" path is tolerated and +// stripped. All identity and envelope construction must use the normalized +// form so independent launches converge. +func NormalizeInstance(raw string) (string, error) { + if !utf8.ValidString(raw) { + return "", errors.New("tracecontext: instance must be valid UTF-8") + } + u, err := url.Parse(raw) + if err != nil { + return "", fmt.Errorf("tracecontext: parse instance URL: %w", err) + } + if u.Scheme == "" || u.Hostname() == "" { + return "", errors.New("tracecontext: instance URL needs a scheme and host") + } + if u.User != nil || strings.ContainsAny(raw, "?#") { + return "", errors.New("tracecontext: instance URL must be a bare scheme://host") + } + if u.Path != "" && u.Path != "/" { + return "", errors.New("tracecontext: instance URL must not carry a path") + } + scheme := strings.ToLower(u.Scheme) + if scheme != "http" && scheme != "https" { + return "", fmt.Errorf("tracecontext: unsupported instance scheme %q", u.Scheme) + } + normalized := scheme + "://" + strings.ToLower(u.Host) + if len(normalized) > 253 { + return "", errors.New("tracecontext: instance must be at most 253 bytes") + } + return normalized, nil +} + +func validInstance(instance string) bool { + normalized, err := NormalizeInstance(instance) + return err == nil && instance == normalized +} diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go new file mode 100644 index 0000000000..efeaacb11a --- /dev/null +++ b/internal/telemetry/tracecontext/identity_test.go @@ -0,0 +1,358 @@ +package tracecontext + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "os" + "os/exec" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + "go.opentelemetry.io/otel/trace" +) + +// v01Identity is the shared V01 fixture: one resolved identity per forge +// kind, exercised by the derivation, sensitivity, rename, and concurrency +// tests below. +func v01Identity() Identity { + return Identity{ + Installation: [16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}, + Instance: "https://github.com", + Container: 274390431, + Kind: KindWorkItem, + Entity: 2468913570, + } +} + +func mustHex(t *testing.T, s string) []byte { + t.Helper() + b, err := hex.DecodeString(s) + require.NoError(t, err) + return b +} + +// TestDeriveFallback_ResolvedAndNonzero is V01: the same resolved immutable +// identity derives a nonzero fallback, and repeated derivation in one +// process is deterministic. +func TestDeriveFallback_ResolvedAndNonzero(t *testing.T) { + fb, ok := DeriveFallback(v01Identity()) + require.True(t, ok, "resolved identity must derive a fallback") + assert.True(t, fb.TraceID.IsValid(), "derived TraceID must be nonzero") + assert.True(t, fb.AnchorSpanID.IsValid(), "derived anchor SpanID must be nonzero") + + again, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + assert.Equal(t, fb, again, "derivation must be deterministic") +} + +// TestDeriveFallback_ComponentSensitivity is V01: changing any binding +// component changes the derived identity, so distinct +// instances, containers, kinds, or entities cannot alias. +func TestDeriveFallback_ComponentSensitivity(t *testing.T) { + base, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + + changed := v01Identity() + changed.Instance = "https://ghe.example.com" + other, ok := DeriveFallback(changed) + require.True(t, ok) + assert.NotEqual(t, base, other, "forge instance must change identity") + + changed = v01Identity() + changed.Container = 274390432 + other, ok = DeriveFallback(changed) + require.True(t, ok) + assert.NotEqual(t, base, other, "container must change identity") + + changed = v01Identity() + changed.Kind = KindChangeProposal + other, ok = DeriveFallback(changed) + require.True(t, ok) + assert.NotEqual(t, base, other, "entity kind must change identity: GitLab issue and MR id spaces are independent") + + changed = v01Identity() + changed.Entity = 2468913571 + other, ok = DeriveFallback(changed) + require.True(t, ok) + assert.NotEqual(t, base, other, "entity must change identity") +} + +// TestDeriveFallback_InstallationExcluded pins the ADR 0154 rule: the +// fallback derivation covers forge instance, repository, and entity IDs — +// never the installation. +func TestDeriveFallback_InstallationExcluded(t *testing.T) { + base, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + + other := v01Identity() + other.Installation = [16]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} + got, ok := DeriveFallback(other) + require.True(t, ok) + assert.Equal(t, base, got, "installation must not participate in fallback derivation") +} + +// TestDeriveFallback_Unresolved is V01/FR-002: missing identity components +// are explicit unresolved outcomes, never a random or zero-context guess. +func TestDeriveFallback_Unresolved(t *testing.T) { + cases := map[string]Identity{ + "empty instance": func() Identity { i := v01Identity(); i.Instance = ""; return i }(), + "zero container": func() Identity { i := v01Identity(); i.Container = 0; return i }(), + "zero entity": func() Identity { i := v01Identity(); i.Entity = 0; return i }(), + "negative entity": func() Identity { i := v01Identity(); i.Entity = -1; return i }(), + "invalid kind": func() Identity { i := v01Identity(); i.Kind = EntityKind(0x00); return i }(), + "unknown kind": func() Identity { i := v01Identity(); i.Kind = EntityKind(0x7f); return i }(), + } + for name, id := range cases { + t.Run(name, func(t *testing.T) { + fb, ok := DeriveFallback(id) + assert.False(t, ok, "unresolved identity must be explicit") + assert.False(t, fb.TraceID.IsValid(), "unresolved identity must not fabricate a TraceID") + assert.False(t, fb.AnchorSpanID.IsValid(), "unresolved identity must not fabricate a SpanID") + assert.False(t, id.Resolved(), "Resolved must agree with DeriveFallback") + }) + } +} + +// TestIdentity_Resolved accepts the V01 fixture. +func TestIdentity_Resolved(t *testing.T) { + assert.True(t, v01Identity().Resolved()) +} + +// TestDeriveFallback_RenameStable documents the D01 rename rule: display +// names never enter the tuple, so a rename cannot change the binding. Two +// identities built from different display names for the same database IDs +// are the same identity. +func TestDeriveFallback_RenameStable(t *testing.T) { + before, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + + renamed := v01Identity() // same database IDs; only display names changed + after, ok := DeriveFallback(renamed) + require.True(t, ok) + assert.Equal(t, before, after, "a rename must not change trace identity") +} + +// TestDeriveFallback_MoveIsNewBinding documents the D01 move rule: moving an +// entity to another bound container changes the binding (container or +// entity database ID), which is a new identity, never a rename. +func TestDeriveFallback_MoveIsNewBinding(t *testing.T) { + base, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + + // Jira project move: same issue id, new project container. + moved := v01Identity() + moved.Container = 999888777 + after, ok := DeriveFallback(moved) + require.True(t, ok) + assert.NotEqual(t, base, after, "a moved entity has a new binding") + + // GitHub issue transfer: new container and new entity id. + transfered := v01Identity() + transfered.Container = 111222333 + transfered.Entity = 987654321 + after, ok = DeriveFallback(transfered) + require.True(t, ok) + assert.NotEqual(t, base, after, "a transferred entity has a new binding") +} + +// TestDeriveFallback_IIDsAreNotIdentity documents the D01 mapping: GitLab +// IIDs (and GitHub numbers, Jira keys) are display values. The same IID in +// two projects, or an issue and MR sharing a database id in different kind +// spaces, must not alias. +func TestDeriveFallback_IIDsAreNotIdentity(t *testing.T) { + a := Identity{Instance: "https://gitlab.com", Container: 101, Kind: KindWorkItem, Entity: 555} + b := Identity{Instance: "https://gitlab.com", Container: 102, Kind: KindWorkItem, Entity: 555} + fa, ok := DeriveFallback(a) + require.True(t, ok) + fb, ok := DeriveFallback(b) + require.True(t, ok) + assert.NotEqual(t, fa, fb, "the same IID in another project is a different entity") +} + +// TestDeriveFallback_ConcurrentFirstEvents is V01: concurrent first events +// converge on the same fallback. Run with -race. +func TestDeriveFallback_ConcurrentFirstEvents(t *testing.T) { + const goroutines = 64 + results := make([]Fallback, goroutines) + var wg sync.WaitGroup + for i := 0; i < goroutines; i++ { + wg.Add(1) + go func(slot int) { + defer wg.Done() + fb, ok := DeriveFallback(v01Identity()) + if !ok { + t.Error("concurrent derivation must resolve") + return + } + results[slot] = fb + }(i) + } + wg.Wait() + for i := 1; i < goroutines; i++ { + assert.Equal(t, results[0], results[i], "all first events must converge") + } + assert.True(t, results[0].TraceID.IsValid()) + assert.True(t, results[0].AnchorSpanID.IsValid()) +} + +// deriveChildEnv re-executes this test binary as a fresh process that +// derives the V01 fixture and prints the result, proving there is no shared +// in-memory state behind convergence. +const deriveChildEnv = "FULLSEND_TRACONTEXT_DERIVE_CHILD=1" + +// TestDeriveFallback_IdenticalAcrossProcesses is V01: two fresh processes +// derive identical nonzero fallbacks for the same immutable identity. +func TestDeriveFallback_IdenticalAcrossProcesses(t *testing.T) { + if os.Getenv("FULLSEND_TRACONTEXT_DERIVE_CHILD") == "1" { + fb, ok := DeriveFallback(v01Identity()) + if !ok { + fmt.Println("unresolved") + os.Exit(1) + } + // Print raw byte slices: the otel ID types implement Stringer, + // and %x on a Stringer would hex-encode the hex string. + fmt.Printf("%x %x\n", fb.TraceID[:], fb.AnchorSpanID[:]) + os.Exit(0) + } + + run := func() string { + cmd := exec.Command(os.Args[0], "-test.run", "^TestDeriveFallback_IdenticalAcrossProcesses$") + cmd.Env = append(os.Environ(), deriveChildEnv) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "child process: %s", out) + return strings.TrimSpace(string(out)) + } + first := run() + second := run() + + assert.NotEqual(t, "unresolved", first) + assert.Equal(t, first, second, "two fresh processes must derive identical fallbacks") + assert.Equal(t, "c9bdb0e38247ebbe2e0f1039250c32d4 892a346c55356aca", first) + + parts := strings.Fields(first) + require.Len(t, parts, 2, "child output: %q", first) + assert.Len(t, parts[0], 32, "TraceID must be 16 bytes hex") + assert.Len(t, parts[1], 16, "SpanID must be 8 bytes hex") + assert.NotEqual(t, strings.Repeat("00", 16), parts[0], "TraceID must be nonzero") + assert.NotEqual(t, strings.Repeat("00", 8), parts[1], "SpanID must be nonzero") +} + +// TestNormalizeInstance covers the D01 instance form: lowercase +// scheme://host, no path, query, fragment, or user info. +func TestNormalizeInstance(t *testing.T) { + cases := []struct { + name string + raw string + want string + }{ + {"github default", "https://github.com", "https://github.com"}, + {"gitlab default", "https://gitlab.com", "https://gitlab.com"}, + {"jira site", "https://acme.atlassian.net", "https://acme.atlassian.net"}, + {"GHES host", "https://ghe.example.com", "https://ghe.example.com"}, + {"uppercase host", "https://GitHub.com", "https://github.com"}, + {"uppercase scheme", "HTTPS://github.com", "https://github.com"}, + {"trailing slash", "https://github.com/", "https://github.com"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := NormalizeInstance(tc.raw) + require.NoError(t, err) + assert.Equal(t, tc.want, got) + }) + } +} + +func TestNormalizeInstance_Rejects(t *testing.T) { + for _, raw := range []string{ + "", + "://missing-scheme", + "https://github.com/owner/repo", + "https://user:passgithub.com", + "https://github.com?query=1", + "https://github.com#fragment", + "https://github.com?", + "https://github.com#", + "https://:443", + "ftp://github.com", + "https://" + strings.Repeat("a", 246), + "https://\xff.example", + } { + _, err := NormalizeInstance(raw) + assert.Error(t, err, "input %q must be rejected", raw) + } +} + +// These preimages and IDs were computed independently with Python struct +// (>H string lengths, >QBQ IDs/kind) and hashlib.sha256, not DeriveFallback. +func TestDeriveFallback_FixedVectors(t *testing.T) { + for _, tc := range []struct { + id Identity + preimage, traceID, anchor string + }{ + {v01Identity(), "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a2", "c9bdb0e38247ebbe2e0f1039250c32d4", "892a346c55356aca"}, + {Identity{Instance: "https://gitlab.com", Container: 101, Kind: KindChangeProposal, Entity: 555}, "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001268747470733a2f2f6769746c61622e636f6d000000000000006502000000000000022b", "407b66d9453075850f3ee7ef31d6ff1e", "a39491edef0440ae"}, + {Identity{Instance: "https://acme.atlassian.net", Container: 10000, Kind: KindWorkItem, Entity: 10100}, "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001a68747470733a2f2f61636d652e61746c61737369616e2e6e65740000000000002710010000000000002774", "535e9f2c6d8bd8a814edd68dceb60e9a", "7e00bd92068701ac"}, + } { + t.Run(tc.id.Instance, func(t *testing.T) { + digest := sha256.Sum256(mustHex(t, tc.preimage)) + assert.Equal(t, tc.traceID, fmt.Sprintf("%x", digest[:16])) + assert.Equal(t, tc.anchor, fmt.Sprintf("%x", digest[16:24])) + fb, ok := DeriveFallback(tc.id) + require.True(t, ok) + assert.Equal(t, tc.traceID, fb.TraceID.String()) + assert.Equal(t, tc.anchor, fb.AnchorSpanID.String()) + }) + } +} + +func TestFallback_SyntheticAnchorExportLifecycle(t *testing.T) { + seen := map[trace.SpanID]bool{} + for range 2 { + // Each provider models an independent launch with no retained state. + exporter := tracetest.NewInMemoryExporter() + provider := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exporter), sdktrace.WithSampler(sdktrace.AlwaysSample())) + t.Cleanup(func() { assert.NoError(t, provider.Shutdown(context.Background())) }) + fb, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + parent := trace.NewSpanContext(trace.SpanContextConfig{TraceID: fb.TraceID, SpanID: fb.AnchorSpanID}) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), parent) + tracer := provider.Tracer("tracecontext-test") + for range 2 { + _, span := tracer.Start(ctx, "operation") + span.End() + } + spans := exporter.GetSpans() + require.Len(t, spans, 2, "only operation spans are exported") + for _, span := range spans { + assert.Equal(t, "c9bdb0e38247ebbe2e0f1039250c32d4", span.SpanContext.TraceID().String()) + assert.Equal(t, "892a346c55356aca", span.Parent.SpanID().String()) + assert.Equal(t, span.SpanContext.TraceID(), span.Parent.TraceID()) + assert.NotEqual(t, fb.AnchorSpanID, span.SpanContext.SpanID(), "anchor is never exported") + assert.False(t, seen[span.SpanContext.SpanID()], "operations have distinct IDs across launches") + seen[span.SpanContext.SpanID()] = true + } + } +} + +// TestDeriveFallback_InstancesDifferByHost ensures normalization feeds +// derivation distinctly per host. +func TestDeriveFallback_InstancesDifferByHost(t *testing.T) { + a := v01Identity() + b := v01Identity() + b.Instance = "https://ghe.example.com" + fa, ok := DeriveFallback(a) + require.True(t, ok) + fb, ok := DeriveFallback(b) + require.True(t, ok) + assert.False(t, bytes.Equal(fa.TraceID[:], fb.TraceID[:])) +} From f500bab3e42f291db583abe349f7da6a8576f595 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:57:38 -0500 Subject: [PATCH 02/40] refactor(telemetry): add signed envelopes and trace admission Signed-off-by: Dharit Shah --- internal/telemetry/tracecontext/envelope.go | 525 +++++++++++++ .../telemetry/tracecontext/envelope_test.go | 715 ++++++++++++++++++ .../telemetry/tracecontext/identity_test.go | 8 - 3 files changed, 1240 insertions(+), 8 deletions(-) create mode 100644 internal/telemetry/tracecontext/envelope.go create mode 100644 internal/telemetry/tracecontext/envelope_test.go diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go new file mode 100644 index 0000000000..8b649a1108 --- /dev/null +++ b/internal/telemetry/tracecontext/envelope.go @@ -0,0 +1,525 @@ +package tracecontext + +import ( + "bytes" + "crypto/ed25519" + "crypto/sha256" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "strings" + + "go.opentelemetry.io/otel/trace" +) + +// Domain distinguishes the two v1 message domains. The domain byte is +// covered by the signature, so a pending marker cannot be replayed as a +// bound envelope. +type Domain byte + +const ( + // DomainBound is a signed envelope bound to a destination entity. + DomainBound Domain = 0x01 + // DomainPending is a signed creation-intent marker. It carries no + // entity ID and grants neither context, parent, nor source link. + DomainPending Domain = 0x02 +) + +// Valid reports whether d is a defined message domain. +func (d Domain) Valid() bool { + return d == DomainBound || d == DomainPending +} + +// ProvenanceKind selects the authenticated provenance section. +type ProvenanceKind byte + +const ( + // ProvenanceNone means the envelope carries no creation provenance. + ProvenanceNone ProvenanceKind = 0x00 + // ProvenanceSourceLink is an ordinary creation relationship: the + // source operation's span context, recorded as a link only. The + // destination keeps its own TraceID. + ProvenanceSourceLink ProvenanceKind = 0x01 + // ProvenanceScenario is behaviour-test scenario ownership: the entity + // inherits the scenario TraceID. + ProvenanceScenario ProvenanceKind = 0x02 +) + +// Valid reports whether k is a defined provenance kind. +func (k ProvenanceKind) Valid() bool { + return k == ProvenanceNone || k == ProvenanceSourceLink || k == ProvenanceScenario +} + +// Provenance carries the authenticated creation provenance of an envelope. +// Only the fields selected by Kind are meaningful. +type Provenance struct { + Kind ProvenanceKind + // SourceTraceID and SourceSpanID identify the creating operation for + // ProvenanceSourceLink. Valid when Kind == ProvenanceSourceLink. + SourceTraceID trace.TraceID + SourceSpanID trace.SpanID + // ScenarioTraceID and ScenarioInvocationID identify the scenario for + // ProvenanceScenario. Valid when Kind == ProvenanceScenario. + ScenarioTraceID trace.TraceID + ScenarioInvocationID [16]byte +} + +// Envelope is a decoded v1 envelope or pending marker. The wire layout, +// exact sizes, and strict limits are frozen in +// docs/reference/trace-context.md; Marshal is its only legal encoder. +type Envelope struct { + Domain Domain + KeyID [8]byte + Installation [16]byte + Instance string + Container int64 + Kind EntityKind + // Entity is the immutable destination database ID. It must be 0 in + // pending markers; the destination does not exist yet. + Entity int64 + TraceID trace.TraceID + ParentSpanID trace.SpanID + Provenance Provenance + Nonce [16]byte + Signature [64]byte +} + +// MaxEnvelopeLen is the maximum legal wire size in bytes: a bound envelope +// with scenario provenance and a 253-byte instance (439 bytes). Anything +// longer is definitionally invalid. +const MaxEnvelopeLen = 439 + +// MaxCarrierLen is the maximum legal base64 carrier length in characters: +// base64.StdEncoding of MaxEnvelopeLen bytes without line breaks. +const MaxCarrierLen = 588 + +// Wire constants of the frozen v1 format. +var magic = [4]byte{'F', 'S', 'T', 'C'} + +const versionV1 = 0x01 + +// Parse error sentinels; Admit maps them to reason codes. +var ( + errOversized = errors.New("tracecontext: envelope exceeds maximum length") + errUnknownVersion = errors.New("tracecontext: unknown envelope version") + errMalformed = errors.New("tracecontext: malformed envelope") +) + +// minEnvelopeLen is the structural lower bound: pending domain, no +// provenance, one instance byte. Canonical URL validation is stricter. +const minEnvelopeLen = 147 + +// KeyID returns the v1 key selector for a verification key: the first 8 +// bytes of SHA-256(public key). Envelopes carry only this selector; keys +// are resolved exclusively against trusted configuration. +func KeyID(pub ed25519.PublicKey) [8]byte { + sum := sha256.Sum256(pub) + var id [8]byte + copy(id[:], sum[:8]) + return id +} + +// validate enforces the structural field constraints shared by Sign and +// Parse. Provenance cross-field consistency is separate (checkConsistency) +// because it is an admission-layer rule, not wire validity. +func (e *Envelope) validate() error { + if !e.Domain.Valid() { + return fmt.Errorf("%w: domain %#02x", errMalformed, byte(e.Domain)) + } + if e.Installation == ([16]byte{}) { + return fmt.Errorf("%w: zero installation", errMalformed) + } + if !validInstance(e.Instance) { + return fmt.Errorf("%w: invalid instance", errMalformed) + } + if e.Container < 1 { + return fmt.Errorf("%w: container %d", errMalformed, e.Container) + } + if !e.Kind.Valid() { + return fmt.Errorf("%w: kind %#02x", errMalformed, byte(e.Kind)) + } + if e.Domain == DomainBound { + if e.Entity < 1 { + return fmt.Errorf("%w: entity %d", errMalformed, e.Entity) + } + } else if e.Entity != 0 { + return fmt.Errorf("%w: pending marker carries entity %d", errMalformed, e.Entity) + } + if !e.TraceID.IsValid() { + return fmt.Errorf("%w: zero trace id", errMalformed) + } + if !e.ParentSpanID.IsValid() { + return fmt.Errorf("%w: zero span id", errMalformed) + } + if !e.Provenance.Kind.Valid() { + return fmt.Errorf("%w: provenance kind %#02x", errMalformed, byte(e.Provenance.Kind)) + } + switch e.Provenance.Kind { + case ProvenanceSourceLink: + if !e.Provenance.SourceTraceID.IsValid() || !e.Provenance.SourceSpanID.IsValid() { + return fmt.Errorf("%w: invalid source link", errMalformed) + } + case ProvenanceScenario: + if !e.Provenance.ScenarioTraceID.IsValid() { + return fmt.Errorf("%w: zero scenario trace id", errMalformed) + } + if e.Provenance.ScenarioInvocationID == ([16]byte{}) { + return fmt.Errorf("%w: zero scenario invocation id", errMalformed) + } + } + if e.Nonce == ([16]byte{}) { + return fmt.Errorf("%w: zero nonce", errMalformed) + } + return nil +} + +// checkConsistency enforces the D02 provenance consistency rules: an +// ordinary source link keeps separate traces; scenario provenance inherits +// the scenario trace. +func (e *Envelope) checkConsistency() error { + switch e.Provenance.Kind { + case ProvenanceSourceLink: + if e.TraceID == e.Provenance.SourceTraceID { + return errors.New("tracecontext: source-link provenance must not merge the source and destination traces") + } + case ProvenanceScenario: + if e.TraceID != e.Provenance.ScenarioTraceID { + return errors.New("tracecontext: scenario provenance must inherit the scenario trace") + } + } + return nil +} + +// payload returns the signed prefix of the wire bytes: everything except +// the 64-byte signature. The magic, version, and domain bytes are included, +// so signatures are domain-separated and cannot be replayed across +// message domains. +func (e *Envelope) payload() []byte { + buf := make([]byte, 0, MaxEnvelopeLen) + buf = append(buf, magic[:]...) + buf = append(buf, versionV1, byte(e.Domain)) + buf = append(buf, e.KeyID[:]...) + buf = append(buf, e.Installation[:]...) + var l [2]byte + binary.BigEndian.PutUint16(l[:], uint16(len(e.Instance))) + buf = append(buf, l[:]...) + buf = append(buf, e.Instance...) + var i64 [8]byte + binary.BigEndian.PutUint64(i64[:], uint64(e.Container)) + buf = append(buf, i64[:]...) + buf = append(buf, byte(e.Kind)) + if e.Domain == DomainBound { + binary.BigEndian.PutUint64(i64[:], uint64(e.Entity)) + buf = append(buf, i64[:]...) + } + buf = append(buf, e.TraceID[:]...) + buf = append(buf, e.ParentSpanID[:]...) + buf = append(buf, byte(e.Provenance.Kind)) + switch e.Provenance.Kind { + case ProvenanceSourceLink: + buf = append(buf, e.Provenance.SourceTraceID[:]...) + buf = append(buf, e.Provenance.SourceSpanID[:]...) + case ProvenanceScenario: + buf = append(buf, e.Provenance.ScenarioTraceID[:]...) + buf = append(buf, e.Provenance.ScenarioInvocationID[:]...) + } + buf = append(buf, e.Nonce[:]...) + return buf +} + +// Sign validates the envelope, derives KeyID from the signing key, and +// signs the canonical bytes in place. Signing is a trusted host-side +// operation; keys never enter sandboxes or argv. +func (e *Envelope) Sign(key ed25519.PrivateKey) error { + if len(key) != ed25519.PrivateKeySize { + return errors.New("tracecontext: invalid signing key size") + } + if err := e.validate(); err != nil { + return err + } + if err := e.checkConsistency(); err != nil { + return err + } + pub, ok := key.Public().(ed25519.PublicKey) + if !ok { + return errors.New("tracecontext: signing key has no Ed25519 public half") + } + e.KeyID = KeyID(pub) + copy(e.Signature[:], ed25519.Sign(key, e.payload())) + return nil +} + +// Marshal returns the canonical wire bytes including the signature. Sign +// must have completed; marshalling an unsigned envelope yields bytes no +// verifier accepts. +func (e *Envelope) Marshal() []byte { + return append(e.payload(), e.Signature[:]...) +} + +// Parse strictly decodes and validates wire bytes. It accepts only the +// exact structural length for the parsed domain and provenance kind; +// duplicate and unknown fields are structurally impossible in the fixed +// layout. Provenance cross-field consistency is checked at admission, not +// here. +func Parse(b []byte) (*Envelope, error) { + if len(b) > MaxEnvelopeLen { + return nil, errOversized + } + if len(b) < minEnvelopeLen { + return nil, fmt.Errorf("%w: %d bytes", errMalformed, len(b)) + } + if !bytes.Equal(b[0:4], magic[:]) { + return nil, fmt.Errorf("%w: bad magic", errMalformed) + } + if b[4] != versionV1 { + return nil, fmt.Errorf("%w: %#02x", errUnknownVersion, b[4]) + } + domain := Domain(b[5]) + if !domain.Valid() { + return nil, fmt.Errorf("%w: domain %#02x", errMalformed, b[5]) + } + + off := 6 + grab := func(n int) ([]byte, error) { + if off+n > len(b) { + return nil, fmt.Errorf("%w: truncated at %d", errMalformed, off) + } + p := b[off : off+n] + off += n + return p, nil + } + + e := &Envelope{Domain: domain} + p, err := grab(8) + if err != nil { + return nil, err + } + copy(e.KeyID[:], p) + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Installation[:], p) + p, err = grab(2) + if err != nil { + return nil, err + } + instLen := int(binary.BigEndian.Uint16(p)) + if instLen < 1 || instLen > 253 { + return nil, fmt.Errorf("%w: instance length %d", errMalformed, instLen) + } + p, err = grab(instLen) + if err != nil { + return nil, err + } + e.Instance = string(p) + p, err = grab(8) + if err != nil { + return nil, err + } + e.Container = int64(binary.BigEndian.Uint64(p)) + p, err = grab(1) + if err != nil { + return nil, err + } + e.Kind = EntityKind(p[0]) + if domain == DomainBound { + p, err = grab(8) + if err != nil { + return nil, err + } + e.Entity = int64(binary.BigEndian.Uint64(p)) + } + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.TraceID[:], p) + p, err = grab(8) + if err != nil { + return nil, err + } + copy(e.ParentSpanID[:], p) + p, err = grab(1) + if err != nil { + return nil, err + } + e.Provenance.Kind = ProvenanceKind(p[0]) + switch e.Provenance.Kind { + case ProvenanceSourceLink: + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Provenance.SourceTraceID[:], p) + p, err = grab(8) + if err != nil { + return nil, err + } + copy(e.Provenance.SourceSpanID[:], p) + case ProvenanceScenario: + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Provenance.ScenarioTraceID[:], p) + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Provenance.ScenarioInvocationID[:], p) + case ProvenanceNone: + default: + return nil, fmt.Errorf("%w: provenance kind %#02x", errMalformed, p[0]) + } + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Nonce[:], p) + if off != len(b)-64 { + return nil, fmt.Errorf("%w: %d trailing bytes", errMalformed, len(b)-64-off) + } + copy(e.Signature[:], b[off:]) + + if err := e.validate(); err != nil { + return nil, err + } + return e, nil +} + +// DecodeCarrier strictly decodes a base64 carrier string to raw envelope +// bytes. It rejects line breaks, non-canonical encodings, and carriers +// longer than MaxCarrierLen. +func DecodeCarrier(s string) ([]byte, error) { + if strings.ContainsAny(s, "\r\n") { + return nil, errors.New("tracecontext: carrier contains line breaks") + } + if len(s) > MaxCarrierLen { + return nil, errors.New("tracecontext: carrier exceeds maximum length") + } + b, err := base64.StdEncoding.Strict().DecodeString(s) + if err != nil { + return nil, fmt.Errorf("tracecontext: decode carrier: %w", err) + } + return b, nil +} + +// Outcome is the admission outcome. It never encodes dispatch permission. +type Outcome int + +const ( + // OutcomeAdmitted means a verified bound envelope matched the + // expected binding; the admitted IDs are available. + OutcomeAdmitted Outcome = iota + // OutcomePending means a verified pending marker matched the expected + // scope. It grants neither context nor links; bounded rereads are + // caller policy. + OutcomePending + // OutcomeFallback means no carrier was admissible; the caller uses + // the deterministic entity-derived fallback. + OutcomeFallback +) + +// Reason codes for non-admitted outcomes. They are redacted diagnostics: +// no key material, no raw bytes. +const ( + ReasonAbsent = "absent" + ReasonMalformed = "malformed" + ReasonOversized = "oversized" + ReasonUnknownVersion = "unknown-version" + ReasonUnknownKey = "unknown-key" + ReasonBadSignature = "bad-signature" + ReasonBindingMismatch = "binding-mismatch" + ReasonConflictingCarrier = "conflicting-carrier" + ReasonProvenance = "provenance" + ReasonPending = "pending" +) + +// Result is the admission outcome. It carries admitted IDs and +// authenticated provenance only — never sampling flags, tracestate, +// baggage, or dispatch permission (FR-007, FR-008). +type Result struct { + Outcome Outcome + // Reason is a redacted reason code when the outcome is not admitted. + Reason string + // TraceID and ParentSpanID are the admitted context, valid when + // Outcome == OutcomeAdmitted. + TraceID trace.TraceID + ParentSpanID trace.SpanID + // Provenance is the authenticated provenance, valid when + // Outcome == OutcomeAdmitted. + Provenance Provenance +} + +func fallback(reason string) Result { + return Result{Outcome: OutcomeFallback, Reason: reason} +} + +func reasonForParse(err error) string { + switch { + case errors.Is(err, errOversized): + return ReasonOversized + case errors.Is(err, errUnknownVersion): + return ReasonUnknownVersion + default: + return ReasonMalformed + } +} + +// Admit parses, verifies, and binds candidate carrier wire bytes against +// the expected identity and the configured eligible verification keys +// (active plus retained). Identical duplicate candidates are acceptable; +// any differing candidates reject. Keys are resolved only from the +// supplied trusted set. Admission is independent of dispatch +// authorization: this function never returns permission. +func Admit(expected Identity, keys map[[8]byte]ed25519.PublicKey, candidates ...[]byte) Result { + if len(candidates) == 0 { + return fallback(ReasonAbsent) + } + parsed := make([]*Envelope, 0, len(candidates)) + for _, c := range candidates { + env, err := Parse(c) + if err != nil { + return fallback(reasonForParse(err)) + } + parsed = append(parsed, env) + } + for i := 1; i < len(parsed); i++ { + if !bytes.Equal(candidates[i], candidates[0]) { + return fallback(ReasonConflictingCarrier) + } + } + + env := parsed[0] + pub, ok := keys[env.KeyID] + if !ok || len(pub) != ed25519.PublicKeySize { + return fallback(ReasonUnknownKey) + } + payload := candidates[0][:len(candidates[0])-64] + if !ed25519.Verify(pub, payload, env.Signature[:]) { + return fallback(ReasonBadSignature) + } + if err := env.checkConsistency(); err != nil { + return fallback(ReasonProvenance) + } + if env.Installation != expected.Installation || + env.Instance != expected.Instance || + env.Container != expected.Container || + env.Kind != expected.Kind { + return fallback(ReasonBindingMismatch) + } + if env.Domain == DomainBound { + if env.Entity != expected.Entity { + return fallback(ReasonBindingMismatch) + } + return Result{ + Outcome: OutcomeAdmitted, + TraceID: env.TraceID, + ParentSpanID: env.ParentSpanID, + Provenance: env.Provenance, + } + } + return Result{Outcome: OutcomePending, Reason: ReasonPending} +} diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go new file mode 100644 index 0000000000..518a05f4af --- /dev/null +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -0,0 +1,715 @@ +package tracecontext + +import ( + "bytes" + "crypto/ed25519" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "reflect" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/trace" +) + +// The tests in this file are V02/V04 for AISDLC-576: exact signed-byte +// fixtures, tamper-every-field, cross-binding replay, strict parser limits, +// duplicate/oversized/zero-ID rejection, retained keys, and pending markers +// granting nothing. Golden hex constants pin the frozen v1 wire format for +// every later PR. + +// goldenKey is a deterministic Ed25519 key for reproducible fixtures. +func goldenKey() ed25519.PrivateKey { + seed := make([]byte, ed25519.SeedSize) + for i := range seed { + seed[i] = byte(i + 1) + } + return ed25519.NewKeyFromSeed(seed) +} + +func goldenKeys(t *testing.T) (ed25519.PrivateKey, map[[8]byte]ed25519.PublicKey) { + t.Helper() + key := goldenKey() + pub := key.Public().(ed25519.PublicKey) + return key, map[[8]byte]ed25519.PublicKey{KeyID(pub): pub} +} + +func hexTrace(s string) trace.TraceID { + tid, err := trace.TraceIDFromHex(s) + if err != nil { + panic(err) + } + return tid +} + +func hexSpan(s string) trace.SpanID { + sid, err := trace.SpanIDFromHex(s) + if err != nil { + panic(err) + } + return sid +} + +// goldenIdentity matches the identity bound into every golden envelope. +func goldenIdentity() Identity { + return Identity{ + Installation: [16]byte{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf}, + Instance: "https://github.com", + Container: 274390431, + Kind: KindWorkItem, + Entity: 2468913570, + } +} + +// goldenEnvelope builds the fixture envelope for a domain and provenance +// kind. Scenario envelopes keep TraceID == ScenarioTraceID per the +// provenance consistency rule. +func goldenEnvelope(domain Domain, prov ProvenanceKind) *Envelope { + id := goldenIdentity() + env := &Envelope{ + Domain: domain, + Installation: id.Installation, + Instance: id.Instance, + Container: id.Container, + Kind: id.Kind, + TraceID: hexTrace("4f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6d"), + ParentSpanID: hexSpan("a1b2c3d4e5f60718"), + Nonce: [16]byte{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}, + } + if domain == DomainBound { + env.Entity = id.Entity + } + switch prov { + case ProvenanceSourceLink: + env.Provenance = Provenance{ + Kind: ProvenanceSourceLink, + SourceTraceID: hexTrace("5c4b3a29180f6e5d4c3b2a1908f7e6d5"), + SourceSpanID: hexSpan("0f1e2d3c4b5a6978"), + } + case ProvenanceScenario: + env.Provenance = Provenance{ + Kind: ProvenanceScenario, + ScenarioTraceID: env.TraceID, // consistency: inherits scenario trace + ScenarioInvocationID: [16]byte{0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}, + } + } + return env +} + +// signedGolden returns precomputed signed bytes so parser/admission tests +// do not depend on Sign or Marshal succeeding during fixture setup. +func signedGolden(t *testing.T, domain Domain, prov ProvenanceKind) ([]byte, map[[8]byte]ed25519.PublicKey) { + t.Helper() + _, keys := goldenKeys(t) + vectors := map[Domain]map[ProvenanceKind]string{ + DomainBound: {ProvenanceNone: goldenBoundNoneHex, ProvenanceSourceLink: goldenBoundSourceLinkHex, ProvenanceScenario: goldenBoundScenarioHex}, + DomainPending: {ProvenanceNone: goldenPendingNoneHex, ProvenanceSourceLink: goldenPendingSourceLinkHex, ProvenanceScenario: goldenPendingScenarioHex}, + } + wire := vectors[domain][prov] + require.NotEmpty(t, wire) + return mustHex(t, wire), keys +} + +// specLayout mirrors the frozen v1 wire layout from +// docs/reference/trace-context.md so tests locate fields independently of +// the implementation, pinning the format from the spec side. +type specLayout struct { + instance, container, kind, entity int + trace, span, prov, provFields int + nonce, sig, total int +} + +func layout(domain Domain, prov ProvenanceKind, instanceLen int) specLayout { + var o specLayout + o.instance = 32 + o.container = o.instance + instanceLen + o.kind = o.container + 8 + o.entity = o.kind + 1 + if domain == DomainBound { + o.trace = o.entity + 8 + } else { + o.trace = o.entity // pending markers omit the entity bytes + } + o.span = o.trace + 16 + o.prov = o.span + 8 + o.provFields = o.prov + 1 + fields := 0 + switch prov { + case ProvenanceSourceLink: + fields = 24 + case ProvenanceScenario: + fields = 32 + } + o.nonce = o.provFields + fields + o.sig = o.nonce + 16 + o.total = o.sig + 64 + return o +} + +// resign re-signs mutated wire bytes so field-validity failures are not +// masked by signature failures: the parser must reject the field, not the +// signature. +func resign(t *testing.T, key ed25519.PrivateKey, raw []byte) []byte { + t.Helper() + require.Greater(t, len(raw), 64) + out := bytes.Clone(raw) + sig := ed25519.Sign(key, out[:len(out)-64]) + copy(out[len(out)-64:], sig) + return out +} + +func mustHex(t *testing.T, s string) []byte { + t.Helper() + b, err := hex.DecodeString(s) + require.NoError(t, err) + return b +} + +// Golden hex constants: frozen from the first green run; any later change +// to the wire format is a compatibility break. Independently reconstructed +// with Python struct + cryptography Ed25519 during corrective review; the +// pending provenance vectors were first generated by that independent code. +var ( + goldenBoundNoneHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f6071800101112131415161718191a1b1c1d1e1fe337c39001d56da6ba8862e01893f5d63d41fee3cab1d35f925aacd2e4a7165b30cf38403fcd2f809f50df67a62ebe705eb25a16e028df6345d8924b01bd2c0e" + goldenBoundSourceLinkHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718015c4b3a29180f6e5d4c3b2a1908f7e6d50f1e2d3c4b5a6978101112131415161718191a1b1c1d1e1f96451fbecf439bee72e636691b09f313df7b94bb017a63b7cdc0ea57775f3ca5a240c6f592f59bf33a25f463049e389345cf4d1354bd929198dc18803163a604" + goldenBoundScenarioHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718024f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6df0f1f2f3f4f5f6f7f8f9fafbfcfdfeff101112131415161718191a1b1c1d1e1fa59c45c20117895374e9ea5631083900ea081913ec21aa7d4604a23a75f2dd0f2ace2c01dda59c399f24bbdb409bc64081d898ba1ee73c292ca3d716e0860001" + goldenPendingNoneHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f6071800101112131415161718191a1b1c1d1e1f51fcd462f5bf6dd75e28f906fe0f4cf72d2c9fe9d3f66f95e1e650588442fdf2167890b17bc34775e27a74cc58ec22603df915fbe5396239d3f2b1ebf965c703" + goldenPendingSourceLinkHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718015c4b3a29180f6e5d4c3b2a1908f7e6d50f1e2d3c4b5a6978101112131415161718191a1b1c1d1e1fa35099c98587f7dc2ba94734f2afe542cd1581bcd0dc9320e436de8ca57c0a3dcd61bcdfad9a933e3baec5a324659286eb164aa745c3f62079ea466513aa6703" + goldenPendingScenarioHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718024f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6df0f1f2f3f4f5f6f7f8f9fafbfcfdfeff101112131415161718191a1b1c1d1e1f0bb31c983e5206e3592f6e437117cbdc06a6991213ee65c57ff3cff4cdd35a26f571fa350d2046117c695892521bf393df228718b96cb5fdbb65c244b3de820c" +) + +func TestGoldenVectors(t *testing.T) { + cases := []struct { + name string + dom Domain + prov ProvenanceKind + hex *string + }{ + {"bound none", DomainBound, ProvenanceNone, &goldenBoundNoneHex}, + {"bound source link", DomainBound, ProvenanceSourceLink, &goldenBoundSourceLinkHex}, + {"bound scenario", DomainBound, ProvenanceScenario, &goldenBoundScenarioHex}, + {"pending none", DomainPending, ProvenanceNone, &goldenPendingNoneHex}, + {"pending source link", DomainPending, ProvenanceSourceLink, &goldenPendingSourceLinkHex}, + {"pending scenario", DomainPending, ProvenanceScenario, &goldenPendingScenarioHex}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, keys := goldenKeys(t) + env := goldenEnvelope(tc.dom, tc.prov) + require.NoError(t, env.Sign(goldenKey())) + raw := env.Marshal() + want := mustHex(t, *tc.hex) + if !bytes.Equal(raw, want) { + t.Fatalf("golden wire bytes changed or not yet frozen:\n got %x\nwant %x", raw, want) + } + + // Layout is exactly the frozen spec's size. + assert.Equal(t, layout(tc.dom, tc.prov, len(goldenIdentity().Instance)).total, len(raw)) + + // Parse round-trips byte-for-byte. + parsed, err := Parse(want) + require.NoError(t, err) + assert.Equal(t, env, parsed) + + // Admission admits exactly the bound context. + res := Admit(goldenIdentity(), keys, want) + if tc.dom == DomainBound { + assert.Equal(t, OutcomeAdmitted, res.Outcome, "reason: %s", res.Reason) + assert.Equal(t, env.TraceID, res.TraceID) + assert.Equal(t, env.ParentSpanID, res.ParentSpanID) + assert.Equal(t, env.Provenance, res.Provenance) + } else { + assert.Equal(t, Result{Outcome: OutcomePending, Reason: ReasonPending}, res) + } + }) + } +} + +// TestTamperEverySignedByte flips each byte of a maximal envelope — header, +// binding, context, provenance, nonce, and signature — and requires +// rejection every time. +func TestTamperEverySignedByte(t *testing.T) { + raw, keys := signedGolden(t, DomainBound, ProvenanceScenario) + for i := 0; i < len(raw); i++ { + tampered := bytes.Clone(raw) + tampered[i] ^= 0x01 + res := Admit(goldenIdentity(), keys, tampered) + assert.NotEqual(t, OutcomeAdmitted, res.Outcome, "flipping byte %d must not admit", i) + } +} + +// TestCrossBindingReplay signs for one identity and admits against another: +// every binding component mismatch must reject a copied envelope. +func TestCrossBindingReplay(t *testing.T) { + raw, keys := signedGolden(t, DomainBound, ProvenanceNone) + + mutations := map[string]func(*Identity){ + "installation": func(i *Identity) { i.Installation = [16]byte{0xbb} }, + "instance": func(i *Identity) { i.Instance = "https://ghe.example.com" }, + "container": func(i *Identity) { i.Container++ }, + "kind": func(i *Identity) { i.Kind = KindChangeProposal }, + "entity": func(i *Identity) { i.Entity++ }, + } + for name, mutate := range mutations { + t.Run(name, func(t *testing.T) { + expected := goldenIdentity() + mutate(&expected) + res := Admit(expected, keys, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonBindingMismatch, res.Reason) + }) + } +} + +func TestAdmit_Absent(t *testing.T) { + _, keys := goldenKeys(t) + res := Admit(goldenIdentity(), keys) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonAbsent, res.Reason) +} + +func TestAdmit_UnknownKey(t *testing.T) { + raw, _ := signedGolden(t, DomainBound, ProvenanceNone) + + // A genuinely different key: goldenKey is deterministic, so derive + // from a distinct seed. + other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize)) + otherPub := other.Public().(ed25519.PublicKey) + res := Admit(goldenIdentity(), map[[8]byte]ed25519.PublicKey{KeyID(otherPub): otherPub}, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonUnknownKey, res.Reason) +} + +func TestAdmit_MalformedVerificationKeys(t *testing.T) { + raw := mustHex(t, goldenBoundSourceLinkHex) + selector := [8]byte{0x65, 0xb6, 0x06, 0x73, 0xd6, 0xed, 0x88, 0x4b} + for _, key := range []ed25519.PublicKey{nil, {}, make([]byte, 31), make([]byte, 33)} { + var result Result + assert.NotPanics(t, func() { + result = Admit(goldenIdentity(), map[[8]byte]ed25519.PublicKey{selector: key}, raw) + }, "key length %d", len(key)) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnknownKey}, result) + } +} + +func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { + for _, instance := range []string{ + "not-a-url", "https://GitHub.com", "HTTPS://github.com", "https://github.com/", + "https://github.com/api", "https://github.com?", "https://github.com#", + "https://user@github.com", "ftp://github.com", "https://:443", + "https://" + strings.Repeat("a", 246), "https://\xff.example", + } { + t.Run(instance, func(t *testing.T) { + id := goldenIdentity() + id.Instance = instance + assert.False(t, id.Resolved()) + fb, ok := DeriveFallback(id) + assert.False(t, ok) + assert.Equal(t, Fallback{}, fb) + + env := goldenEnvelope(DomainBound, ProvenanceNone) + env.Instance = instance + assert.Error(t, env.Sign(goldenKey())) + + // Replace only the instance in precomputed wire bytes, then sign + // directly so Sign validation cannot mask Parse/Admit failures. + raw := mustHex(t, goldenBoundNoneHex) + mutated := append(bytes.Clone(raw[:32]), []byte(instance)...) + mutated = append(mutated, raw[50:]...) + binary.BigEndian.PutUint16(mutated[30:32], uint16(len(instance))) + mutated = resign(t, goldenKey(), mutated) + _, err := Parse(mutated) + assert.Error(t, err) + _, keys := goldenKeys(t) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, Admit(id, keys, mutated)) + }) + } +} + +// TestAdmit_RetainedKey covers rotation: metadata signed by an older +// retained key stays verifiable while the active key signs new metadata. +func TestAdmit_RetainedKey(t *testing.T) { + oldKey, _ := goldenKeys(t) + env := goldenEnvelope(DomainBound, ProvenanceNone) + require.NoError(t, env.Sign(oldKey)) + raw := env.Marshal() + + // Rotation: generate the new active key, keep the old public key. + newSeed := make([]byte, ed25519.SeedSize) + for i := range newSeed { + newSeed[i] = byte(200 - i) + } + newKey := ed25519.NewKeyFromSeed(newSeed) + newPub := newKey.Public().(ed25519.PublicKey) + oldPub := oldKey.Public().(ed25519.PublicKey) + keys := map[[8]byte]ed25519.PublicKey{KeyID(newPub): newPub, KeyID(oldPub): oldPub} + + res := Admit(goldenIdentity(), keys, raw) + assert.Equal(t, OutcomeAdmitted, res.Outcome, "old metadata must verify with a retained key") +} + +// TestAdmit_KeyIDDerivedFromPublicKey pins the selector rule: the key ID is +// the first 8 bytes of SHA-256(public key). +func TestAdmit_KeyIDDerivedFromPublicKey(t *testing.T) { + key, _ := goldenKeys(t) + pub := key.Public().(ed25519.PublicKey) + + env := goldenEnvelope(DomainBound, ProvenanceNone) + require.NoError(t, env.Sign(key)) + raw := env.Marshal() + + // Same public key registered under a wrong key ID: the envelope's + // selector must not resolve, proving lookup uses the derived ID. + wrong := map[[8]byte]ed25519.PublicKey{[8]byte{0x99}: pub} + res := Admit(goldenIdentity(), wrong, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonUnknownKey, res.Reason) +} + +func TestAdmit_DuplicateCarriers(t *testing.T) { + raw, keys := signedGolden(t, DomainBound, ProvenanceNone) + + res := Admit(goldenIdentity(), keys, raw, bytes.Clone(raw)) + assert.Equal(t, OutcomeAdmitted, res.Outcome, "identical duplicates are idempotent publication") + + // A differing carrier (different nonce) must conflict, never + // first-match. + key, _ := goldenKeys(t) + otherEnv := goldenEnvelope(DomainBound, ProvenanceNone) + otherEnv.Nonce[0] ^= 0xff + require.NoError(t, otherEnv.Sign(key)) + res = Admit(goldenIdentity(), keys, raw, otherEnv.Marshal()) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonConflictingCarrier, res.Reason, "conflicting carriers must reject, never first-match") +} + +func TestAdmit_Oversized(t *testing.T) { + _, keys := goldenKeys(t) + + // Pad a valid envelope beyond the maximum legal size. + padded := make([]byte, MaxEnvelopeLen+1) + res := Admit(goldenIdentity(), keys, padded) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonOversized, res.Reason) + + big := make([]byte, 10*1024) + res = Admit(goldenIdentity(), keys, big) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonOversized, res.Reason) +} + +// TestParse_ZeroAndInvalidFields mutates individual fields in otherwise +// valid, correctly signed envelopes: the parser must reject the field +// itself, not merely the signature. +func TestParse_ZeroAndInvalidFields(t *testing.T) { + key, keys := goldenKeys(t) + inst := len(goldenIdentity().Instance) + + cases := []struct { + name string + domain Domain + prov ProvenanceKind + mutate func(raw []byte) []byte + }{ + {"zero installation", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, 14, 16); return r }}, + {"zero container", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).container, 8); return r }}, + {"zero entity", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).entity, 8); return r }}, + {"zero trace", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).trace, 16); return r }}, + {"zero span", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).span, 8); return r }}, + {"zero nonce", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).nonce, 16); return r }}, + {"invalid kind", DomainBound, ProvenanceNone, func(r []byte) []byte { r[layout(DomainBound, ProvenanceNone, inst).kind] = 0x7f; return r }}, + {"invalid provenance kind", DomainBound, ProvenanceNone, func(r []byte) []byte { r[layout(DomainBound, ProvenanceNone, inst).prov] = 0x03; return r }}, + {"zero scenario trace", DomainBound, ProvenanceScenario, func(r []byte) []byte { + zeroAt(r, layout(DomainBound, ProvenanceScenario, inst).provFields, 16) + return r + }}, + {"zero invocation id", DomainBound, ProvenanceScenario, func(r []byte) []byte { + zeroAt(r, layout(DomainBound, ProvenanceScenario, inst).provFields+16, 16) + return r + }}, + {"zero source trace", DomainBound, ProvenanceSourceLink, func(r []byte) []byte { + zeroAt(r, layout(DomainBound, ProvenanceSourceLink, inst).provFields, 16) + return r + }}, + {"unknown version", DomainBound, ProvenanceNone, func(r []byte) []byte { r[4] = 0x02; return r }}, + {"unknown domain", DomainBound, ProvenanceNone, func(r []byte) []byte { r[5] = 0x03; return r }}, + {"bad magic", DomainBound, ProvenanceNone, func(r []byte) []byte { r[0] = 'X'; return r }}, + {"trailing byte", DomainBound, ProvenanceNone, func(r []byte) []byte { return append(r[:len(r):len(r)], 0) }}, + {"truncated", DomainBound, ProvenanceNone, func(r []byte) []byte { return r[:len(r)-1] }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + raw, _ := signedGolden(t, tc.domain, tc.prov) + raw = tc.mutate(raw) + raw = resign(t, key, raw) + + _, err := Parse(raw) + require.Error(t, err, "parser must reject invalid field values") + + res := Admit(goldenIdentity(), keys, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + if tc.name == "unknown version" { + assert.Equal(t, ReasonUnknownVersion, res.Reason) + } + }) + } +} + +func zeroAt(b []byte, off, n int) { + for i := off; i < off+n; i++ { + b[i] = 0 + } +} + +// TestAdmit_PlainTraceparentIsNotAnEnvelope is V04: a plain W3C +// traceparent never substitutes for a signed envelope. +func TestAdmit_PlainTraceparentIsNotAnEnvelope(t *testing.T) { + _, keys := goldenKeys(t) + res := Admit(goldenIdentity(), keys, []byte("00-4f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6d-a1b2c3d4e5f60718-01")) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonMalformed, res.Reason) + assert.Equal(t, trace.TraceID{}, res.TraceID, "no unverified trace may be adopted") + assert.Equal(t, Provenance{}, res.Provenance, "no unverified link may be adopted") +} + +// TestAdmit_PendingGrantsNothing is V04: a verified pending marker matching +// the expected scope yields the pending outcome with no context and no +// links; a scope mismatch is a binding mismatch. +func TestAdmit_PendingGrantsNothing(t *testing.T) { + raw, keys := signedGolden(t, DomainPending, ProvenanceScenario) + + res := Admit(goldenIdentity(), keys, raw) + assert.Equal(t, OutcomePending, res.Outcome) + assert.Equal(t, ReasonPending, res.Reason) + assert.Equal(t, trace.TraceID{}, res.TraceID, "pending must not grant context") + assert.Equal(t, trace.SpanID{}, res.ParentSpanID, "pending must not grant a parent") + assert.Equal(t, Provenance{}, res.Provenance, "pending must not grant links or scenario membership") + + expected := goldenIdentity() + expected.Container++ + res = Admit(expected, keys, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonBindingMismatch, res.Reason) +} + +// TestAdmit_ProvenanceConsistency enforces the D02 rules: an ordinary +// source link keeps the destination's own trace; scenario provenance +// inherits the scenario trace. +func TestAdmit_ProvenanceConsistency(t *testing.T) { + key, keys := goldenKeys(t) + + // Source link whose destination trace equals the source trace: the + // traces would merge, which ordinary provenance forbids. + raw := mustHex(t, goldenBoundSourceLinkHex) + lay := layout(DomainBound, ProvenanceSourceLink, len(goldenIdentity().Instance)) + copy(raw[lay.trace:lay.trace+16], raw[lay.provFields:lay.provFields+16]) + res := Admit(goldenIdentity(), keys, resign(t, key, raw)) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonProvenance, res.Reason) + + // Scenario provenance whose trace differs from the scenario trace. + raw = mustHex(t, goldenBoundScenarioHex) + lay = layout(DomainBound, ProvenanceScenario, len(goldenIdentity().Instance)) + raw[lay.trace] ^= 0x01 + res = Admit(goldenIdentity(), keys, resign(t, key, raw)) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonProvenance, res.Reason) +} + +// TestAdmit_FallbackAdoptsNothing asserts every non-admitted result keeps +// zero context and provenance (FR-005). +func TestAdmit_FallbackAdoptsNothing(t *testing.T) { + raw, keys := signedGolden(t, DomainBound, ProvenanceSourceLink) + + tampered := bytes.Clone(raw) + tampered[len(tampered)-1] ^= 0x01 // break the signature only + res := Admit(goldenIdentity(), keys, tampered) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonBadSignature, res.Reason) + assert.Equal(t, trace.TraceID{}, res.TraceID) + assert.Equal(t, trace.SpanID{}, res.ParentSpanID) + assert.Equal(t, Provenance{}, res.Provenance) +} + +// TestResultCarriesNoSamplingStateOrBaggage is FR-007/V02: the admission +// result structurally cannot carry sampling flags, tracestate, or baggage. +func TestResultCarriesNoSamplingStateOrBaggage(t *testing.T) { + rt := reflect.TypeOf(Result{}) + var fields []string + for i := 0; i < rt.NumField(); i++ { + fields = append(fields, rt.Field(i).Name) + } + assert.ElementsMatch(t, + []string{"Outcome", "Reason", "TraceID", "ParentSpanID", "Provenance"}, + fields) +} + +// TestSign_RejectsInvalidEnvelopes keeps malformed envelopes from ever +// being signed: signing validates exactly what the parser validates. +func TestSign_RejectsInvalidEnvelopes(t *testing.T) { + key, _ := goldenKeys(t) + inst := goldenIdentity().Instance + + cases := map[string]func(*Envelope){"zero installation": func(e *Envelope) { e.Installation = [16]byte{} }, + "empty instance": func(e *Envelope) { e.Instance = "" }, + "nul in instance": func(e *Envelope) { e.Instance = "https://git\x00hub.com" }, + "instance too long": func(e *Envelope) { e.Instance = "https://" + strings.Repeat("a", 300) + ".com" }, + "zero container": func(e *Envelope) { e.Container = 0 }, + "zero entity": func(e *Envelope) { e.Entity = 0 }, + "zero trace": func(e *Envelope) { e.TraceID = trace.TraceID{} }, + "zero span": func(e *Envelope) { e.ParentSpanID = trace.SpanID{} }, + "zero nonce": func(e *Envelope) { e.Nonce = [16]byte{} }, + "invalid kind": func(e *Envelope) { e.Kind = EntityKind(0x7f) }, + "invalid domain": func(e *Envelope) { e.Domain = Domain(0x03) }, + "invalid provenance": func(e *Envelope) { e.Provenance = Provenance{Kind: ProvenanceKind(0x03)} }, + "zero source span": func(e *Envelope) { + e.Provenance = Provenance{Kind: ProvenanceSourceLink, SourceTraceID: hexTrace("4f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6d")} + }, + "zero invocation id": func(e *Envelope) { + e.Provenance = Provenance{Kind: ProvenanceScenario, ScenarioTraceID: hexTrace("4f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6d")} + }, + "pending with entity": func(e *Envelope) { + e.Domain = DomainPending + e.Entity = 1 + }, + "bound scenario trace mismatch": func(e *Envelope) { + e.Provenance = Provenance{ + Kind: ProvenanceScenario, + ScenarioTraceID: hexTrace("11111111111111111111111111111111"), + ScenarioInvocationID: [16]byte{1}, + } + }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + env := goldenEnvelope(DomainBound, ProvenanceNone) + env.Instance = inst + mutate(env) + err := env.Sign(key) + assert.Error(t, err, "Sign must refuse to sign an invalid envelope") + }) + } +} + +func TestDecodeCarrier(t *testing.T) { + raw, _ := signedGolden(t, DomainBound, ProvenanceNone) + carrier := base64.StdEncoding.EncodeToString(raw) + + got, err := DecodeCarrier(carrier) + require.NoError(t, err) + assert.Equal(t, raw, got) + + _, err = DecodeCarrier("ab\r\ncd") // line break inside + assert.Error(t, err, "line breaks must be rejected") + + _, err = DecodeCarrier(carrier[:len(carrier)-2]) // broken padding + assert.Error(t, err) + + _, err = DecodeCarrier(carrier + "!!!") + assert.Error(t, err, "invalid alphabet must be rejected") + + _, err = DecodeCarrier(strings.Repeat("A", MaxCarrierLen+1)) + assert.Error(t, err, "carriers longer than the maximum must be rejected") +} + +func TestKeyID_Derivation(t *testing.T) { + key := goldenKey() + pub := key.Public().(ed25519.PublicKey) + id := KeyID(pub) + assert.NotEqual(t, [8]byte{}, id, "key ID must be derived, not zero") + + other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, 32)) + otherPub := other.Public().(ed25519.PublicKey) + assert.NotEqual(t, id, KeyID(otherPub), "distinct keys must have distinct IDs") +} + +// TestSign_RejectsWrongKeySize guards the trust boundary between caller +// and host-side signing: only a well-formed Ed25519 private key may sign. +func TestSign_RejectsWrongKeySize(t *testing.T) { + env := goldenEnvelope(DomainBound, ProvenanceNone) + err := env.Sign(ed25519.PrivateKey(bytes.Repeat([]byte{1}, 10))) + assert.Error(t, err, "Sign must reject a mis-sized private key") +} + +// TestParse_Truncations walks every truncation of a maximal envelope: no +// prefix may parse, and none may panic. +func TestParse_Truncations(t *testing.T) { + raw, _ := signedGolden(t, DomainBound, ProvenanceScenario) + for n := 0; n < len(raw); n++ { + _, err := Parse(raw[:n]) + require.Error(t, err, "truncation to %d bytes must not parse", n) + } +} + +// TestParse_ShortTails exercises mid-structure bounds failures: buffers +// that pass the minimum-length and header checks but end inside a later +// fixed-size field. The instance length is chosen per buffer so each +// truncation point lands in a different grab. +func TestParse_ShortTails(t *testing.T) { + build := func(instLen, total int) []byte { + b := make([]byte, total) + copy(b, magic[:]) + b[4] = versionV1 + b[5] = byte(DomainBound) + binary.BigEndian.PutUint16(b[30:32], uint16(instLen)) + for i := 32; i < 32+instLen && i < total; i++ { + b[i] = 'x' + } + return b + } + // Instance field overruns the buffer. + _, err := Parse(build(253, 150)) + assert.Error(t, err) + // Container field overruns. + _, err = Parse(build(100, 135)) + assert.Error(t, err) + // Entity field overruns. + _, err = Parse(build(100, 143)) + assert.Error(t, err) + // Trace field overruns. + _, err = Parse(build(100, 151)) + assert.Error(t, err) + // Span field overruns. + _, err = Parse(build(100, 159)) + assert.Error(t, err) + // Provenance kind byte overruns. + _, err = Parse(build(100, 167)) + assert.Error(t, err) + // Signature region overruns (nonce fits, 64-byte signature does not). + _, err = Parse(build(100, 183)) + assert.Error(t, err) +} + +func FuzzParse(f *testing.F) { + // The frozen golden vectors, their truncations, and oversized inputs + // seed the corpus; CI fuzzing grows it from there. + for _, h := range []string{goldenBoundNoneHex, goldenBoundSourceLinkHex, goldenBoundScenarioHex, goldenPendingNoneHex, goldenPendingSourceLinkHex, goldenPendingScenarioHex} { + b, err := hex.DecodeString(h) + if err != nil { + f.Fatal(err) + } + f.Add(b) + f.Add(b[:len(b)-1]) + f.Add(b[:len(b)/2]) + } + f.Add([]byte{}) + f.Add(bytes.Repeat([]byte{0x41}, MaxEnvelopeLen)) + f.Add(bytes.Repeat([]byte{0x00}, MaxEnvelopeLen+1)) + f.Fuzz(func(t *testing.T, data []byte) { + env, err := Parse(data) + if err != nil { + return + } + // Any parsed envelope must round-trip byte-for-byte: the wire + // format has exactly one encoding. + if got := env.Marshal(); !bytes.Equal(got, data) { + t.Fatalf("round-trip mismatch:\n got %x\nwant %x", got, data) + } + }) +} diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index efeaacb11a..421e9a3479 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "crypto/sha256" - "encoding/hex" "fmt" "os" "os/exec" @@ -33,13 +32,6 @@ func v01Identity() Identity { } } -func mustHex(t *testing.T, s string) []byte { - t.Helper() - b, err := hex.DecodeString(s) - require.NoError(t, err) - return b -} - // TestDeriveFallback_ResolvedAndNonzero is V01: the same resolved immutable // identity derives a nonzero fallback, and repeated derivation in one // process is deterministic. From 5e12e97e81763a377132d1c0f92fa70b064cfaa3 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:57:51 -0500 Subject: [PATCH 03/40] refactor(forge): carry immutable IDs in models and fakes Signed-off-by: Dharit Shah --- internal/forge/fake.go | 8 ++++++++ internal/forge/fake_test.go | 4 ++++ internal/forge/forge.go | 19 ++++++++++++++++--- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/internal/forge/fake.go b/internal/forge/fake.go index 014a89e450..36ecabf0a0 100644 --- a/internal/forge/fake.go +++ b/internal/forge/fake.go @@ -1219,6 +1219,9 @@ func (f *FakeClient) CreateChangeProposal(_ context.Context, owner, repo, title, f.proposalCounter++ cp := ChangeProposal{ + // Synthetic immutable database ID in a distinct space from the + // display number, mirroring the real forges. + ID: int64(9100000000 + f.proposalCounter), URL: fmt.Sprintf("https://forge.example.com/%s/%s/pull/%d", owner, repo, f.proposalCounter), Title: title, Number: f.proposalCounter, @@ -1240,6 +1243,7 @@ func (f *FakeClient) CreateCrossRepoChangeProposal(_ context.Context, baseOwner, f.proposalCounter++ cp := ChangeProposal{ URL: fmt.Sprintf("https://forge.example.com/%s/%s/pull/%d", baseOwner, baseRepo, f.proposalCounter), + ID: int64(9100000000 + f.proposalCounter), Title: title, Number: f.proposalCounter, Head: headOwner + ":" + headBranch, @@ -1602,7 +1606,11 @@ func (f *FakeClient) CreateIssue(_ context.Context, owner, repo, title, body str return nil, e } f.issueCounter++ + // The synthetic immutable database ID lives in a distinct space from + // the display number, mirroring the real forges, so identity tests + // can detect conflation. Deterministic: 9000000000 + counter. issue := Issue{ + ID: int64(9000000000 + f.issueCounter), Number: f.issueCounter, Title: title, Body: body, diff --git a/internal/forge/fake_test.go b/internal/forge/fake_test.go index e254b3de51..24d175e948 100644 --- a/internal/forge/fake_test.go +++ b/internal/forge/fake_test.go @@ -338,6 +338,8 @@ func TestFakeClient_CreateCrossRepoChangeProposal(t *testing.T) { assert.Equal(t, "head-owner/head-repo", cp.HeadRepo) assert.Equal(t, "main", cp.Base) assert.Contains(t, cp.URL, "base-owner/base-repo/pull/1") + assert.Positive(t, cp.ID) + assert.NotEqual(t, int64(cp.Number), cp.ID) // Second proposal gets incremented number. cp2, err := fc.CreateCrossRepoChangeProposal(ctx, @@ -347,6 +349,8 @@ func TestFakeClient_CreateCrossRepoChangeProposal(t *testing.T) { require.NoError(t, err) assert.Equal(t, 2, cp2.Number) assert.Len(t, fc.CreatedProposals, 2) + assert.NotEqual(t, cp.ID, cp2.ID) + assert.Equal(t, []ChangeProposal{*cp, *cp2}, fc.CreatedProposals) } func TestFakeClient_CreateChangeProposal(t *testing.T) { diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 46568f54e1..bd6d40370e 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -495,10 +495,16 @@ type Repository struct { // ChangeProposal represents a pull request or merge request. type ChangeProposal struct { - URL string - Title string + URL string + Title string + // Number is the display number: GitHub's per-repo PR number or + // GitLab's per-project MR IID. It is not a stable identity. Number int - Head string + // ID is the immutable forge database ID of the change proposal: + // GitHub's REST pull-request id or GitLab's database merge-request + // id (not the IID). It is 0 when the adapter did not capture one. + ID int64 + Head string // HeadRepo identifies the repository the head branch lives in, as // "owner/repo" on both GitHub and GitLab (GitLab resolves a fork's // numeric source project ID to its path_with_namespace). Empty when @@ -573,7 +579,14 @@ type Annotation struct { // Issue represents a forge issue. type Issue struct { + // Number is the display number: GitHub's per-repo issue number or + // GitLab's per-project IID. It is not a stable identity. Number int + // ID is the immutable forge database ID of the issue: GitHub's REST + // id or GitLab's database id (not the IID). It is 0 when the adapter + // did not capture one; trace admission treats that as unresolved + // identity rather than guessing. + ID int64 Title string Body string URL string From 8c71bbf42d2eda5388dfc75ce4fd23aa73f1d710 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:58:12 -0500 Subject: [PATCH 04/40] refactor(github): preserve full-width immutable entity IDs Signed-off-by: Dharit Shah --- internal/forge/github/github.go | 27 +++++- internal/forge/github/github_test.go | 57 +++++++++++- internal/forge/github/trace_identity_test.go | 97 ++++++++++++++++++++ 3 files changed, 175 insertions(+), 6 deletions(-) create mode 100644 internal/forge/github/trace_identity_test.go diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index ee614fcec2..d88972e7f0 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -2483,6 +2483,7 @@ func (c *LiveClient) CreateChangeProposal(ctx context.Context, owner, repo, titl } var pr struct { + ID int64 `json:"id"` HTMLURL string `json:"html_url"` Title string `json:"title"` Number int `json:"number"` @@ -2492,6 +2493,7 @@ func (c *LiveClient) CreateChangeProposal(ctx context.Context, owner, repo, titl } return &forge.ChangeProposal{ + ID: pr.ID, URL: pr.HTMLURL, Title: pr.Title, Number: pr.Number, @@ -2535,6 +2537,7 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne query := `mutation($input: CreatePullRequestInput!) { createPullRequest(input: $input) { pullRequest { + fullDatabaseId number title url @@ -2565,9 +2568,10 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne Data struct { CreatePullRequest struct { PullRequest struct { - Number int `json:"number"` - Title string `json:"title"` - URL string `json:"url"` + FullDatabaseID json.Number `json:"fullDatabaseId"` + Number int `json:"number"` + Title string `json:"title"` + URL string `json:"url"` } `json:"pullRequest"` } `json:"createPullRequest"` } `json:"data"` @@ -2594,7 +2598,16 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne } pr := gqlResult.Data.CreatePullRequest.PullRequest + var id int64 + if pr.FullDatabaseID != "" { + id, err = pr.FullDatabaseID.Int64() + if err != nil || id < 1 { + return nil, fmt.Errorf("decode cross-repo pull request response: invalid fullDatabaseId %q", pr.FullDatabaseID) + } + } return &forge.ChangeProposal{ + // BigInt may be a JSON number or string; never round through float64. + ID: id, URL: pr.URL, Title: pr.Title, Number: pr.Number, @@ -2612,6 +2625,7 @@ func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo strin } var prs []struct { + ID int64 `json:"id"` HTMLURL string `json:"html_url"` Title string `json:"title"` Number int `json:"number"` @@ -2634,6 +2648,7 @@ func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo strin for _, pr := range prs { result = append(result, forge.ChangeProposal{ + ID: pr.ID, URL: pr.HTMLURL, Title: pr.Title, Number: pr.Number, @@ -3299,6 +3314,7 @@ func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body s } } var result struct { + ID int64 `json:"id"` Number int `json:"number"` Title string `json:"title"` Body string `json:"body"` @@ -3311,6 +3327,7 @@ func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body s return nil, fmt.Errorf("decode issue: %w", err) } return &forge.Issue{ + ID: result.ID, Number: result.Number, Title: result.Title, Body: result.Body, @@ -3353,6 +3370,7 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in return nil, fmt.Errorf("get issue #%d: %w", number, err) } var result struct { + ID int64 `json:"id"` Number int `json:"number"` Title string `json:"title"` Body string `json:"body"` @@ -3367,6 +3385,7 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in return nil, fmt.Errorf("decode issue #%d: %w", number, err) } return &forge.Issue{ + ID: result.ID, Number: result.Number, Title: result.Title, Body: result.Body, @@ -3417,6 +3436,7 @@ func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, lab return nil, fmt.Errorf("list open issues page %d: %w", page, err) } var raw []struct { + ID int64 `json:"id"` Number int `json:"number"` Title string `json:"title"` Body string `json:"body"` @@ -3436,6 +3456,7 @@ func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, lab continue } result = append(result, forge.Issue{ + ID: item.ID, Number: item.Number, Title: item.Title, Body: item.Body, diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 649cb7a329..724146927d 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -1056,6 +1056,53 @@ func TestCreateChangeProposal_Forbidden(t *testing.T) { assert.True(t, forge.IsForbidden(err), "CreateChangeProposal 403 should wrap ErrForbidden") } +func TestCreateCrossRepoChangeProposal_FullWidthID(t *testing.T) { + for _, tc := range []struct { + name, jsonID string + want int64 + wantErr bool + }{ + {"number", "9007199254740993", 9007199254740993, false}, + {"string", `"9007199254740993"`, 9007199254740993, false}, + {"max int64", `"9223372036854775807"`, 9223372036854775807, false}, + {"null unresolved", "null", 0, false}, + {"missing unresolved", "", 0, false}, + {"overflow", `"9223372036854775808"`, 0, true}, + {"negative", "-1", 0, true}, + {"zero", "0", 0, true}, + {"fractional", "1.5", 0, true}, + {"nonnumeric", `"bad"`, 0, true}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/"): + json.NewEncoder(w).Encode(map[string]string{"node_id": "NODE_repo"}) + case r.Method == http.MethodPost && r.URL.Path == "/graphql": + calls++ + id := "" + if tc.jsonID != "" { + id = `"fullDatabaseId":` + tc.jsonID + "," + } + fmt.Fprintf(w, `{"data":{"createPullRequest":{"pullRequest":{%s"number":99}}}}`, id) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + cp, err := newTestClient(t, srv).CreateCrossRepoChangeProposal(context.Background(), "org", "repo", "org", "fork", "title", "body", "feature", "main") + assert.Equal(t, 1, calls) + if tc.wantErr { + assert.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tc.want, cp.ID) + }) + } +} + func TestCreateCrossRepoChangeProposal(t *testing.T) { t.Run("same-org fork uses GraphQL", func(t *testing.T) { var getRepoCalls []string @@ -1075,6 +1122,8 @@ func TestCreateCrossRepoChangeProposal(t *testing.T) { var body map[string]any json.NewDecoder(r.Body).Decode(&body) + assert.Contains(t, body["query"], "fullDatabaseId") + assert.NotContains(t, body["query"], "\n\t\t\t\tdatabaseId") vars, _ := body["variables"].(map[string]any) input, _ := vars["input"].(map[string]any) assert.Equal(t, "NODE_org_repo", input["repositoryId"]) @@ -1088,9 +1137,10 @@ func TestCreateCrossRepoChangeProposal(t *testing.T) { "data": map[string]any{ "createPullRequest": map[string]any{ "pullRequest": map[string]any{ - "number": 99, - "title": "PR title", - "url": "https://github.com/org/repo/pull/99", + "fullDatabaseId": "9007199254740993", + "number": 99, + "title": "PR title", + "url": "https://github.com/org/repo/pull/99", }, }, }, @@ -1111,6 +1161,7 @@ func TestCreateCrossRepoChangeProposal(t *testing.T) { assert.True(t, graphqlCalled, "should use GraphQL createPullRequest") require.Len(t, getRepoCalls, 2, "should fetch node IDs for both repos") assert.Equal(t, 99, cp.Number) + assert.Equal(t, int64(9007199254740993), cp.ID, "BigInt must survive without float64 rounding") assert.Equal(t, "PR title", cp.Title) assert.Equal(t, "https://github.com/org/repo/pull/99", cp.URL) }) diff --git a/internal/forge/github/trace_identity_test.go b/internal/forge/github/trace_identity_test.go new file mode 100644 index 0000000000..4ff9b3cc4b --- /dev/null +++ b/internal/forge/github/trace_identity_test.go @@ -0,0 +1,97 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The tests in this file are V03 for AISDLC-576: the immutable database IDs +// required by the D01 identity tuple must survive adapter mapping. GitHub's +// per-repo numbers are display values; the REST `id` is the identity. + +func TestGetIssue_CapturesImmutableID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/repos/org/repo/issues/7", r.URL.Path) + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 2468913570, + "number": 7, + "title": "Widget is broken", + "body": "details", + "html_url": "https://github.com/org/repo/issues/7", + "state": "open", + "labels": []any{}, + }) + })) + defer srv.Close() + + client := newTestClient(t, srv) + issue, err := client.GetIssue(context.Background(), "org", "repo", 7) + require.NoError(t, err) + assert.Equal(t, int64(2468913570), issue.ID, "GetIssue must capture the immutable REST issue id") + assert.Equal(t, 7, issue.Number, "the display number is still addressed by (owner, repo, number)") +} + +func TestCreateIssue_CapturesImmutableID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 2468913571, + "number": 8, + "title": "New work", + "body": "body", + "html_url": "https://github.com/org/repo/issues/8", + }) + })) + defer srv.Close() + + client := newTestClient(t, srv) + issue, err := client.CreateIssue(context.Background(), "org", "repo", "New work", "body") + require.NoError(t, err) + assert.Equal(t, int64(2468913571), issue.ID, "CreateIssue must capture the immutable REST issue id") + assert.Equal(t, 8, issue.Number) +} + +func TestCreateChangeProposal_CapturesImmutableID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 1357924680, + "number": 12, + "title": "Add widget", + "html_url": "https://github.com/org/repo/pull/12", + }) + })) + defer srv.Close() + + client := newTestClient(t, srv) + cp, err := client.CreateChangeProposal(context.Background(), "org", "repo", "Add widget", "body", "head", "main") + require.NoError(t, err) + assert.Equal(t, int64(1357924680), cp.ID, "CreateChangeProposal must capture the immutable REST pull-request id") + assert.Equal(t, 12, cp.Number) +} + +func TestListRepoPullRequests_CapturesImmutableID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode([]map[string]any{{ + "id": 1357924681, + "number": 13, + "title": "Fix widget", + "html_url": "https://github.com/org/repo/pull/13", + "head": map[string]any{"ref": "fix", "repo": map[string]any{"full_name": "org/repo"}}, + "base": map[string]any{"ref": "main"}, + "user": map[string]any{"login": "octocat"}, + }}) + })) + defer srv.Close() + + client := newTestClient(t, srv) + cps, err := client.ListRepoPullRequests(context.Background(), "org", "repo") + require.NoError(t, err) + require.Len(t, cps, 1) + assert.Equal(t, int64(1357924681), cps[0].ID, "ListRepoPullRequests must capture the immutable REST pull-request id") + assert.Equal(t, 13, cps[0].Number) +} From 966e07a95d09ab936900b9ebc9efc55414277870 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:58:36 -0500 Subject: [PATCH 05/40] refactor(gitlab): retain database IDs for issues and proposals Signed-off-by: Dharit Shah --- internal/forge/gitlab/issue.go | 6 + internal/forge/gitlab/mr.go | 4 + internal/forge/gitlab/trace_identity_test.go | 173 +++++++++++++++++++ 3 files changed, 183 insertions(+) create mode 100644 internal/forge/gitlab/trace_identity_test.go diff --git a/internal/forge/gitlab/issue.go b/internal/forge/gitlab/issue.go index a6e45ddec9..c48e5f5a6f 100644 --- a/internal/forge/gitlab/issue.go +++ b/internal/forge/gitlab/issue.go @@ -29,6 +29,7 @@ func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body s } var result struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` Desc string `json:"description"` @@ -40,6 +41,7 @@ func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body s } return &forge.Issue{ + ID: result.ID, Number: result.IID, Title: result.Title, Body: result.Desc, @@ -58,6 +60,7 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in } var result struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` Desc string `json:"description"` @@ -76,6 +79,7 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in state = "open" } return &forge.Issue{ + ID: result.ID, Number: result.IID, Title: result.Title, Body: result.Desc, @@ -107,6 +111,7 @@ func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, lab } var raw []struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` Desc string `json:"description"` @@ -119,6 +124,7 @@ func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, lab for _, item := range raw { result = append(result, forge.Issue{ + ID: item.ID, Number: item.IID, Title: item.Title, Body: item.Desc, diff --git a/internal/forge/gitlab/mr.go b/internal/forge/gitlab/mr.go index bb48e74eca..5619bd592a 100644 --- a/internal/forge/gitlab/mr.go +++ b/internal/forge/gitlab/mr.go @@ -77,6 +77,7 @@ func (c *LiveClient) createMergeRequest(ctx context.Context, projPath string, pa } var mr struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` WebURL string `json:"web_url"` @@ -88,6 +89,7 @@ func (c *LiveClient) createMergeRequest(ctx context.Context, projPath string, pa } return &forge.ChangeProposal{ + ID: mr.ID, Number: mr.IID, URL: mr.WebURL, Title: mr.Title, @@ -112,6 +114,7 @@ func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo strin } var mrs []struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` WebURL string `json:"web_url"` @@ -151,6 +154,7 @@ func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo strin headRepo = resolved } result = append(result, forge.ChangeProposal{ + ID: mr.ID, Number: mr.IID, URL: mr.WebURL, Title: mr.Title, diff --git a/internal/forge/gitlab/trace_identity_test.go b/internal/forge/gitlab/trace_identity_test.go new file mode 100644 index 0000000000..c7dd80e107 --- /dev/null +++ b/internal/forge/gitlab/trace_identity_test.go @@ -0,0 +1,173 @@ +package gitlab + +import ( + "context" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +// The tests in this file are V03 for AISDLC-576: the immutable database IDs +// required by the D01 identity tuple must survive adapter mapping. GitLab's +// per-project IIDs are display values; the database `id` is the identity, +// and issue and merge-request id spaces are independent. + +func TestGetIssue_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/issues/5", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, map[string]any{ + "id": 987654321, + "iid": 5, + "title": "Widget is broken", + "description": "details", + "web_url": "https://gitlab.com/owner/repo/-/issues/5", + "state": "opened", + }) + }) + + issue, err := client.GetIssue(ctx, "owner", "repo", 5) + require.NoError(t, err) + assert.True(t, handlerCalled, "handler was not called — URL path mismatch") + assert.Equal(t, int64(987654321), issue.ID, "GetIssue must capture the immutable database id, not the IID") + assert.Equal(t, 5, issue.Number, "the display IID is still addressed by (owner, repo, iid)") +} + +func TestCreateIssue_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/issues", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusCreated, map[string]any{ + "id": 987654322, + "iid": 6, + "title": "New work", + "description": "body", + "web_url": "https://gitlab.com/owner/repo/-/issues/6", + }) + }) + + issue, err := client.CreateIssue(ctx, "owner", "repo", "New work", "body") + assert.True(t, handlerCalled) + require.NoError(t, err) + assert.Equal(t, int64(987654322), issue.ID, "CreateIssue must capture the immutable database id") + assert.Equal(t, 6, issue.Number) +} + +// TestGetIssue_NestedNamespace exercises a project path under nested groups: +// the identity fields must survive the same escaped-path mapping. +func TestGetIssue_NestedNamespace(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/group%2Fsubgroup%2Frepo/issues/7", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, map[string]any{ + "id": 987654323, + "iid": 7, + "title": "Nested", + "description": "details", + "web_url": "https://gitlab.com/group/subgroup/repo/-/issues/7", + "state": "opened", + }) + }) + + issue, err := client.GetIssue(ctx, "group/subgroup", "repo", 7) + require.NoError(t, err) + assert.True(t, handlerCalled, "handler was not called — URL path mismatch") + assert.Equal(t, int64(987654323), issue.ID) + assert.Equal(t, 7, issue.Number) +} + +func TestCreateChangeProposal_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/merge_requests", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusCreated, map[string]any{ + "id": 555444333, + "iid": 9, + "title": "Add widget", + "web_url": "https://gitlab.com/owner/repo/-/merge_requests/9", + "source_branch": "feature", + "target_branch": "main", + }) + }) + + cp, err := client.CreateChangeProposal(ctx, "owner", "repo", "Add widget", "body", "feature", "main") + assert.True(t, handlerCalled) + require.NoError(t, err) + assert.Equal(t, int64(555444333), cp.ID, "CreateChangeProposal must capture the immutable database MR id, not the IID") + assert.Equal(t, 9, cp.Number) +} + +func TestListRepoPullRequests_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/merge_requests", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, []map[string]any{{ + "id": 555444334, + "iid": 10, + "title": "Fix widget", + "web_url": "https://gitlab.com/owner/repo/-/merge_requests/10", + "source_branch": "fix", + "target_branch": "main", + "author": map[string]any{"username": "octocat"}, + }}) + }) + + cps, err := client.ListRepoPullRequests(ctx, "owner", "repo") + assert.True(t, handlerCalled) + require.NoError(t, err) + require.Len(t, cps, 1) + assert.Equal(t, int64(555444334), cps[0].ID, "ListRepoPullRequests must capture the immutable database MR id") + assert.Equal(t, 10, cps[0].Number) +} + +// TestListOpenIssues_CapturesDatabaseID keeps the display and identity +// fields distinguishable on the listing path used by polling. +func TestListOpenIssues_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/issues", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, []map[string]any{{ + "id": 987654324, + "iid": 11, + "title": "Listed", + "description": "details", + "web_url": "https://gitlab.com/owner/repo/-/issues/11", + }}) + }) + + issues, err := client.ListOpenIssues(ctx, "owner", "repo") + assert.True(t, handlerCalled) + require.NoError(t, err) + require.Len(t, issues, 1) + assert.Equal(t, int64(987654324), issues[0].ID) + assert.Equal(t, 11, issues[0].Number) +} + +// Compile-time guard: the fixture values above must stay forge.Issue / +// forge.ChangeProposal fields. +var ( + _ = forge.Issue{ID: 1} + _ = forge.ChangeProposal{ID: 1} +) From f6c0f31d6a41b9366f9c903a07c3b9a6a83c4651 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:59:04 -0500 Subject: [PATCH 06/40] refactor(tracker): propagate immutable issue and project identity Signed-off-by: Dharit Shah --- internal/forge/jira/client.go | 2 +- internal/forge/jira/client_test.go | 54 +++++++++++ internal/forge/jira/types.go | 10 ++ internal/tracker/fake_jira.go | 10 +- internal/tracker/forge_client.go | 2 + internal/tracker/jira_client.go | 21 ++++ internal/tracker/trace_identity_test.go | 122 ++++++++++++++++++++++++ internal/tracker/tracker.go | 21 +++- 8 files changed, 235 insertions(+), 7 deletions(-) create mode 100644 internal/tracker/trace_identity_test.go diff --git a/internal/forge/jira/client.go b/internal/forge/jira/client.go index 68f956e09d..bd7d916ed9 100644 --- a/internal/forge/jira/client.go +++ b/internal/forge/jira/client.go @@ -351,7 +351,7 @@ type searchRequest struct { // plausibly exceed the client's 10MB decode cap — and since a failed // search aborts the whole cycle with the same data returning every time, // that failure mode would wedge the poller for the entire project. -var searchFields = []string{"summary", "status", "labels", "reporter", "created", "updated"} +var searchFields = []string{"summary", "status", "labels", "reporter", "created", "updated", "project"} // maxSearchPages limits pagination to prevent unbounded memory growth // from overly broad JQL queries. diff --git a/internal/forge/jira/client_test.go b/internal/forge/jira/client_test.go index 1d49890591..f282c31162 100644 --- a/internal/forge/jira/client_test.go +++ b/internal/forge/jira/client_test.go @@ -781,6 +781,60 @@ func TestGetIssue(t *testing.T) { assert.Equal(t, "new", issue.Fields.Status.StatusCategory.Key) } +// TestGetIssue_CapturesProjectRef is V03 for AISDLC-576: the immutable +// project database ID (the D01 Jira container identity) must survive issue +// reads, distinct from the display project key. +func TestGetIssue_CapturesProjectRef(t *testing.T) { + t.Parallel() + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/rest/api/3/issue/PROJ-42", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, map[string]any{ + "id": "10042", + "key": "PROJ-42", + "fields": map[string]any{ + "summary": "Test issue", + "project": map[string]any{"id": "10000", "key": "PROJ"}, + }, + }) + }) + + issue, err := client.GetIssue(ctx, "PROJ-42") + assert.True(t, handlerCalled) + require.NoError(t, err) + require.NotNil(t, issue.Fields.Project, "project ref must be captured") + assert.Equal(t, "10000", issue.Fields.Project.ID, "immutable project database id") + assert.Equal(t, "PROJ", issue.Fields.Project.Key, "display project key") +} + +func TestSearchIssues_CapturesProjectRef(t *testing.T) { + client, mux := setupTest(t) + handlerCalled := false + mux.HandleFunc("/rest/api/3/search/jql", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + var body searchRequest + if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) { + return + } + assert.Contains(t, body.Fields, "project", "polling must request immutable container identity") + writeJSON(t, w, http.StatusOK, map[string]any{ + "isLast": true, + "issues": []any{map[string]any{"id": "10042", "key": "PROJ-42", "fields": map[string]any{ + "project": map[string]any{"id": "10000", "key": "PROJ"}, + }}}, + }) + }) + issues, err := client.SearchIssues(context.Background(), "project = PROJ", 0) + assert.True(t, handlerCalled) + require.NoError(t, err) + require.Len(t, issues, 1) + require.NotNil(t, issues[0].Fields.Project) + assert.Equal(t, "10000", issues[0].Fields.Project.ID) +} + func TestGetIssue_IssueTypeAndCustomFields(t *testing.T) { t.Parallel() client, mux := setupTest(t) diff --git a/internal/forge/jira/types.go b/internal/forge/jira/types.go index 158e0039c0..46907ed020 100644 --- a/internal/forge/jira/types.go +++ b/internal/forge/jira/types.go @@ -32,6 +32,9 @@ type IssueFields struct { Updated string `json:"updated"` Comment *CommentPage `json:"comment,omitempty"` IssueType *IssueType `json:"issuetype,omitempty"` + // Project is the issue's project. Its ID is the immutable Jira + // container identity for trace binding; the key is display-only. + Project *ProjectRef `json:"project,omitempty"` // CustomFields holds the raw JSON value of every "customfield_*" key // in the fields object, keyed by field ID (e.g. "customfield_10875"). @@ -44,6 +47,13 @@ type IssueFields struct { // customFieldPrefix is the prefix Jira uses for custom field IDs. const customFieldPrefix = "customfield_" +// ProjectRef identifies a Jira project. ID is the immutable project +// database ID (the trace container identity); Key is the display key. +type ProjectRef struct { + ID string `json:"id"` + Key string `json:"key"` +} + // UnmarshalJSON decodes the standard fields and additionally collects // every "customfield_*" key into CustomFields. func (f *IssueFields) UnmarshalJSON(data []byte) error { diff --git a/internal/tracker/fake_jira.go b/internal/tracker/fake_jira.go index 53f9d13fd8..651b0193bd 100644 --- a/internal/tracker/fake_jira.go +++ b/internal/tracker/fake_jira.go @@ -22,6 +22,8 @@ import ( type FakeJiraClient struct { Issues map[string]*jira.Issue Comments map[string][]jira.Comment + // ProjectIDs supplies immutable project IDs for created issue reads. + ProjectIDs map[string]string // CommentProperties maps "issueKey/commentID" to a map of // propertyKey -> value, mirroring Jira's per-comment entity @@ -129,8 +131,12 @@ func (f *FakeJiraClient) CreateIssue(_ context.Context, in jira.CreateIssueInput issueType.Name = in.IssueType } f.Issues[key] = &jira.Issue{ - Key: key, - Fields: jira.IssueFields{Summary: in.Summary, Description: description, IssueType: issueType}, + ID: fmt.Sprintf("%d", 10000+len(f.CreatedIssues)), + Key: key, + Fields: jira.IssueFields{ + Summary: in.Summary, Description: description, IssueType: issueType, + Project: &jira.ProjectRef{ID: f.ProjectIDs[in.ProjectKey], Key: in.ProjectKey}, + }, } return &jira.CreatedIssue{ID: fmt.Sprintf("%d", 10000+len(f.CreatedIssues)), Key: key}, nil } diff --git a/internal/tracker/forge_client.go b/internal/tracker/forge_client.go index aac72d1f7a..ad6cc030d5 100644 --- a/internal/tracker/forge_client.go +++ b/internal/tracker/forge_client.go @@ -43,6 +43,7 @@ func (c *ForgeClient) GetIssue(ctx context.Context, project string, number int) return nil, wrapNotFound(err) } return &Issue{ + ID: issue.ID, Number: issue.Number, Title: issue.Title, Body: Body(issue.Body), @@ -72,6 +73,7 @@ func (c *ForgeClient) CreateIssue(ctx context.Context, project, title string, bo return nil, wrapNotFound(err) } return &Issue{ + ID: issue.ID, Number: issue.Number, Title: issue.Title, Body: Body(issue.Body), diff --git a/internal/tracker/jira_client.go b/internal/tracker/jira_client.go index 6a17446095..dcadb88531 100644 --- a/internal/tracker/jira_client.go +++ b/internal/tracker/jira_client.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "log" "strconv" "strings" "time" @@ -120,11 +121,17 @@ func (c *JiraClient) GetIssue(ctx context.Context, project string, number int) ( if issue.Fields.IssueType != nil { issueType = issue.Fields.IssueType.Name } + var containerID int64 + if issue.Fields.Project != nil { + containerID = parseJiraID(issue.Fields.Project.ID) + } canonicalKey := issue.Key if canonicalKey == "" { canonicalKey = key } return &Issue{ + ID: parseJiraID(issue.ID), + ContainerID: containerID, Number: number, Title: issue.Fields.Summary, Body: Body(jira.ADFToMarkdown(issue.Fields.Description)), @@ -161,6 +168,7 @@ func (c *JiraClient) CreateIssue(ctx context.Context, project, title string, bod return nil, err } return &Issue{ + ID: parseJiraID(created.ID), Number: number, Title: title, Body: body, @@ -169,6 +177,19 @@ func (c *JiraClient) CreateIssue(ctx context.Context, project, title string, bod }, nil } +// parseJiraID converts a Jira issue or project ID string to the immutable +// int64 identity. Jira returns positive numeric ID strings; an invalid value +// yields 0, which callers must treat as an unresolved identity rather than +// guessing (FR-002), matching jirapoll's parseIssueID behavior. +func parseJiraID(id string) int64 { + n, err := strconv.ParseInt(id, 10, 64) + if err != nil || n < 1 { + log.Printf("WARNING: invalid Jira id %q, using 0", id) + return 0 + } + return n +} + // issueNumberFromKey returns the numeric part of a Jira issue key, e.g. // issueNumberFromKey("PROJ-123") = 123. func issueNumberFromKey(key string) (int, error) { diff --git a/internal/tracker/trace_identity_test.go b/internal/tracker/trace_identity_test.go new file mode 100644 index 0000000000..1033dbac68 --- /dev/null +++ b/internal/tracker/trace_identity_test.go @@ -0,0 +1,122 @@ +package tracker + +import ( + "context" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The tests in this file are V03 for AISDLC-576: the immutable database IDs +// required by the D01 identity tuple must survive tracker mapping, and the +// Jira immutable issue ID must stay distinct from the display key. + +func TestForgeClient_GetIssue_MapsImmutableID(t *testing.T) { + fc := forge.NewFakeClient() + fc.OpenIssues = map[string][]forge.Issue{ + "acme/widgets": { + {ID: 2468913570, Number: 42, Title: "Widget is broken", Body: "details", URL: "https://example.com/42"}, + }, + } + + c := NewForgeClient(fc) + issue, err := c.GetIssue(context.Background(), "acme/widgets", 42) + if err != nil { + t.Fatalf("GetIssue returned error: %v", err) + } + if issue.ID != 2468913570 { + t.Errorf("issue.ID = %d, want 2468913570 (immutable forge issue id)", issue.ID) + } + if issue.Number != 42 { + t.Errorf("issue.Number = %d, want 42 (display number)", issue.Number) + } +} + +func TestForgeClient_CreateIssue_MapsImmutableID(t *testing.T) { + fc := forge.NewFakeClient() + + c := NewForgeClient(fc) + issue, err := c.CreateIssue(context.Background(), "acme/widgets", "New work", "body", CreateIssueOptions{}) + if err != nil { + t.Fatalf("CreateIssue returned error: %v", err) + } + if issue.ID == 0 { + t.Errorf("issue.ID = 0, want the fake's synthesized immutable issue id") + } + if issue.Number == 0 { + t.Errorf("issue.Number = 0, want a display number") + } + if issue.ID == int64(issue.Number) { + t.Errorf("issue.ID (%d) must be a distinct id space from the display number (%d)", issue.ID, issue.Number) + } +} + +// TestJiraClient_GetIssue_IDAndKeyDistinct covers the Jira ID/key +// distinction: the immutable numeric issue id and the display key must both +// survive mapping without being conflated. +func TestJiraClient_GetIssue_IDAndKeyDistinct(t *testing.T) { + fc := &FakeJiraClient{ + Issues: map[string]*jira.Issue{ + "PROJ-42": { + ID: "10100", + Key: "PROJ-42", + Fields: jira.IssueFields{ + Summary: "Widget is broken", + Project: &jira.ProjectRef{ID: "10000", Key: "PROJ"}, + }, + }, + }, + } + + c := newTestJiraClient(t, fc, "https://acme.atlassian.net") + issue, err := c.GetIssue(context.Background(), "PROJ", 42) + if err != nil { + t.Fatalf("GetIssue returned error: %v", err) + } + if issue.ID != 10100 { + t.Errorf("issue.ID = %d, want 10100 (immutable Jira issue id)", issue.ID) + } + if issue.Key != "PROJ-42" { + t.Errorf("issue.Key = %q, want %q (display key)", issue.Key, "PROJ-42") + } + if issue.Number != 42 { + t.Errorf("issue.Number = %d, want 42 (numeric key suffix)", issue.Number) + } + assert.Equal(t, int64(10000), issue.ContainerID) +} + +func TestJiraClient_CreateIssue_MapsImmutableID(t *testing.T) { + fc := &FakeJiraClient{ProjectIDs: map[string]string{"PROJ": "20000"}} + c := newTestJiraClient(t, fc, "https://acme.atlassian.net") + + issue, err := c.CreateIssue(context.Background(), "PROJ", "New work", "body", CreateIssueOptions{IssueType: "Task"}) + if err != nil { + t.Fatalf("CreateIssue returned error: %v", err) + } + if issue.ID == 0 { + t.Errorf("issue.ID = 0, want the immutable id of the created issue") + } + if issue.Key == "" { + t.Errorf("issue.Key is empty, want the display key of the created issue") + } + assert.Zero(t, issue.ContainerID, "Jira create response has no project ID") + read, err := c.GetIssue(context.Background(), "PROJ", issue.Number) + require.NoError(t, err) + assert.Equal(t, issue.ID, read.ID) + assert.Equal(t, int64(20000), read.ContainerID, "trusted read resolves the container") +} + +func TestJiraClient_GetIssue_UnresolvedProject(t *testing.T) { + for _, project := range []*jira.ProjectRef{nil, {}, {ID: "bad"}, {ID: "0"}, {ID: "-1"}, {ID: "9223372036854775808"}} { + fc := &FakeJiraClient{Issues: map[string]*jira.Issue{ + "PROJ-42": {ID: "10100", Key: "PROJ-42", Fields: jira.IssueFields{Project: project}}, + }} + c := newTestJiraClient(t, fc, "https://acme.atlassian.net") + issue, err := c.GetIssue(context.Background(), "PROJ", 42) + require.NoError(t, err) + assert.Zero(t, issue.ContainerID, "project %#v must remain unresolved", project) + } +} diff --git a/internal/tracker/tracker.go b/internal/tracker/tracker.go index df7548bd0e..b025bd8f90 100644 --- a/internal/tracker/tracker.go +++ b/internal/tracker/tracker.go @@ -58,11 +58,24 @@ type Body string // Issue represents an issue's content, independent of the tracker backend. type Issue struct { + // Number is the display number addressing the issue as (project, + // number): GitHub's per-repo issue number, GitLab's per-project IID, + // or the numeric suffix of a Jira key. It is not a stable identity. Number int - Title string - Body Body - URL string - Labels []string + // ID is the immutable issue database ID: GitHub's REST issue id, + // GitLab's database issue id (not the IID), or Jira's numeric issue + // id string parsed to an integer. It is 0 when the backend did not + // report one; trace admission treats that as unresolved identity + // rather than guessing. + ID int64 + // ContainerID is the immutable Jira project ID supplied by GetIssue. + // Zero means unresolved: create responses and forge-backed reads need + // a separate trusted project/repository lookup before trace admission. + ContainerID int64 + Title string + Body Body + URL string + Labels []string // IssueType is the tracker's issue type name (e.g. "Bug", "Story"). // Set by the Jira client; empty for trackers that don't report one. IssueType string From 96e02edf9fc739e7e5685502eda1a24959e9aa9f Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:59:28 -0500 Subject: [PATCH 07/40] docs(telemetry): document the authenticated trace-context contract Signed-off-by: Dharit Shah --- docs/.vitepress/config.ts | 1 + .../infrastructure/distributed-tracing.md | 8 + docs/reference/trace-context.md | 229 ++++++++++++++++++ 3 files changed, 238 insertions(+) create mode 100644 docs/reference/trace-context.md diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 103b44cb98..c7b2e2dd42 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -349,6 +349,7 @@ export default defineConfig({ items: [ { text: "Config Reference", link: "/reference/config-reference" }, { text: "Harness Field Reference", link: "/reference/harness-reference" }, + { text: "Trace Context Reference", link: "/reference/trace-context" }, ], }, { diff --git a/docs/guides/infrastructure/distributed-tracing.md b/docs/guides/infrastructure/distributed-tracing.md index 5e3a511add..b6d6dbf527 100644 --- a/docs/guides/infrastructure/distributed-tracing.md +++ b/docs/guides/infrastructure/distributed-tracing.md @@ -664,6 +664,14 @@ GitHub webhooks do not support custom trace headers. Within a single work item, `fullsend.work_item_id` on the root `run` span is the correlation key for filtering related traces in a backend. +Durable work-item continuity across independent launches — signed, +entity-bound context published as metadata on the work item, with a +deterministic fallback derived from immutable entity identity — is a +separate mechanism specified in +[ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md) +and documented in the +[Trace Context Reference](../../reference/trace-context.md). + ## Operational behavior - **Export timing:** spans are exported live via the batch processor. On diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md new file mode 100644 index 0000000000..24931e4851 --- /dev/null +++ b/docs/reference/trace-context.md @@ -0,0 +1,229 @@ +# Trace Context Reference + +Version 1 of the work-item trace-context identity and signed-envelope +protocol from [ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). +This page documents the implemented contract surfaces: the immutable +identity tuple, the deterministic fallback derivation, the v1 wire format, +and the pure admission operation. Carrier publication (hidden body +metadata, Jira properties), key provisioning, and runtime admission wiring +are separate delivery slices; this page marks them where they are not yet +implemented. + +The Go implementation is +[`internal/telemetry/tracecontext`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext). +It is pure: no network I/O, no configuration reads, and it never grants +dispatch permission. + +## Identity + +Every forge entity is addressed by an immutable five-part tuple. Display +names, URLs, GitHub numbers, GitLab IIDs, and Jira keys are not identity +components. + +| Component | GitHub | GitLab | Jira | +|-----------|--------|--------|------| +| Installation | 128-bit ID provisioned with the signing key pair | same | same | +| Forge instance | web base URL (`https://github.com`, or a GHES host) | web base URL (`https://gitlab.com`, or a self-hosted host) | site base URL | +| Container | repository `id` | project `id` | project `id` | +| Entity kind | `work_item` (issue), `change_proposal` (PR) | `work_item` (issue), `change_proposal` (MR) | `work_item` (issue; Jira has no change proposal) | +| Entity | issue or PR REST `id`; PR GraphQL `fullDatabaseId` (`BigInt`) | issue or MR database `id` (not the IID) | issue `id` | + +The instance string is the normalized base URL: lowercase +`scheme://host`, using `http` or `https`, at most 253 UTF-8 bytes, no path or +trailing slash. `NormalizeInstance` builds it (accepting and removing a bare +`/`) and rejects URLs with a longer path, query, fragment, user info, or +missing host. Identity resolution, signing, and parsing require the already +canonical value; they never silently rewrite an authenticated field. + +Jira issue reads expose the project ID as `tracker.Issue.ContainerID`; search +requests include `project`. Missing or invalid project IDs stay zero +(unresolved). Jira's create response contains no project ID, so a subsequent +trusted read must resolve the container before trace admission. Forge-backed +tracker reads resolve their repository separately through `forge.Client`. +GitHub cross-repository PR creation decodes `fullDatabaseId` directly into +an `int64`, accepting numeric or string JSON without floating-point rounding; +the deprecated 32-bit GraphQL `databaseId` is not used. + +The installation ID is generated during key provisioning and identifies +one install's key set. It is authenticated inside every envelope and must +match the verifier's configured installation at admission. It is +deliberately **not** part of fallback derivation, so entities keep stable +traces regardless of key state. + +### Rename and move rules + +- Renames (issue titles, repository names, Jira project keys) never + change identity: every component is a database ID. +- Repository transfers on GitHub and GitLab preserve the database ID, so + identity survives a transfer. +- An entity moved between containers (a GitHub issue transfer, a Jira + project move) has a **new binding** — a different container or entity + ID — and therefore a new identity. A previously published envelope + fails the binding check and the moved entity falls back. A move is + never treated as a rename. + +### Fallback derivation (v1) + +When no admissible stored context exists, the entity's context is derived +deterministically: + +- Input: the forge instance, container, kind, and entity — never the + installation. +- SHA-256 over the exact concatenation below. Only strings are + length-prefixed; all integers are big-endian: + `uint16(33) || "fullsend.tracecontext.identity.v1" || uint16(N) || + instance[N] || uint64(container) || byte(kind) || uint64(entity)`. + `N` counts UTF-8 bytes, container/entity are in `[1, 2^63−1]`, and kind + is `0x01` (work item) or `0x02` (change proposal). +- TraceID = the first 16 digest bytes; the anchor SpanID = the next 8. +- An all-zero result (probability 2⁻¹²⁸ for the trace, 2⁻⁶⁴ for the span) + replaces only that ID's final byte with `0x01`, so derived IDs are valid. + +The derivation is pure, so independent launches and concurrent first +events converge on identical nonzero IDs without shared state. The anchor +SpanID is a synthetic parent reference by protocol choice: no exported span +carries the anchor ID, the anchor is never repointed, and operation spans +keep distinct SDK-generated IDs. OpenTelemetry supports custom ID generators +(`WithIDGenerator`); this contract deliberately uses an unexported anchor +rather than creating a real root span with that ID. + +For `https://github.com`, container `274390431`, kind `0x01`, and entity +`2468913570`, the exact input is: + +```text +002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631 +001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a2 +``` + +Concatenate those hex lines before hashing. The TraceID is +`c9bdb0e38247ebbe2e0f1039250c32d4`; the anchor is `892a346c55356aca`. +Additional independent GitLab/Jira vectors and an SDK exporter lifecycle +test are in `identity_test.go`; runtime integration remains a later slice. + +## Signed envelope (wire format v1) + +One fixed-layout binary encoding serves both message domains; all +integers are big-endian, and the Ed25519 signature covers every byte from +the magic through the nonce — there are no unsigned fields. + +| Offset | Size | Field | Constraints | +|--------|------|-------|-------------| +| 0 | 4 | Magic `FSTC` | exact bytes | +| 4 | 1 | Version | `0x01`; anything else rejects | +| 5 | 1 | Message domain | `0x01` bound envelope, `0x02` pending marker | +| 6 | 8 | Key ID | first 8 bytes of SHA-256(public key) | +| 14 | 16 | Installation ID | nonzero | +| 30 | 2 | Instance length N | `1 ≤ N ≤ 253` | +| 32 | N | Forge instance | normalized form, UTF-8, no NUL | +| 32+N | 8 | Container ID | `int64 ≥ 1` | +| 40+N | 1 | Entity kind | `0x01` work item, `0x02` change proposal | +| 41+N | 8 | Entity ID | `int64 ≥ 1`; bound envelopes only — pending markers omit these 8 bytes, retaining the kind byte | +| · | 16 | Trace ID | nonzero | +| · | 8 | Parent/anchor Span ID | nonzero | +| · | 1 | Provenance kind | `0x00` none, `0x01` source link, `0x02` scenario | +| · | 0/24/32 | Provenance fields | none; source link = 16B source TraceID + 8B source SpanID; scenario = 16B scenario TraceID + 16B invocation ID | +| · | 16 | Nonce | `crypto/rand`, nonzero, unique per creation intent | +| end−64 | 64 | Ed25519 signature | over bytes `[0, end−64)` | + +The maximum legal size is 439 bytes (bound envelope, scenario provenance, +253-byte instance); carriers hold the envelope as unwrapped standard +base64 (≤ 588 characters, no line breaks). + +Strict parsing rules: + +- The total length must equal the exact structural length for the parsed + domain and provenance kind; trailing bytes reject. +- Duplicate and unknown fields are structurally impossible in the fixed + layout. +- Every enumerated byte and ID must satisfy its constraint; invalid + values reject rather than degrade. +- Unknown versions reject — never a partial parse. +- Identical duplicate carriers are acceptable (idempotent publication); + any differing carriers reject — never first-match. + +### Domains, keys, and nonces + +The domain byte is covered by the signature, so a pending marker cannot +be replayed as a bound envelope and vice versa. A pending marker carries +the creation's intended context and provenance as signed intent, omits +the entity ID (the destination does not exist yet), and grants neither +context, parent, nor source link. The nonce links a pending marker to +the bound envelope published after creation; admission never depends on +having seen the marker. + +The key selector resolves **only** against the verifier's configured +eligible keys (active plus retained). Envelopes never carry public keys +or key locations, and metadata can never select a signer or a remote key +URL. After rotation, metadata signed by an older retained key remains +verifiable while new metadata uses the active key. +Missing or malformed-length verification keys yield `unknown-key` fallback +without context or provenance; they never reach Ed25519 verification. + +### Provenance consistency + +- Source-link provenance (ordinary created work) requires the envelope + TraceID to differ from the source TraceID: the destination keeps its + own trace and the source context is a link, never a parent. +- Scenario provenance (behaviour-test work) requires the envelope + TraceID to equal the scenario TraceID: descendants inherit the + scenario trace with distinct operation spans. + +## Admission + +`Admit(expected Identity, keys, candidates...)` is the pure decision +operation. It takes the trusted expected binding, the configured eligible +verification keys, and bounded candidate carrier bytes, and returns +exactly one outcome: + +- **Admitted**: a verified bound envelope matched every binding + component. The result carries the admitted TraceID, parent SpanID, and + authenticated provenance. +- **Pending**: a verified pending marker matched the expected scope. It + grants nothing; bounded rereads are caller policy. +- **Fallback**: nothing was admissible. The caller uses the + entity-derived fallback. + +Fallback reason codes are redacted diagnostics — `absent`, `malformed`, +`oversized`, `unknown-version`, `unknown-key`, `bad-signature`, +`binding-mismatch`, `conflicting-carrier`, `provenance` — never key +material or raw bytes. A plain W3C `traceparent` is never an envelope. + +The result structurally cannot carry sampling flags, `tracestate`, +baggage, or dispatch permission. Trace admission and dispatch +authorization are independent decisions; a denied actor never dispatches +regardless of admission, and an admitted envelope never authorizes +anything. + +An unresolved identity (missing instance, container, kind, or entity) is +explicit: callers must postpone dispatch with diagnostics rather than +derive a fallback or guess. + +## Go API + +| Symbol | Purpose | +|--------|---------| +| `Identity` | The immutable binding tuple | +| `Identity.Resolved` | Whether forge-side identity components are present | +| `DeriveFallback` | The v1 deterministic fallback context | +| `NormalizeInstance` | Canonical `scheme://host` instance form | +| `Envelope` | A decoded v1 envelope or pending marker | +| `Envelope.Sign` | Validate and sign with an Ed25519 private key (host-side only) | +| `Envelope.Marshal` | Canonical wire bytes | +| `Parse` | Strict bounded decode | +| `DecodeCarrier` | Strict base64 carrier decode | +| `KeyID` | The 8-byte key selector for a public key | +| `Admit` | The pure admission decision | +| `Result`, `Outcome` | Admission outcome and admitted IDs | + +The package must stay importable from public behaviour-test code: it +must not depend on `internal/cli`, `internal/repos`, `internal/layers`, +or the nested mintcore module. + +## Compatibility + +The golden test vectors in +[`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/envelope_test.go) +pin the exact signed bytes of one envelope per domain and provenance +kind. Any change to the wire layout, derivation, or key-selector rules is +a compatibility break that requires a new version byte and a reviewed +migration path. Unknown versions already reject cleanly. From 6ece68afc05e3825e1e1dfa2ba6116562d59afba Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 13:02:46 -0500 Subject: [PATCH 08/40] test: address trace-context review consistency findings Signed-off-by: Dharit Shah --- internal/forge/github/trace_identity_test.go | 4 +- internal/forge/gitlab/trace_identity_test.go | 4 +- internal/forge/jira/client_test.go | 5 +- .../telemetry/tracecontext/envelope_test.go | 2 +- .../telemetry/tracecontext/identity_test.go | 4 +- internal/tracker/trace_identity_test.go | 60 +++++-------------- 6 files changed, 26 insertions(+), 53 deletions(-) diff --git a/internal/forge/github/trace_identity_test.go b/internal/forge/github/trace_identity_test.go index 4ff9b3cc4b..d5e8648a55 100644 --- a/internal/forge/github/trace_identity_test.go +++ b/internal/forge/github/trace_identity_test.go @@ -11,8 +11,8 @@ import ( "github.com/stretchr/testify/require" ) -// The tests in this file are V03 for AISDLC-576: the immutable database IDs -// required by the D01 identity tuple must survive adapter mapping. GitHub's +// The tests in this file cover ADR 0154: the immutable database IDs +// required by the identity tuple must survive adapter mapping. GitHub's // per-repo numbers are display values; the REST `id` is the identity. func TestGetIssue_CapturesImmutableID(t *testing.T) { diff --git a/internal/forge/gitlab/trace_identity_test.go b/internal/forge/gitlab/trace_identity_test.go index c7dd80e107..3286096f36 100644 --- a/internal/forge/gitlab/trace_identity_test.go +++ b/internal/forge/gitlab/trace_identity_test.go @@ -11,8 +11,8 @@ import ( "github.com/fullsend-ai/fullsend/internal/forge" ) -// The tests in this file are V03 for AISDLC-576: the immutable database IDs -// required by the D01 identity tuple must survive adapter mapping. GitLab's +// The tests in this file cover ADR 0154: the immutable database IDs +// required by the identity tuple must survive adapter mapping. GitLab's // per-project IIDs are display values; the database `id` is the identity, // and issue and merge-request id spaces are independent. diff --git a/internal/forge/jira/client_test.go b/internal/forge/jira/client_test.go index f282c31162..ff5ef96950 100644 --- a/internal/forge/jira/client_test.go +++ b/internal/forge/jira/client_test.go @@ -781,8 +781,8 @@ func TestGetIssue(t *testing.T) { assert.Equal(t, "new", issue.Fields.Status.StatusCategory.Key) } -// TestGetIssue_CapturesProjectRef is V03 for AISDLC-576: the immutable -// project database ID (the D01 Jira container identity) must survive issue +// TestGetIssue_CapturesProjectRef covers ADR 0154: the immutable +// project database ID (the Jira container identity) must survive issue // reads, distinct from the display project key. func TestGetIssue_CapturesProjectRef(t *testing.T) { t.Parallel() @@ -811,6 +811,7 @@ func TestGetIssue_CapturesProjectRef(t *testing.T) { } func TestSearchIssues_CapturesProjectRef(t *testing.T) { + t.Parallel() client, mux := setupTest(t) handlerCalled := false mux.HandleFunc("/rest/api/3/search/jql", func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index 518a05f4af..e253b1f570 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -15,7 +15,7 @@ import ( "go.opentelemetry.io/otel/trace" ) -// The tests in this file are V02/V04 for AISDLC-576: exact signed-byte +// The tests in this file cover ADR 0154: exact signed-byte // fixtures, tamper-every-field, cross-binding replay, strict parser limits, // duplicate/oversized/zero-ID rejection, retained keys, and pending markers // granting nothing. Golden hex constants pin the frozen v1 wire format for diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index 421e9a3479..bb65f79e51 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -200,12 +200,12 @@ func TestDeriveFallback_ConcurrentFirstEvents(t *testing.T) { // deriveChildEnv re-executes this test binary as a fresh process that // derives the V01 fixture and prints the result, proving there is no shared // in-memory state behind convergence. -const deriveChildEnv = "FULLSEND_TRACONTEXT_DERIVE_CHILD=1" +const deriveChildEnv = "FULLSEND_TRACECONTEXT_DERIVE_CHILD=1" // TestDeriveFallback_IdenticalAcrossProcesses is V01: two fresh processes // derive identical nonzero fallbacks for the same immutable identity. func TestDeriveFallback_IdenticalAcrossProcesses(t *testing.T) { - if os.Getenv("FULLSEND_TRACONTEXT_DERIVE_CHILD") == "1" { + if os.Getenv("FULLSEND_TRACECONTEXT_DERIVE_CHILD") == "1" { fb, ok := DeriveFallback(v01Identity()) if !ok { fmt.Println("unresolved") diff --git a/internal/tracker/trace_identity_test.go b/internal/tracker/trace_identity_test.go index 1033dbac68..4b229fab12 100644 --- a/internal/tracker/trace_identity_test.go +++ b/internal/tracker/trace_identity_test.go @@ -10,8 +10,8 @@ import ( "github.com/stretchr/testify/require" ) -// The tests in this file are V03 for AISDLC-576: the immutable database IDs -// required by the D01 identity tuple must survive tracker mapping, and the +// The tests in this file cover ADR 0154: the immutable database IDs +// required by the identity tuple must survive tracker mapping, and the // Jira immutable issue ID must stay distinct from the display key. func TestForgeClient_GetIssue_MapsImmutableID(t *testing.T) { @@ -24,15 +24,9 @@ func TestForgeClient_GetIssue_MapsImmutableID(t *testing.T) { c := NewForgeClient(fc) issue, err := c.GetIssue(context.Background(), "acme/widgets", 42) - if err != nil { - t.Fatalf("GetIssue returned error: %v", err) - } - if issue.ID != 2468913570 { - t.Errorf("issue.ID = %d, want 2468913570 (immutable forge issue id)", issue.ID) - } - if issue.Number != 42 { - t.Errorf("issue.Number = %d, want 42 (display number)", issue.Number) - } + require.NoError(t, err) + assert.Equal(t, int64(2468913570), issue.ID, "immutable forge issue id") + assert.Equal(t, 42, issue.Number, "display number") } func TestForgeClient_CreateIssue_MapsImmutableID(t *testing.T) { @@ -40,18 +34,10 @@ func TestForgeClient_CreateIssue_MapsImmutableID(t *testing.T) { c := NewForgeClient(fc) issue, err := c.CreateIssue(context.Background(), "acme/widgets", "New work", "body", CreateIssueOptions{}) - if err != nil { - t.Fatalf("CreateIssue returned error: %v", err) - } - if issue.ID == 0 { - t.Errorf("issue.ID = 0, want the fake's synthesized immutable issue id") - } - if issue.Number == 0 { - t.Errorf("issue.Number = 0, want a display number") - } - if issue.ID == int64(issue.Number) { - t.Errorf("issue.ID (%d) must be a distinct id space from the display number (%d)", issue.ID, issue.Number) - } + require.NoError(t, err) + assert.NotZero(t, issue.ID, "the fake's synthesized immutable issue id") + assert.NotZero(t, issue.Number, "display number") + assert.NotEqual(t, int64(issue.Number), issue.ID, "identity and display number use distinct id spaces") } // TestJiraClient_GetIssue_IDAndKeyDistinct covers the Jira ID/key @@ -73,18 +59,10 @@ func TestJiraClient_GetIssue_IDAndKeyDistinct(t *testing.T) { c := newTestJiraClient(t, fc, "https://acme.atlassian.net") issue, err := c.GetIssue(context.Background(), "PROJ", 42) - if err != nil { - t.Fatalf("GetIssue returned error: %v", err) - } - if issue.ID != 10100 { - t.Errorf("issue.ID = %d, want 10100 (immutable Jira issue id)", issue.ID) - } - if issue.Key != "PROJ-42" { - t.Errorf("issue.Key = %q, want %q (display key)", issue.Key, "PROJ-42") - } - if issue.Number != 42 { - t.Errorf("issue.Number = %d, want 42 (numeric key suffix)", issue.Number) - } + require.NoError(t, err) + assert.Equal(t, int64(10100), issue.ID, "immutable Jira issue id") + assert.Equal(t, "PROJ-42", issue.Key, "display key") + assert.Equal(t, 42, issue.Number, "numeric key suffix") assert.Equal(t, int64(10000), issue.ContainerID) } @@ -93,15 +71,9 @@ func TestJiraClient_CreateIssue_MapsImmutableID(t *testing.T) { c := newTestJiraClient(t, fc, "https://acme.atlassian.net") issue, err := c.CreateIssue(context.Background(), "PROJ", "New work", "body", CreateIssueOptions{IssueType: "Task"}) - if err != nil { - t.Fatalf("CreateIssue returned error: %v", err) - } - if issue.ID == 0 { - t.Errorf("issue.ID = 0, want the immutable id of the created issue") - } - if issue.Key == "" { - t.Errorf("issue.Key is empty, want the display key of the created issue") - } + require.NoError(t, err) + assert.NotZero(t, issue.ID, "immutable id of the created issue") + assert.NotEmpty(t, issue.Key, "display key of the created issue") assert.Zero(t, issue.ContainerID, "Jira create response has no project ID") read, err := c.GetIssue(context.Background(), "PROJ", issue.Number) require.NoError(t, err) From 4db927eaee7bc33b2ff0bb161493cd0d0f6acd76 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 13:04:00 -0500 Subject: [PATCH 09/40] refactor(telemetry): simplify and cover envelope bounds checks Signed-off-by: Dharit Shah --- internal/telemetry/tracecontext/envelope.go | 28 ++----- .../telemetry/tracecontext/envelope_test.go | 78 ++++++++----------- 2 files changed, 41 insertions(+), 65 deletions(-) diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index 8b649a1108..60917af7fd 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -241,10 +241,7 @@ func (e *Envelope) Sign(key ed25519.PrivateKey) error { if err := e.checkConsistency(); err != nil { return err } - pub, ok := key.Public().(ed25519.PublicKey) - if !ok { - return errors.New("tracecontext: signing key has no Ed25519 public half") - } + pub := key.Public().(ed25519.PublicKey) e.KeyID = KeyID(pub) copy(e.Signature[:], ed25519.Sign(key, e.payload())) return nil @@ -280,7 +277,7 @@ func Parse(b []byte) (*Envelope, error) { return nil, fmt.Errorf("%w: domain %#02x", errMalformed, b[5]) } - off := 6 + off := 32 grab := func(n int) ([]byte, error) { if off+n > len(b) { return nil, fmt.Errorf("%w: truncated at %d", errMalformed, off) @@ -291,25 +288,14 @@ func Parse(b []byte) (*Envelope, error) { } e := &Envelope{Domain: domain} - p, err := grab(8) - if err != nil { - return nil, err - } - copy(e.KeyID[:], p) - p, err = grab(16) - if err != nil { - return nil, err - } - copy(e.Installation[:], p) - p, err = grab(2) - if err != nil { - return nil, err - } - instLen := int(binary.BigEndian.Uint16(p)) + // The minimum-length check covers the fixed 32-byte header. + copy(e.KeyID[:], b[6:14]) + copy(e.Installation[:], b[14:30]) + instLen := int(binary.BigEndian.Uint16(b[30:32])) if instLen < 1 || instLen > 253 { return nil, fmt.Errorf("%w: instance length %d", errMalformed, instLen) } - p, err = grab(instLen) + p, err := grab(instLen) if err != nil { return nil, err } diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index e253b1f570..37e6cbbd91 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "encoding/binary" "encoding/hex" + "fmt" "reflect" "strings" "testing" @@ -637,53 +638,42 @@ func TestSign_RejectsWrongKeySize(t *testing.T) { assert.Error(t, err, "Sign must reject a mis-sized private key") } -// TestParse_Truncations walks every truncation of a maximal envelope: no -// prefix may parse, and none may panic. +// Long instances let truncations reach every variable-field boundary +// beyond the minimum-length check, including both provenance layouts. func TestParse_Truncations(t *testing.T) { - raw, _ := signedGolden(t, DomainBound, ProvenanceScenario) - for n := 0; n < len(raw); n++ { - _, err := Parse(raw[:n]) - require.Error(t, err, "truncation to %d bytes must not parse", n) - } -} - -// TestParse_ShortTails exercises mid-structure bounds failures: buffers -// that pass the minimum-length and header checks but end inside a later -// fixed-size field. The instance length is chosen per buffer so each -// truncation point lands in a different grab. -func TestParse_ShortTails(t *testing.T) { - build := func(instLen, total int) []byte { - b := make([]byte, total) - copy(b, magic[:]) - b[4] = versionV1 - b[5] = byte(DomainBound) - binary.BigEndian.PutUint16(b[30:32], uint16(instLen)) - for i := 32; i < 32+instLen && i < total; i++ { - b[i] = 'x' + for _, domain := range []Domain{DomainBound, DomainPending} { + for _, provenance := range []ProvenanceKind{ProvenanceNone, ProvenanceSourceLink, ProvenanceScenario} { + for _, instance := range []string{goldenIdentity().Instance, "https://" + strings.Repeat("a.", 122) + "a"} { + t.Run(fmt.Sprintf("domain=%d/provenance=%d/instance=%d", domain, provenance, len(instance)), func(t *testing.T) { + raw, keys := signedGolden(t, domain, provenance) + // Change the precomputed fixture's instance and re-sign independently. + extended := append(bytes.Clone(raw[:32]), []byte(instance)...) + extended = append(extended, raw[32+len(goldenIdentity().Instance):]...) + binary.BigEndian.PutUint16(extended[30:32], uint16(len(instance))) + raw = resign(t, goldenKey(), extended) + + parsed, err := Parse(raw) + require.NoError(t, err, "complete envelope must parse") + assert.Equal(t, raw, parsed.Marshal()) + expected := goldenIdentity() + expected.Instance = instance + outcome := OutcomeAdmitted + if domain == DomainPending { + outcome = OutcomePending + } + require.Equal(t, outcome, Admit(expected, keys, raw).Outcome) + + for n := 0; n < len(raw); n++ { + parsed, err := Parse(raw[:n]) + require.ErrorIs(t, err, errMalformed, "truncation to %d bytes", n) + assert.Nil(t, parsed) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, + Admit(expected, keys, raw[:n]), "truncation to %d bytes grants nothing", n) + } + }) + } } - return b } - // Instance field overruns the buffer. - _, err := Parse(build(253, 150)) - assert.Error(t, err) - // Container field overruns. - _, err = Parse(build(100, 135)) - assert.Error(t, err) - // Entity field overruns. - _, err = Parse(build(100, 143)) - assert.Error(t, err) - // Trace field overruns. - _, err = Parse(build(100, 151)) - assert.Error(t, err) - // Span field overruns. - _, err = Parse(build(100, 159)) - assert.Error(t, err) - // Provenance kind byte overruns. - _, err = Parse(build(100, 167)) - assert.Error(t, err) - // Signature region overruns (nonce fits, 64-byte signature does not). - _, err = Parse(build(100, 183)) - assert.Error(t, err) } func FuzzParse(f *testing.F) { From 6bc67036eb95c63da781d2ec18ffcf05ba1fa351 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 13:06:42 -0500 Subject: [PATCH 10/40] refactor(telemetry): isolate and test zero-ID fallback guards Signed-off-by: Dharit Shah --- internal/telemetry/tracecontext/identity.go | 10 ++++---- .../telemetry/tracecontext/identity_test.go | 23 +++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index a8f69631ae..eee058acbe 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -109,16 +109,18 @@ func DeriveFallback(id Identity) (fb Fallback, ok bool) { sum := h.Sum(nil) copy(fb.TraceID[:], sum[0:16]) copy(fb.AnchorSpanID[:], sum[16:24]) - // Deterministic nonzero guarantee: SHA-256 output is all-zero with - // probability 2^-128 (trace) / 2^-64 (span); substitute a documented - // nonzero value so callers never see an invalid ID. + return nonzeroFallback(fb), true +} + +// All-zero digest slices use the documented v1 substitute so IDs stay valid. +func nonzeroFallback(fb Fallback) Fallback { if fb.TraceID == (trace.TraceID{}) { fb.TraceID[15] = 0x01 } if fb.AnchorSpanID == (trace.SpanID{}) { fb.AnchorSpanID[7] = 0x01 } - return fb, true + return fb } // NormalizeInstance canonicalizes a forge web base URL to the D01 instance diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index bb65f79e51..96866c6e1f 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -307,6 +307,29 @@ func TestDeriveFallback_FixedVectors(t *testing.T) { } } +func TestNonzeroFallback(t *testing.T) { + t.Parallel() + traceID := trace.TraceID{0: 0xab, 15: 0xcd} + anchor := trace.SpanID{0: 0xef, 7: 0x42} + for _, tc := range []struct { + name string + in Fallback + want Fallback + }{ + {"both zero", Fallback{}, Fallback{trace.TraceID{15: 1}, trace.SpanID{7: 1}}}, + {"zero trace", Fallback{AnchorSpanID: anchor}, Fallback{trace.TraceID{15: 1}, anchor}}, + {"zero anchor", Fallback{TraceID: traceID}, Fallback{traceID, trace.SpanID{7: 1}}}, + {"nonzero preserved", Fallback{traceID, anchor}, Fallback{traceID, anchor}}, + } { + t.Run(tc.name, func(t *testing.T) { + got := nonzeroFallback(tc.in) + assert.Equal(t, tc.want, got) + assert.True(t, got.TraceID.IsValid()) + assert.True(t, got.AnchorSpanID.IsValid()) + }) + } +} + func TestFallback_SyntheticAnchorExportLifecycle(t *testing.T) { seen := map[trace.SpanID]bool{} for range 2 { From f536adc6a2d63b0f82fb51dd0d524eab0f4585e4 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 14:52:02 -0500 Subject: [PATCH 11/40] fix(github): preserve created PRs with unresolved database IDs Signed-off-by: Dharit Shah --- docs/reference/trace-context.md | 3 ++- internal/forge/github/github.go | 16 +++++++----- internal/forge/github/github_test.go | 38 +++++++++++++++------------- 3 files changed, 32 insertions(+), 25 deletions(-) diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 24931e4851..dcde03e0fd 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -42,7 +42,8 @@ trusted read must resolve the container before trace admission. Forge-backed tracker reads resolve their repository separately through `forge.Client`. GitHub cross-repository PR creation decodes `fullDatabaseId` directly into an `int64`, accepting numeric or string JSON without floating-point rounding; -the deprecated 32-bit GraphQL `databaseId` is not used. +the deprecated 32-bit GraphQL `databaseId` is not used. Missing or invalid +IDs leave identity unresolved without discarding a successful PR creation. The installation ID is generated during key provisioning and identifies one install's key set. It is authenticated inside every envelope and must diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index d88972e7f0..c22055adbe 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -2568,10 +2568,10 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne Data struct { CreatePullRequest struct { PullRequest struct { - FullDatabaseID json.Number `json:"fullDatabaseId"` - Number int `json:"number"` - Title string `json:"title"` - URL string `json:"url"` + FullDatabaseID json.RawMessage `json:"fullDatabaseId"` + Number int `json:"number"` + Title string `json:"title"` + URL string `json:"url"` } `json:"pullRequest"` } `json:"createPullRequest"` } `json:"data"` @@ -2599,10 +2599,12 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne pr := gqlResult.Data.CreatePullRequest.PullRequest var id int64 - if pr.FullDatabaseID != "" { - id, err = pr.FullDatabaseID.Int64() + var number json.Number + // An unusable optional ID must not discard an already-created PR. + if json.Unmarshal(pr.FullDatabaseID, &number) == nil { + id, err = number.Int64() if err != nil || id < 1 { - return nil, fmt.Errorf("decode cross-repo pull request response: invalid fullDatabaseId %q", pr.FullDatabaseID) + id = 0 } } return &forge.ChangeProposal{ diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 724146927d..a530cba63a 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -1057,27 +1057,31 @@ func TestCreateChangeProposal_Forbidden(t *testing.T) { } func TestCreateCrossRepoChangeProposal_FullWidthID(t *testing.T) { + t.Parallel() for _, tc := range []struct { name, jsonID string want int64 - wantErr bool }{ - {"number", "9007199254740993", 9007199254740993, false}, - {"string", `"9007199254740993"`, 9007199254740993, false}, - {"max int64", `"9223372036854775807"`, 9223372036854775807, false}, - {"null unresolved", "null", 0, false}, - {"missing unresolved", "", 0, false}, - {"overflow", `"9223372036854775808"`, 0, true}, - {"negative", "-1", 0, true}, - {"zero", "0", 0, true}, - {"fractional", "1.5", 0, true}, - {"nonnumeric", `"bad"`, 0, true}, + {"number", "9007199254740993", 9007199254740993}, + {"string", `"9007199254740993"`, 9007199254740993}, + {"max int64", `"9223372036854775807"`, 9223372036854775807}, + {"null unresolved", "null", 0}, + {"missing unresolved", "", 0}, + {"overflow", `"9223372036854775808"`, 0}, + {"negative", "-1", 0}, + {"zero", "0", 0}, + {"fractional", "1.5", 0}, + {"nonnumeric", `"bad"`, 0}, + {"boolean", "true", 0}, + {"object", `{}`, 0}, + {"array", `[]`, 0}, } { t.Run(tc.name, func(t *testing.T) { - calls := 0 + getCalls, calls := 0, 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/"): + getCalls++ json.NewEncoder(w).Encode(map[string]string{"node_id": "NODE_repo"}) case r.Method == http.MethodPost && r.URL.Path == "/graphql": calls++ @@ -1085,20 +1089,20 @@ func TestCreateCrossRepoChangeProposal_FullWidthID(t *testing.T) { if tc.jsonID != "" { id = `"fullDatabaseId":` + tc.jsonID + "," } - fmt.Fprintf(w, `{"data":{"createPullRequest":{"pullRequest":{%s"number":99}}}}`, id) + fmt.Fprintf(w, `{"data":{"createPullRequest":{"pullRequest":{%s"number":99,"title":"title","url":"https://github.com/org/repo/pull/99"}}}}`, id) default: http.NotFound(w, r) } })) defer srv.Close() cp, err := newTestClient(t, srv).CreateCrossRepoChangeProposal(context.Background(), "org", "repo", "org", "fork", "title", "body", "feature", "main") + assert.Equal(t, 2, getCalls) assert.Equal(t, 1, calls) - if tc.wantErr { - assert.Error(t, err) - return - } require.NoError(t, err) assert.Equal(t, tc.want, cp.ID) + assert.Equal(t, 99, cp.Number) + assert.Equal(t, "title", cp.Title) + assert.Equal(t, "https://github.com/org/repo/pull/99", cp.URL) }) } } From 18862ff3a0a657230c58b9aab487a9ff85f54f2d Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 14:54:48 -0500 Subject: [PATCH 12/40] fix(telemetry): retain deployment prefixes in trace identity Signed-off-by: Dharit Shah --- docs/reference/trace-context.md | 24 ++++++++++---- .../telemetry/tracecontext/envelope_test.go | 33 ++++++++++++++++++- internal/telemetry/tracecontext/identity.go | 23 ++++++------- .../telemetry/tracecontext/identity_test.go | 25 ++++++++++++-- 4 files changed, 84 insertions(+), 21 deletions(-) diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index dcde03e0fd..ecdb514868 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -28,12 +28,22 @@ components. | Entity kind | `work_item` (issue), `change_proposal` (PR) | `work_item` (issue), `change_proposal` (MR) | `work_item` (issue; Jira has no change proposal) | | Entity | issue or PR REST `id`; PR GraphQL `fullDatabaseId` (`BigInt`) | issue or MR database `id` (not the IID) | issue `id` | -The instance string is the normalized base URL: lowercase -`scheme://host`, using `http` or `https`, at most 253 UTF-8 bytes, no path or -trailing slash. `NormalizeInstance` builds it (accepting and removing a bare -`/`) and rejects URLs with a longer path, query, fragment, user info, or -missing host. Identity resolution, signing, and parsing require the already -canonical value; they never silently rewrite an authenticated field. +The instance string is the normalized, trusted deployment base URL: lowercase +`scheme://host`, using `http` or `https`, followed by the case-sensitive, +URL-escaped deployment path prefix, with trailing slashes removed. For +example, `https://GitLab.example.com/gitlab/` becomes +`https://gitlab.example.com/gitlab`; it is distinct from both the root +installation and `/GitLab`. Path segments and existing escape spelling are +preserved, never cleaned or decoded into separators. Use the same configured +deployment URL on every launch, rather than an entity or API URL. + +`NormalizeInstance` rejects queries, fragments, user info, missing hosts, +invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes +(including the escaped prefix). Identity resolution, signing, and parsing +require the already canonical value; they never silently rewrite an +authenticated field. Root-instance vectors, wire layout, and size limits +are unchanged; prefixed deployments use the same v1 length-delimited field +and fallback derivation with the full normalized instance bytes. Jira issue reads expose the project ID as `tracker.Issue.ContainerID`; search requests include `project`. Missing or invalid project IDs stay zero @@ -206,7 +216,7 @@ derive a fallback or guess. | `Identity` | The immutable binding tuple | | `Identity.Resolved` | Whether forge-side identity components are present | | `DeriveFallback` | The v1 deterministic fallback context | -| `NormalizeInstance` | Canonical `scheme://host` instance form | +| `NormalizeInstance` | Canonical deployment base URL, including its path prefix | | `Envelope` | A decoded v1 envelope or pending marker | | `Envelope.Sign` | Validate and sign with an Ed25519 private key (host-side only) | | `Envelope.Marshal` | Canonical wire bytes | diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index 37e6cbbd91..0a33c7eff5 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -302,7 +302,8 @@ func TestAdmit_MalformedVerificationKeys(t *testing.T) { func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { for _, instance := range []string{ "not-a-url", "https://GitHub.com", "HTTPS://github.com", "https://github.com/", - "https://github.com/api", "https://github.com?", "https://github.com#", + "https://gitlab.example.com/gitlab/", "https://github.com?", "https://github.com#", + "https://gitlab.example.com/café", "https://gitlab.example.com/%00", "https://gitlab.example.com/%ff", "https://user@github.com", "ftp://github.com", "https://:443", "https://" + strings.Repeat("a", 246), "https://\xff.example", } { @@ -333,6 +334,36 @@ func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { } } +func TestEnvelope_DeploymentPrefixBinding(t *testing.T) { + t.Parallel() + key, keys := goldenKeys(t) + for _, domain := range []Domain{DomainBound, DomainPending} { + raw, _ := signedGolden(t, domain, ProvenanceNone) + instance := "https://gitlab.example.com/gitlab" + // Build the prefixed fixture independently of production validation. + raw = append(append(bytes.Clone(raw[:32]), []byte(instance)...), raw[50:]...) + binary.BigEndian.PutUint16(raw[30:32], uint16(len(instance))) + raw = resign(t, key, raw) + env, err := Parse(raw) + require.NoError(t, err) + assert.Equal(t, instance, env.Instance) + require.NoError(t, env.Sign(key)) + assert.Equal(t, raw, env.Marshal()) + + id := goldenIdentity() + id.Instance = instance + want := OutcomeAdmitted + if domain == DomainPending { + want = OutcomePending + } + assert.Equal(t, want, Admit(id, keys, raw).Outcome) + for _, other := range []string{"https://gitlab.example.com", "https://gitlab.example.com/other", "https://gitlab.example.com/GitLab"} { + id.Instance = other + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonBindingMismatch}, Admit(id, keys, raw)) + } + } +} + // TestAdmit_RetainedKey covers rotation: metadata signed by an older // retained key stays verifiable while the active key signs new metadata. func TestAdmit_RetainedKey(t *testing.T) { diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index eee058acbe..a5867b4d97 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -47,9 +47,9 @@ type Identity struct { // with the signing key pair. It is authenticated in envelopes but // deliberately excluded from fallback derivation, per ADR 0154. Installation [16]byte - // Instance is the normalized forge web base URL: lowercase - // scheme://host with no path and no trailing slash. Use - // NormalizeInstance to build it. + // Instance is the normalized forge web base URL: lowercase scheme://host + // with its escaped, case-sensitive deployment prefix and no trailing slash. + // Use NormalizeInstance to build it from trusted configuration. Instance string // Container is the immutable repository or project database ID. Container int64 @@ -124,10 +124,11 @@ func nonzeroFallback(fb Fallback) Fallback { } // NormalizeInstance canonicalizes a forge web base URL to the D01 instance -// form: lowercase scheme://host with no path, query, fragment, or user -// info. Only http and https are accepted; a bare "/" path is tolerated and -// stripped. All identity and envelope construction must use the normalized -// form so independent launches converge. +// form: lowercase scheme://host with an escaped, case-sensitive deployment +// prefix and no trailing slashes, query, fragment, or user info. Only http +// and https are accepted. Path segments and escape spelling are preserved +// so distinct deployments cannot alias. All identity and envelope construction +// must use the normalized form so independent launches converge. func NormalizeInstance(raw string) (string, error) { if !utf8.ValidString(raw) { return "", errors.New("tracecontext: instance must be valid UTF-8") @@ -140,16 +141,16 @@ func NormalizeInstance(raw string) (string, error) { return "", errors.New("tracecontext: instance URL needs a scheme and host") } if u.User != nil || strings.ContainsAny(raw, "?#") { - return "", errors.New("tracecontext: instance URL must be a bare scheme://host") + return "", errors.New("tracecontext: instance URL must not carry user info, query, or fragment") } - if u.Path != "" && u.Path != "/" { - return "", errors.New("tracecontext: instance URL must not carry a path") + if !utf8.ValidString(u.Path) || strings.ContainsRune(u.Path, '\x00') { + return "", errors.New("tracecontext: instance path must be valid UTF-8 without NUL") } scheme := strings.ToLower(u.Scheme) if scheme != "http" && scheme != "https" { return "", fmt.Errorf("tracecontext: unsupported instance scheme %q", u.Scheme) } - normalized := scheme + "://" + strings.ToLower(u.Host) + normalized := scheme + "://" + strings.ToLower(u.Host) + strings.TrimRight(u.EscapedPath(), "/") if len(normalized) > 253 { return "", errors.New("tracecontext: instance must be at most 253 bytes") } diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index 96866c6e1f..adc29f0875 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -240,7 +240,7 @@ func TestDeriveFallback_IdenticalAcrossProcesses(t *testing.T) { } // TestNormalizeInstance covers the D01 instance form: lowercase -// scheme://host, no path, query, fragment, or user info. +// scheme://host with a deployment prefix, no query, fragment, or user info. func TestNormalizeInstance(t *testing.T) { cases := []struct { name string @@ -254,6 +254,11 @@ func TestNormalizeInstance(t *testing.T) { {"uppercase host", "https://GitHub.com", "https://github.com"}, {"uppercase scheme", "HTTPS://github.com", "https://github.com"}, {"trailing slash", "https://github.com/", "https://github.com"}, + {"gitlab prefix", "https://GitLab.example.com/gitlab/", "https://gitlab.example.com/gitlab"}, + {"nested case-sensitive prefix", "https://gitlab.example.com/Services/GitLab///", "https://gitlab.example.com/Services/GitLab"}, + {"escaped prefix", "https://gitlab.example.com/a%2Fb/", "https://gitlab.example.com/a%2Fb"}, + {"unicode prefix", "https://gitlab.example.com/café/", "https://gitlab.example.com/caf%C3%A9"}, + {"maximum prefix", "https://example.com/" + strings.Repeat("a", 233), "https://example.com/" + strings.Repeat("a", 233)}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -268,7 +273,8 @@ func TestNormalizeInstance_Rejects(t *testing.T) { for _, raw := range []string{ "", "://missing-scheme", - "https://github.com/owner/repo", + "https://github.com/%00", + "https://github.com/%ff", "https://user:passgithub.com", "https://github.com?query=1", "https://github.com#fragment", @@ -277,6 +283,7 @@ func TestNormalizeInstance_Rejects(t *testing.T) { "https://:443", "ftp://github.com", "https://" + strings.Repeat("a", 246), + "https://example.com/" + strings.Repeat("a", 234), "https://\xff.example", } { _, err := NormalizeInstance(raw) @@ -294,6 +301,7 @@ func TestDeriveFallback_FixedVectors(t *testing.T) { {v01Identity(), "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a2", "c9bdb0e38247ebbe2e0f1039250c32d4", "892a346c55356aca"}, {Identity{Instance: "https://gitlab.com", Container: 101, Kind: KindChangeProposal, Entity: 555}, "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001268747470733a2f2f6769746c61622e636f6d000000000000006502000000000000022b", "407b66d9453075850f3ee7ef31d6ff1e", "a39491edef0440ae"}, {Identity{Instance: "https://acme.atlassian.net", Container: 10000, Kind: KindWorkItem, Entity: 10100}, "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001a68747470733a2f2f61636d652e61746c61737369616e2e6e65740000000000002710010000000000002774", "535e9f2c6d8bd8a814edd68dceb60e9a", "7e00bd92068701ac"}, + {Identity{Instance: "https://gitlab.example.com/gitlab", Container: 101, Kind: KindChangeProposal, Entity: 555}, "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631002168747470733a2f2f6769746c61622e6578616d706c652e636f6d2f6769746c6162000000000000006502000000000000022b", "71c6f9ad9a13f7244356f839e29687fa", "8f2d2a176bde1f88"}, } { t.Run(tc.id.Instance, func(t *testing.T) { digest := sha256.Sum256(mustHex(t, tc.preimage)) @@ -371,3 +379,16 @@ func TestDeriveFallback_InstancesDifferByHost(t *testing.T) { require.True(t, ok) assert.False(t, bytes.Equal(fa.TraceID[:], fb.TraceID[:])) } + +func TestDeriveFallback_DeploymentPrefixesStayDistinct(t *testing.T) { + t.Parallel() + seen := map[Fallback]bool{} + for _, prefix := range []string{"", "/gitlab", "/GitLab", "/other/gitlab", "/a%2Fb", "/a/b"} { + id := v01Identity() + id.Instance = "https://gitlab.example.com" + prefix + fb, ok := DeriveFallback(id) + require.True(t, ok, id.Instance) + assert.False(t, seen[fb], "deployment prefixes must not alias: %s", prefix) + seen[fb] = true + } +} From b1f0d1eaa1d8b39667ab86e2e1ba061909b9d73a Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 14:58:09 -0500 Subject: [PATCH 13/40] docs(telemetry): version the trace-context protocol contract Signed-off-by: Dharit Shah --- ...work-item-and-behaviour-scenario-traces.md | 4 + .../infrastructure/distributed-tracing.md | 8 +- docs/normative/trace-context/v1/README.md | 201 +++++++++++++ docs/reference/trace-context.md | 264 +++--------------- internal/telemetry/tracecontext/envelope.go | 2 +- .../telemetry/tracecontext/envelope_test.go | 2 +- internal/telemetry/tracecontext/identity.go | 2 +- 7 files changed, 256 insertions(+), 227 deletions(-) create mode 100644 docs/normative/trace-context/v1/README.md diff --git a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md index 90d969ef1f..066a20414a 100644 --- a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md +++ b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md @@ -21,6 +21,10 @@ Accepted This records the chosen topology; implementation is pending. +The [trace-context v1 specification](../normative/trace-context/v1/README.md) +defines the detailed identity, fallback, signed-envelope, and admission +contract. + ## Context An ADLC flow crosses separately launched agents and CLI commands, forge API diff --git a/docs/guides/infrastructure/distributed-tracing.md b/docs/guides/infrastructure/distributed-tracing.md index b6d6dbf527..a9eadc1876 100644 --- a/docs/guides/infrastructure/distributed-tracing.md +++ b/docs/guides/infrastructure/distributed-tracing.md @@ -664,13 +664,9 @@ GitHub webhooks do not support custom trace headers. Within a single work item, `fullsend.work_item_id` on the root `run` span is the correlation key for filtering related traces in a backend. -Durable work-item continuity across independent launches — signed, -entity-bound context published as metadata on the work item, with a -deterministic fallback derived from immutable entity identity — is a -separate mechanism specified in +For durable work-item continuity, see [ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md) -and documented in the -[Trace Context Reference](../../reference/trace-context.md). +and the [Trace Context Reference](../../reference/trace-context.md). ## Operational behavior diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md new file mode 100644 index 0000000000..2ac9095d4a --- /dev/null +++ b/docs/normative/trace-context/v1/README.md @@ -0,0 +1,201 @@ +# Trace context v1 + +This normative specification defines the immutable identity, deterministic +fallback, signed-envelope encoding, and admission contract adopted by +[ADR 0154](../../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). +See the [Trace Context Reference](../../../reference/trace-context.md) for +Go API guidance and implementation scope. Carrier publication, key +provisioning, and runtime integration are outside this contract. + +## Identity + +Every forge entity is addressed by an immutable five-part tuple. Display +names, URLs, GitHub numbers, GitLab IIDs, and Jira keys are not identity +components. + +| Component | GitHub | GitLab | Jira | +|-----------|--------|--------|------| +| Installation | 128-bit ID provisioned with the signing key pair | same | same | +| Forge instance | web base URL (`https://github.com`, or a GHES host) | web base URL (`https://gitlab.com`, or a self-hosted host) | site base URL | +| Container | repository `id` | project `id` | project `id` | +| Entity kind | `work_item` (issue), `change_proposal` (PR) | `work_item` (issue), `change_proposal` (MR) | `work_item` (issue; Jira has no change proposal) | +| Entity | issue or PR REST `id`; PR GraphQL `fullDatabaseId` (`BigInt`) | issue or MR database `id` (not the IID) | issue `id` | + +The instance string is the normalized, trusted deployment base URL: lowercase +`scheme://host`, using `http` or `https`, followed by the case-sensitive, +URL-escaped deployment path prefix, with trailing slashes removed. For +example, `https://GitLab.example.com/gitlab/` becomes +`https://gitlab.example.com/gitlab`; it is distinct from both the root +installation and `/GitLab`. Path segments and existing escape spelling are +preserved, never cleaned or decoded into separators. Use the same configured +deployment URL on every launch, rather than an entity or API URL. + +`NormalizeInstance` rejects queries, fragments, user info, missing hosts, +invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes +(including the escaped prefix). Identity resolution, signing, and parsing +require the already canonical value; they never silently rewrite an +authenticated field. Root-instance vectors, wire layout, and size limits +are unchanged; prefixed deployments use the same v1 length-delimited field +and fallback derivation with the full normalized instance bytes. + +The installation ID is generated during key provisioning and identifies +one install's key set. It is authenticated inside every envelope and must +match the verifier's configured installation at admission. It is +deliberately **not** part of fallback derivation, so entities keep stable +traces regardless of key state. + +### Rename and move rules + +- Renames (issue titles, repository names, Jira project keys) never + change identity: every component is a database ID. +- Repository transfers on GitHub and GitLab preserve the database ID, so + identity survives a transfer. +- An entity moved between containers (a GitHub issue transfer, a Jira + project move) has a **new binding** — a different container or entity + ID — and therefore a new identity. A previously published envelope + fails the binding check and the moved entity falls back. A move is + never treated as a rename. + +### Fallback derivation (v1) + +When no admissible stored context exists, the entity's context is derived +deterministically: + +- Input: the forge instance, container, kind, and entity — never the + installation. +- SHA-256 over the exact concatenation below. Only strings are + length-prefixed; all integers are big-endian: + `uint16(33) || "fullsend.tracecontext.identity.v1" || uint16(N) || + instance[N] || uint64(container) || byte(kind) || uint64(entity)`. + `N` counts UTF-8 bytes, container/entity are in `[1, 2^63−1]`, and kind + is `0x01` (work item) or `0x02` (change proposal). +- TraceID = the first 16 digest bytes; the anchor SpanID = the next 8. +- An all-zero result (probability 2⁻¹²⁸ for the trace, 2⁻⁶⁴ for the span) + replaces only that ID's final byte with `0x01`, so derived IDs are valid. + +The derivation is pure, so independent launches and concurrent first +events converge on identical nonzero IDs without shared state. The anchor +SpanID is a synthetic parent reference by protocol choice: no exported span +carries the anchor ID, the anchor is never repointed, and operation spans +keep distinct SDK-generated IDs. OpenTelemetry supports custom ID generators +(`WithIDGenerator`); this contract deliberately uses an unexported anchor +rather than creating a real root span with that ID. + +For `https://github.com`, container `274390431`, kind `0x01`, and entity +`2468913570`, the exact input is: + +```text +002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631 +001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a2 +``` + +Concatenate those hex lines before hashing. The TraceID is +`c9bdb0e38247ebbe2e0f1039250c32d4`; the anchor is `892a346c55356aca`. +Additional independent GitLab/Jira vectors and an SDK exporter lifecycle +test are linked from the [implementation reference](../../../reference/trace-context.md). + +## Signed envelope (wire format v1) + +One fixed-layout binary encoding serves both message domains; all +integers are big-endian, and the Ed25519 signature covers every byte from +the magic through the nonce — there are no unsigned fields. + +| Offset | Size | Field | Constraints | +|--------|------|-------|-------------| +| 0 | 4 | Magic `FSTC` | exact bytes | +| 4 | 1 | Version | `0x01`; anything else rejects | +| 5 | 1 | Message domain | `0x01` bound envelope, `0x02` pending marker | +| 6 | 8 | Key ID | first 8 bytes of SHA-256(public key) | +| 14 | 16 | Installation ID | nonzero | +| 30 | 2 | Instance length N | `1 ≤ N ≤ 253` | +| 32 | N | Forge instance | normalized form, UTF-8, no NUL | +| 32+N | 8 | Container ID | `int64 ≥ 1` | +| 40+N | 1 | Entity kind | `0x01` work item, `0x02` change proposal | +| 41+N | 8 | Entity ID | `int64 ≥ 1`; bound envelopes only — pending markers omit these 8 bytes, retaining the kind byte | +| · | 16 | Trace ID | nonzero | +| · | 8 | Parent/anchor Span ID | nonzero | +| · | 1 | Provenance kind | `0x00` none, `0x01` source link, `0x02` scenario | +| · | 0/24/32 | Provenance fields | none; source link = 16B source TraceID + 8B source SpanID; scenario = 16B scenario TraceID + 16B invocation ID | +| · | 16 | Nonce | `crypto/rand`, nonzero, unique per creation intent | +| end−64 | 64 | Ed25519 signature | over bytes `[0, end−64)` | + +The maximum legal size is 439 bytes (bound envelope, scenario provenance, +253-byte instance); carriers hold the envelope as unwrapped standard +base64 (≤ 588 characters, no line breaks). + +Strict parsing rules: + +- The total length must equal the exact structural length for the parsed + domain and provenance kind; trailing bytes reject. +- Duplicate and unknown fields are structurally impossible in the fixed + layout. +- Every enumerated byte and ID must satisfy its constraint; invalid + values reject rather than degrade. +- Unknown versions reject — never a partial parse. +- Identical duplicate carriers are acceptable (idempotent publication); + any differing carriers reject — never first-match. + +### Domains, keys, and nonces + +The domain byte is covered by the signature, so a pending marker cannot +be replayed as a bound envelope and vice versa. A pending marker carries +the creation's intended context and provenance as signed intent, omits +the entity ID (the destination does not exist yet), and grants neither +context, parent, nor source link. The nonce links a pending marker to +the bound envelope published after creation; admission never depends on +having seen the marker. + +The key selector resolves **only** against the verifier's configured +eligible keys (active plus retained). Envelopes never carry public keys +or key locations, and metadata can never select a signer or a remote key +URL. After rotation, metadata signed by an older retained key remains +verifiable while new metadata uses the active key. +Missing or malformed-length verification keys yield `unknown-key` fallback +without context or provenance; they never reach Ed25519 verification. + +### Provenance consistency + +- Source-link provenance (ordinary created work) requires the envelope + TraceID to differ from the source TraceID: the destination keeps its + own trace and the source context is a link, never a parent. +- Scenario provenance (behaviour-test work) requires the envelope + TraceID to equal the scenario TraceID: descendants inherit the + scenario trace with distinct operation spans. + +## Admission + +`Admit(expected Identity, keys, candidates...)` is the pure decision +operation. It takes the trusted expected binding, the configured eligible +verification keys, and bounded candidate carrier bytes, and returns +exactly one outcome: + +- **Admitted**: a verified bound envelope matched every binding + component. The result carries the admitted TraceID, parent SpanID, and + authenticated provenance. +- **Pending**: a verified pending marker matched the expected scope. It + grants nothing; bounded rereads are caller policy. +- **Fallback**: nothing was admissible. The caller uses the + entity-derived fallback. + +Fallback reason codes are redacted diagnostics — `absent`, `malformed`, +`oversized`, `unknown-version`, `unknown-key`, `bad-signature`, +`binding-mismatch`, `conflicting-carrier`, `provenance` — never key +material or raw bytes. A plain W3C `traceparent` is never an envelope. + +The result structurally cannot carry sampling flags, `tracestate`, +baggage, or dispatch permission. Trace admission and dispatch +authorization are independent decisions; a denied actor never dispatches +regardless of admission, and an admitted envelope never authorizes +anything. + +An unresolved identity (missing instance, container, kind, or entity) is +explicit: callers must postpone dispatch with diagnostics rather than +derive a fallback or guess. + +## Compatibility + +The [conformance vectors](../../../reference/trace-context.md#conformance-evidence) +pin the exact signed bytes of one envelope per domain and provenance kind. +Any change to the wire layout, derivation, or key-selector rules is a +compatibility break that requires a new version byte and a reviewed migration +path. Unknown versions must reject cleanly. diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index ecdb514868..6e2ad204d1 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -1,213 +1,42 @@ # Trace Context Reference -Version 1 of the work-item trace-context identity and signed-envelope -protocol from [ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). -This page documents the implemented contract surfaces: the immutable -identity tuple, the deterministic fallback derivation, the v1 wire format, -and the pure admission operation. Carrier publication (hidden body -metadata, Jira properties), key provisioning, and runtime admission wiring -are separate delivery slices; this page marks them where they are not yet -implemented. - -The Go implementation is -[`internal/telemetry/tracecontext`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext). -It is pure: no network I/O, no configuration reads, and it never grants -dispatch permission. - -## Identity - -Every forge entity is addressed by an immutable five-part tuple. Display -names, URLs, GitHub numbers, GitLab IIDs, and Jira keys are not identity -components. - -| Component | GitHub | GitLab | Jira | -|-----------|--------|--------|------| -| Installation | 128-bit ID provisioned with the signing key pair | same | same | -| Forge instance | web base URL (`https://github.com`, or a GHES host) | web base URL (`https://gitlab.com`, or a self-hosted host) | site base URL | -| Container | repository `id` | project `id` | project `id` | -| Entity kind | `work_item` (issue), `change_proposal` (PR) | `work_item` (issue), `change_proposal` (MR) | `work_item` (issue; Jira has no change proposal) | -| Entity | issue or PR REST `id`; PR GraphQL `fullDatabaseId` (`BigInt`) | issue or MR database `id` (not the IID) | issue `id` | - -The instance string is the normalized, trusted deployment base URL: lowercase -`scheme://host`, using `http` or `https`, followed by the case-sensitive, -URL-escaped deployment path prefix, with trailing slashes removed. For -example, `https://GitLab.example.com/gitlab/` becomes -`https://gitlab.example.com/gitlab`; it is distinct from both the root -installation and `/GitLab`. Path segments and existing escape spelling are -preserved, never cleaned or decoded into separators. Use the same configured -deployment URL on every launch, rather than an entity or API URL. - -`NormalizeInstance` rejects queries, fragments, user info, missing hosts, -invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes -(including the escaped prefix). Identity resolution, signing, and parsing -require the already canonical value; they never silently rewrite an -authenticated field. Root-instance vectors, wire layout, and size limits -are unchanged; prefixed deployments use the same v1 length-delimited field -and fallback derivation with the full normalized instance bytes. - -Jira issue reads expose the project ID as `tracker.Issue.ContainerID`; search -requests include `project`. Missing or invalid project IDs stay zero -(unresolved). Jira's create response contains no project ID, so a subsequent -trusted read must resolve the container before trace admission. Forge-backed -tracker reads resolve their repository separately through `forge.Client`. -GitHub cross-repository PR creation decodes `fullDatabaseId` directly into -an `int64`, accepting numeric or string JSON without floating-point rounding; -the deprecated 32-bit GraphQL `databaseId` is not used. Missing or invalid -IDs leave identity unresolved without discarding a successful PR creation. - -The installation ID is generated during key provisioning and identifies -one install's key set. It is authenticated inside every envelope and must -match the verifier's configured installation at admission. It is -deliberately **not** part of fallback derivation, so entities keep stable -traces regardless of key state. - -### Rename and move rules - -- Renames (issue titles, repository names, Jira project keys) never - change identity: every component is a database ID. -- Repository transfers on GitHub and GitLab preserve the database ID, so - identity survives a transfer. -- An entity moved between containers (a GitHub issue transfer, a Jira - project move) has a **new binding** — a different container or entity - ID — and therefore a new identity. A previously published envelope - fails the binding check and the moved entity falls back. A move is - never treated as a rename. - -### Fallback derivation (v1) - -When no admissible stored context exists, the entity's context is derived -deterministically: - -- Input: the forge instance, container, kind, and entity — never the - installation. -- SHA-256 over the exact concatenation below. Only strings are - length-prefixed; all integers are big-endian: - `uint16(33) || "fullsend.tracecontext.identity.v1" || uint16(N) || - instance[N] || uint64(container) || byte(kind) || uint64(entity)`. - `N` counts UTF-8 bytes, container/entity are in `[1, 2^63−1]`, and kind - is `0x01` (work item) or `0x02` (change proposal). -- TraceID = the first 16 digest bytes; the anchor SpanID = the next 8. -- An all-zero result (probability 2⁻¹²⁸ for the trace, 2⁻⁶⁴ for the span) - replaces only that ID's final byte with `0x01`, so derived IDs are valid. - -The derivation is pure, so independent launches and concurrent first -events converge on identical nonzero IDs without shared state. The anchor -SpanID is a synthetic parent reference by protocol choice: no exported span -carries the anchor ID, the anchor is never repointed, and operation spans -keep distinct SDK-generated IDs. OpenTelemetry supports custom ID generators -(`WithIDGenerator`); this contract deliberately uses an unexported anchor -rather than creating a real root span with that ID. - -For `https://github.com`, container `274390431`, kind `0x01`, and entity -`2468913570`, the exact input is: - -```text -002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631 -001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a2 -``` - -Concatenate those hex lines before hashing. The TraceID is -`c9bdb0e38247ebbe2e0f1039250c32d4`; the anchor is `892a346c55356aca`. -Additional independent GitLab/Jira vectors and an SDK exporter lifecycle -test are in `identity_test.go`; runtime integration remains a later slice. - -## Signed envelope (wire format v1) - -One fixed-layout binary encoding serves both message domains; all -integers are big-endian, and the Ed25519 signature covers every byte from -the magic through the nonce — there are no unsigned fields. - -| Offset | Size | Field | Constraints | -|--------|------|-------|-------------| -| 0 | 4 | Magic `FSTC` | exact bytes | -| 4 | 1 | Version | `0x01`; anything else rejects | -| 5 | 1 | Message domain | `0x01` bound envelope, `0x02` pending marker | -| 6 | 8 | Key ID | first 8 bytes of SHA-256(public key) | -| 14 | 16 | Installation ID | nonzero | -| 30 | 2 | Instance length N | `1 ≤ N ≤ 253` | -| 32 | N | Forge instance | normalized form, UTF-8, no NUL | -| 32+N | 8 | Container ID | `int64 ≥ 1` | -| 40+N | 1 | Entity kind | `0x01` work item, `0x02` change proposal | -| 41+N | 8 | Entity ID | `int64 ≥ 1`; bound envelopes only — pending markers omit these 8 bytes, retaining the kind byte | -| · | 16 | Trace ID | nonzero | -| · | 8 | Parent/anchor Span ID | nonzero | -| · | 1 | Provenance kind | `0x00` none, `0x01` source link, `0x02` scenario | -| · | 0/24/32 | Provenance fields | none; source link = 16B source TraceID + 8B source SpanID; scenario = 16B scenario TraceID + 16B invocation ID | -| · | 16 | Nonce | `crypto/rand`, nonzero, unique per creation intent | -| end−64 | 64 | Ed25519 signature | over bytes `[0, end−64)` | - -The maximum legal size is 439 bytes (bound envelope, scenario provenance, -253-byte instance); carriers hold the envelope as unwrapped standard -base64 (≤ 588 characters, no line breaks). - -Strict parsing rules: - -- The total length must equal the exact structural length for the parsed - domain and provenance kind; trailing bytes reject. -- Duplicate and unknown fields are structurally impossible in the fixed - layout. -- Every enumerated byte and ID must satisfy its constraint; invalid - values reject rather than degrade. -- Unknown versions reject — never a partial parse. -- Identical duplicate carriers are acceptable (idempotent publication); - any differing carriers reject — never first-match. - -### Domains, keys, and nonces - -The domain byte is covered by the signature, so a pending marker cannot -be replayed as a bound envelope and vice versa. A pending marker carries -the creation's intended context and provenance as signed intent, omits -the entity ID (the destination does not exist yet), and grants neither -context, parent, nor source link. The nonce links a pending marker to -the bound envelope published after creation; admission never depends on -having seen the marker. - -The key selector resolves **only** against the verifier's configured -eligible keys (active plus retained). Envelopes never carry public keys -or key locations, and metadata can never select a signer or a remote key -URL. After rotation, metadata signed by an older retained key remains -verifiable while new metadata uses the active key. -Missing or malformed-length verification keys yield `unknown-key` fallback -without context or provenance; they never reach Ed25519 verification. - -### Provenance consistency - -- Source-link provenance (ordinary created work) requires the envelope - TraceID to differ from the source TraceID: the destination keeps its - own trace and the source context is a link, never a parent. -- Scenario provenance (behaviour-test work) requires the envelope - TraceID to equal the scenario TraceID: descendants inherit the - scenario trace with distinct operation spans. - -## Admission - -`Admit(expected Identity, keys, candidates...)` is the pure decision -operation. It takes the trusted expected binding, the configured eligible -verification keys, and bounded candidate carrier bytes, and returns -exactly one outcome: - -- **Admitted**: a verified bound envelope matched every binding - component. The result carries the admitted TraceID, parent SpanID, and - authenticated provenance. -- **Pending**: a verified pending marker matched the expected scope. It - grants nothing; bounded rereads are caller policy. -- **Fallback**: nothing was admissible. The caller uses the - entity-derived fallback. - -Fallback reason codes are redacted diagnostics — `absent`, `malformed`, -`oversized`, `unknown-version`, `unknown-key`, `bad-signature`, -`binding-mismatch`, `conflicting-carrier`, `provenance` — never key -material or raw bytes. A plain W3C `traceparent` is never an envelope. - -The result structurally cannot carry sampling flags, `tracestate`, -baggage, or dispatch permission. Trace admission and dispatch -authorization are independent decisions; a denied actor never dispatches -regardless of admission, and an admitted envelope never authorizes -anything. - -An unresolved identity (missing instance, container, kind, or entity) is -explicit: callers must postpone dispatch with diagnostics rather than -derive a fallback or guess. +The [trace-context v1 specification](../normative/trace-context/v1/README.md) +defines the identity, fallback, wire format, admission, and compatibility +contract for [ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). +This page covers the Go API and adapter integration. + +## Implementation scope + +At implementation revision +[`18862ff3a0a657230c58b9aab487a9ff85f54f2d`](https://github.com/fullsend-ai/fullsend/tree/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext), +[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext/identity.go) +implements identity resolution and fallback derivation; +[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext/envelope.go) +implements signing, strict parsing, and admission. The package performs no +network I/O or configuration reads and never grants dispatch permission. +Carrier publication, key provisioning, production creation activation, +runtime admission wiring, and scenario collection remain later delivery +slices. + +The package must stay importable from public behaviour-test code: it must not +depend on `internal/cli`, `internal/repos`, `internal/layers`, or the nested +mintcore module. + +## Adapter integration + +[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/tracker/jira_client.go) +exposes the project ID as `tracker.Issue.ContainerID`; Jira +[search requests](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/forge/jira/client.go) +include `project`. Missing or invalid project IDs stay zero (unresolved). +Jira's create response contains no project ID, so a subsequent trusted read +must resolve the container before trace admission. Forge-backed tracker +callers must resolve their repository separately through `forge.Client`. + +[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/forge/github/github.go) +decodes GitHub's `fullDatabaseId` into an `int64`, accepting numeric or string +JSON without floating-point rounding; it does not use the deprecated 32-bit +GraphQL `databaseId`. Missing or invalid IDs leave identity unresolved without +discarding a successful PR creation. ## Go API @@ -226,15 +55,14 @@ derive a fallback or guess. | `Admit` | The pure admission decision | | `Result`, `Outcome` | Admission outcome and admitted IDs | -The package must stay importable from public behaviour-test code: it -must not depend on `internal/cli`, `internal/repos`, `internal/layers`, -or the nested mintcore module. +## Conformance evidence -## Compatibility +- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext/identity_test.go) + contains independent fallback vectors, deployment-prefix separation checks, + cross-process convergence, and SDK exporter lifecycle assertions. +- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext/envelope_test.go) + contains independent signed-wire vectors for both domains and all provenance + kinds, binding checks, malformed-input cases, and parser fuzzing. -The golden test vectors in -[`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/envelope_test.go) -pin the exact signed bytes of one envelope per domain and provenance -kind. Any change to the wire layout, derivation, or key-selector rules is -a compatibility break that requires a new version byte and a reviewed -migration path. Unknown versions already reject cleanly. +These foundation tests do not establish production runtime integration or +live-adapter trace continuity. diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index 60917af7fd..56ee9eedd6 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -67,7 +67,7 @@ type Provenance struct { // Envelope is a decoded v1 envelope or pending marker. The wire layout, // exact sizes, and strict limits are frozen in -// docs/reference/trace-context.md; Marshal is its only legal encoder. +// docs/normative/trace-context/v1/README.md; Marshal is its only legal encoder. type Envelope struct { Domain Domain KeyID [8]byte diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index 0a33c7eff5..db38b42632 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -118,7 +118,7 @@ func signedGolden(t *testing.T, domain Domain, prov ProvenanceKind) ([]byte, map } // specLayout mirrors the frozen v1 wire layout from -// docs/reference/trace-context.md so tests locate fields independently of +// docs/normative/trace-context/v1/README.md so tests locate fields independently of // the implementation, pinning the format from the spec side. type specLayout struct { instance, container, kind, entity int diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index a5867b4d97..0634fd2c55 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -40,7 +40,7 @@ func (k EntityKind) Valid() bool { // Identity is the immutable binding of a forge entity (ADR 0154, D01): // installation, forge instance, container, entity kind, and entity // database ID. Display names, URLs, GitHub numbers, GitLab IIDs, and Jira -// keys are not identity components; docs/reference/trace-context.md holds +// keys are not identity components; docs/normative/trace-context/v1/README.md holds // the per-forge field mapping. type Identity struct { // Installation is the 128-bit installation identifier provisioned From f16c077d3d59c87fefbd90b0fca886c9e41d2f8b Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 15:49:43 -0500 Subject: [PATCH 14/40] fix(telemetry): canonicalize instance ports and IDN hosts Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 8 ++++++++ .../telemetry/tracecontext/envelope_test.go | 17 +++++++++++++++++ internal/telemetry/tracecontext/identity.go | 15 +++++++++++++-- .../telemetry/tracecontext/identity_test.go | 10 ++++++++++ 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 2ac9095d4a..0a64a41230 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -30,6 +30,14 @@ installation and `/GitLab`. Path segments and existing escape spelling are preserved, never cleaned or decoded into separators. Use the same configured deployment URL on every launch, rather than an entity or API URL. +Remove the scheme's default port (`443` for HTTPS, `80` for HTTP), including +zero-padded spellings; preserve nondefault ports. Hosts must be ASCII: use +the punycode form for internationalized domain names, and reject Unicode +host spellings instead of converting them. For example, +`https://GitHub.com:443/` becomes `https://github.com`, and +`https://XN--BCHER-KVA.example` becomes `https://xn--bcher-kva.example`. +Bracketed IPv6 hosts follow the same case and default-port rules. + `NormalizeInstance` rejects queries, fragments, user info, missing hosts, invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes (including the escaped prefix). Identity resolution, signing, and parsing diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index db38b42632..8687251ad7 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -301,6 +301,8 @@ func TestAdmit_MalformedVerificationKeys(t *testing.T) { func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { for _, instance := range []string{ + "https://github.com:443", "https://github.com:0443", "http://github.com:80", + "https://bücher.example", "not-a-url", "https://GitHub.com", "HTTPS://github.com", "https://github.com/", "https://gitlab.example.com/gitlab/", "https://github.com?", "https://github.com#", "https://gitlab.example.com/café", "https://gitlab.example.com/%00", "https://gitlab.example.com/%ff", @@ -334,6 +336,21 @@ func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { } } +func TestAdmit_NormalizedDefaultPort(t *testing.T) { + t.Parallel() + raw, keys := signedGolden(t, DomainBound, ProvenanceNone) + id := goldenIdentity() + wantFallback, ok := DeriveFallback(id) + require.True(t, ok) + var err error + id.Instance, err = NormalizeInstance("https://GitHub.com:443/") + require.NoError(t, err) + fb, ok := DeriveFallback(id) + require.True(t, ok) + assert.Equal(t, wantFallback, fb) + assert.Equal(t, OutcomeAdmitted, Admit(id, keys, raw).Outcome) +} + func TestEnvelope_DeploymentPrefixBinding(t *testing.T) { t.Parallel() key, keys := goldenKeys(t) diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index 0634fd2c55..6e51389971 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -126,7 +126,8 @@ func nonzeroFallback(fb Fallback) Fallback { // NormalizeInstance canonicalizes a forge web base URL to the D01 instance // form: lowercase scheme://host with an escaped, case-sensitive deployment // prefix and no trailing slashes, query, fragment, or user info. Only http -// and https are accepted. Path segments and escape spelling are preserved +// and https are accepted, default ports are removed, and hosts must be ASCII +// (punycode for IDNs). Path segments and escape spelling are preserved // so distinct deployments cannot alias. All identity and envelope construction // must use the normalized form so independent launches converge. func NormalizeInstance(raw string) (string, error) { @@ -150,7 +151,17 @@ func NormalizeInstance(raw string) (string, error) { if scheme != "http" && scheme != "https" { return "", fmt.Errorf("tracecontext: unsupported instance scheme %q", u.Scheme) } - normalized := scheme + "://" + strings.ToLower(u.Host) + strings.TrimRight(u.EscapedPath(), "/") + for _, r := range u.Host { + if r >= utf8.RuneSelf { + return "", errors.New("tracecontext: instance host must be ASCII; use punycode for IDNs") + } + } + host := strings.ToLower(u.Host) + port := strings.TrimLeft(u.Port(), "0") + if scheme == "https" && port == "443" || scheme == "http" && port == "80" { + host = strings.TrimSuffix(host, ":"+u.Port()) + } + normalized := scheme + "://" + host + strings.TrimRight(u.EscapedPath(), "/") if len(normalized) > 253 { return "", errors.New("tracecontext: instance must be at most 253 bytes") } diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index adc29f0875..da28886f8a 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -253,6 +253,14 @@ func TestNormalizeInstance(t *testing.T) { {"GHES host", "https://ghe.example.com", "https://ghe.example.com"}, {"uppercase host", "https://GitHub.com", "https://github.com"}, {"uppercase scheme", "HTTPS://github.com", "https://github.com"}, + {"https default port", "https://GitHub.com:443/", "https://github.com"}, + {"https padded default port", "https://github.com:0443", "https://github.com"}, + {"http default port", "http://example.com:80/gitlab/", "http://example.com/gitlab"}, + {"nondefault port", "https://example.com:8443/gitlab", "https://example.com:8443/gitlab"}, + {"http nondefault port", "http://example.com:443", "http://example.com:443"}, + {"ipv6 default port", "https://[2001:DB8::1]:443/", "https://[2001:db8::1]"}, + {"ipv6 nondefault port", "https://[2001:DB8::1]:8443", "https://[2001:db8::1]:8443"}, + {"IDN punycode", "https://XN--BCHER-KVA.example", "https://xn--bcher-kva.example"}, {"trailing slash", "https://github.com/", "https://github.com"}, {"gitlab prefix", "https://GitLab.example.com/gitlab/", "https://gitlab.example.com/gitlab"}, {"nested case-sensitive prefix", "https://gitlab.example.com/Services/GitLab///", "https://gitlab.example.com/Services/GitLab"}, @@ -285,6 +293,8 @@ func TestNormalizeInstance_Rejects(t *testing.T) { "https://" + strings.Repeat("a", 246), "https://example.com/" + strings.Repeat("a", 234), "https://\xff.example", + "https://bücher.example", + "https://b%C3%BCcher.example", } { _, err := NormalizeInstance(raw) assert.Error(t, err, "input %q must be rejected", raw) From fd6ebf496f241c7831fe2c8aa9c81730a1d144a4 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 15:50:33 -0500 Subject: [PATCH 15/40] fix(telemetry): make zero-value admission results fall back Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 2 ++ internal/telemetry/tracecontext/envelope.go | 9 +++++---- internal/telemetry/tracecontext/envelope_test.go | 9 +++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 0a64a41230..fa36899292 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -185,6 +185,8 @@ exactly one outcome: - **Fallback**: nothing was admissible. The caller uses the entity-derived fallback. +The zero-value result selects fallback and grants no context or provenance. + Fallback reason codes are redacted diagnostics — `absent`, `malformed`, `oversized`, `unknown-version`, `unknown-key`, `bad-signature`, `binding-mismatch`, `conflicting-carrier`, `provenance` — never key diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index 56ee9eedd6..653763678f 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -396,16 +396,16 @@ func DecodeCarrier(s string) ([]byte, error) { type Outcome int const ( + // OutcomeFallback means no carrier was admissible; the caller uses + // the deterministic entity-derived fallback. It is the zero value. + OutcomeFallback Outcome = iota // OutcomeAdmitted means a verified bound envelope matched the // expected binding; the admitted IDs are available. - OutcomeAdmitted Outcome = iota + OutcomeAdmitted // OutcomePending means a verified pending marker matched the expected // scope. It grants neither context nor links; bounded rereads are // caller policy. OutcomePending - // OutcomeFallback means no carrier was admissible; the caller uses - // the deterministic entity-derived fallback. - OutcomeFallback ) // Reason codes for non-admitted outcomes. They are redacted diagnostics: @@ -426,6 +426,7 @@ const ( // Result is the admission outcome. It carries admitted IDs and // authenticated provenance only — never sampling flags, tracestate, // baggage, or dispatch permission (FR-007, FR-008). +// Its zero value selects fallback and carries no admitted context or links. type Result struct { Outcome Outcome // Reason is a redacted reason code when the outcome is not admitted. diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index 8687251ad7..f6541cc34f 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -268,6 +268,15 @@ func TestCrossBindingReplay(t *testing.T) { } } +func TestResult_ZeroValueFallsBack(t *testing.T) { + t.Parallel() + var result Result + assert.Equal(t, OutcomeFallback, result.Outcome) + assert.False(t, result.TraceID.IsValid()) + assert.False(t, result.ParentSpanID.IsValid()) + assert.Equal(t, Provenance{}, result.Provenance) +} + func TestAdmit_Absent(t *testing.T) { _, keys := goldenKeys(t) res := Admit(goldenIdentity(), keys) From d8706166b859eaebea10fdf036ece539b6b6a4a2 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 15:52:26 -0500 Subject: [PATCH 16/40] docs(telemetry): distinguish GitHub pull and issue identities Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 13 ++++++++++- docs/reference/trace-context.md | 28 +++++++++++++++-------- internal/forge/forge.go | 4 ++++ 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index fa36899292..9eeaff768c 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -19,7 +19,18 @@ components. | Forge instance | web base URL (`https://github.com`, or a GHES host) | web base URL (`https://gitlab.com`, or a self-hosted host) | site base URL | | Container | repository `id` | project `id` | project `id` | | Entity kind | `work_item` (issue), `change_proposal` (PR) | `work_item` (issue), `change_proposal` (MR) | `work_item` (issue; Jira has no change proposal) | -| Entity | issue or PR REST `id`; PR GraphQL `fullDatabaseId` (`BigInt`) | issue or MR database `id` (not the IID) | issue `id` | +| Entity | `work_item`: issue REST `id`; `change_proposal`: pull-request REST `id` = GraphQL `fullDatabaseId` (`BigInt`), never the issue-space ID | issue or MR database `id` (not the IID) | issue `id` | + +A GitHub PR has both a pull-request ID and a different issue-space ID. +The `change_proposal` identity must use the pull-request ID from +`/repos/{owner}/{repo}/pulls/{number}`, also exposed as GraphQL +`fullDatabaseId`. A PR's `/issues/{number}` response and the `issue` object +in an `issue_comment` event carry its issue-space ID, which must never be +used for `change_proposal` identity. For a PR event carrying only that issue +object, resolve the pull-request ID through a trusted forge-adapter +`/pulls/{number}` read before declaring the identity resolved. Until that +read succeeds, keep the identity unresolved rather than substituting the +issue-space ID or display number. The instance string is the normalized, trusted deployment base URL: lowercase `scheme://host`, using `http` or `https`, followed by the case-sensitive, diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 6e2ad204d1..8777611c88 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -8,10 +8,10 @@ This page covers the Go API and adapter integration. ## Implementation scope At implementation revision -[`18862ff3a0a657230c58b9aab487a9ff85f54f2d`](https://github.com/fullsend-ai/fullsend/tree/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext), -[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext/identity.go) +[`fd6ebf496f241c7831fe2c8aa9c81730a1d144a4`](https://github.com/fullsend-ai/fullsend/tree/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext), +[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext/identity.go) implements identity resolution and fallback derivation; -[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext/envelope.go) +[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext/envelope.go) implements signing, strict parsing, and admission. The package performs no network I/O or configuration reads and never grants dispatch permission. Carrier publication, key provisioning, production creation activation, @@ -24,20 +24,27 @@ mintcore module. ## Adapter integration -[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/tracker/jira_client.go) +[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/tracker/jira_client.go) exposes the project ID as `tracker.Issue.ContainerID`; Jira -[search requests](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/forge/jira/client.go) +[search requests](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/forge/jira/client.go) include `project`. Missing or invalid project IDs stay zero (unresolved). Jira's create response contains no project ID, so a subsequent trusted read must resolve the container before trace admission. Forge-backed tracker callers must resolve their repository separately through `forge.Client`. -[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/forge/github/github.go) +[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/forge/github/github.go) decodes GitHub's `fullDatabaseId` into an `int64`, accepting numeric or string JSON without floating-point rounding; it does not use the deprecated 32-bit GraphQL `databaseId`. Missing or invalid IDs leave identity unresolved without discarding a successful PR creation. +GitHub `GetIssue` preserves the issue-space ID even for a PR number. Before +constructing a `KindChangeProposal` identity for an `issue_comment` event on +a PR, the runtime integration must resolve the pull-request ID through a +trusted forge read, following the [identity contract](../normative/trace-context/v1/README.md#identity). +`GetPullRequestInfo` currently returns branch/repository context without that +database ID; its result alone cannot resolve trace identity. + ## Go API | Symbol | Purpose | @@ -53,16 +60,17 @@ discarding a successful PR creation. | `DecodeCarrier` | Strict base64 carrier decode | | `KeyID` | The 8-byte key selector for a public key | | `Admit` | The pure admission decision | -| `Result`, `Outcome` | Admission outcome and admitted IDs | +| `Result`, `Outcome` | Admission outcome and admitted IDs; the zero value selects fallback | ## Conformance evidence -- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext/identity_test.go) +- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext/identity_test.go) contains independent fallback vectors, deployment-prefix separation checks, cross-process convergence, and SDK exporter lifecycle assertions. -- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/18862ff3a0a657230c58b9aab487a9ff85f54f2d/internal/telemetry/tracecontext/envelope_test.go) +- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext/envelope_test.go) contains independent signed-wire vectors for both domains and all provenance - kinds, binding checks, malformed-input cases, and parser fuzzing. + kinds, binding checks, default-port convergence, zero-value fallback, + malformed-input cases, and parser fuzzing. These foundation tests do not establish production runtime integration or live-adapter trace continuity. diff --git a/internal/forge/forge.go b/internal/forge/forge.go index bd6d40370e..3967ef0e2b 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -503,6 +503,7 @@ type ChangeProposal struct { // ID is the immutable forge database ID of the change proposal: // GitHub's REST pull-request id or GitLab's database merge-request // id (not the IID). It is 0 when the adapter did not capture one. + // A GitHub PR's issue-space id is not its change-proposal identity. ID int64 Head string // HeadRepo identifies the repository the head branch lives in, as @@ -586,6 +587,9 @@ type Issue struct { // id or GitLab's database id (not the IID). It is 0 when the adapter // did not capture one; trace admission treats that as unresolved // identity rather than guessing. + // For a GitHub PR number, GetIssue returns the issue-space id, not the + // pull-request id. Never use it as KindChangeProposal identity; resolve + // the pull-request id through a trusted pull-request read instead. ID int64 Title string Body string From 59e9cce6098e0633b0a767feb5b77c0ad32054f1 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 16:20:31 -0500 Subject: [PATCH 17/40] fix(github): retry delayed workflow job visibility Retry jobs-page 404 responses within the existing bounded retry budget. Preserve persistent errors and include repository, run, and page context. Cover recovery, permission failures, cancellation, and later-page retries. Signed-off-by: Dharit Shah --- internal/forge/github/github.go | 10 ++- internal/forge/github/github_test.go | 99 ++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 2 deletions(-) diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index c22055adbe..bd7c446c6a 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -4434,8 +4434,14 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string } path := fmt.Sprintf("/repos/%s/%s/actions/runs/%d/jobs?per_page=%d&page=%d", url.PathEscape(owner), url.PathEscape(repo), runID, perPage, page) - if err := c.getCachedJSON(ctx, path, &result); err != nil { - return nil, fmt.Errorf("list workflow run jobs page %d: %w", page, err) + label := fmt.Sprintf("list workflow run jobs for %s/%s run %d page %d", owner, repo, runID, page) + // A listed run's jobs can briefly return 404; retry that page without losing earlier jobs. + if err := c.retryOnRepoRaceIf(ctx, label, func(apiErr *APIError) bool { + return apiErr.StatusCode == http.StatusNotFound + }, func() error { + return c.getCachedJSON(ctx, path, &result) + }); err != nil { + return nil, fmt.Errorf("%s: %w", label, err) } if len(result.Jobs) == 0 { return jobs, nil diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index a530cba63a..f38aba4653 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -5114,6 +5114,73 @@ func TestListWorkflowRunJobs_APIError(t *testing.T) { require.Error(t, err) } +func TestListWorkflowRunJobs_NotFound(t *testing.T) { + for _, tt := range []struct { + name string + status int + failures int + wantCalls int + wantError bool + }{ + {name: "jobs become visible", status: http.StatusNotFound, failures: 2, wantCalls: 3}, + {name: "missing run stays an error", status: http.StatusNotFound, failures: 5, wantCalls: 5, wantError: true}, + {name: "permission failure is not retried", status: http.StatusForbidden, failures: 5, wantCalls: 1, wantError: true}, + } { + t.Run(tt.name, func(t *testing.T) { + calls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, "/repos/org/repo/actions/runs/42/jobs", r.URL.Path) + assert.Equal(t, "1", r.URL.Query().Get("page")) + if calls <= tt.failures { + w.WriteHeader(tt.status) + return + } + _, _ = io.WriteString(w, `{"jobs":[{"id":1,"name":"dispatch / Fix","status":"completed","conclusion":"success"}]}`) + })) + defer srv.Close() + + jobs, err := newTestClient(t, srv).ListWorkflowRunJobs(context.Background(), "org", "repo", 42) + assert.Equal(t, tt.wantCalls, calls) + if tt.wantError { + require.Error(t, err) + assert.Nil(t, jobs) + assert.Contains(t, err.Error(), "org/repo") + assert.Contains(t, err.Error(), "run 42") + assert.Contains(t, err.Error(), "page 1") + var apiErr *APIError + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, tt.status, apiErr.StatusCode) + assert.Equal(t, tt.status == http.StatusNotFound, forge.IsNotFound(err)) + return + } + require.NoError(t, err) + require.Len(t, jobs, 1) + assert.Equal(t, "dispatch / Fix", jobs[0].Name) + }) + } +} + +func TestListWorkflowRunJobs_NotFoundRetryCancelled(t *testing.T) { + calls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(http.StatusNotFound) + })) + defer srv.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + client := newTestClient(t, srv).WithAfterFunc(func(time.Duration) <-chan time.Time { + cancel() + return make(chan time.Time) + }) + + jobs, err := client.ListWorkflowRunJobs(ctx, "org", "repo", 42) + require.ErrorIs(t, err, context.Canceled) + assert.Nil(t, jobs) + assert.Equal(t, 1, calls) +} + // TestListWorkflowRunJobs_PaginatesBeyondFirstPage is a regression test // (#7996 review): ListWorkflowRunJobs previously issued a single // per_page=100 request with no pagination, so a run with more than 100 @@ -5163,6 +5230,38 @@ func TestListWorkflowRunJobs_PaginatesBeyondFirstPage(t *testing.T) { assert.Len(t, pageRequests, 2, "pagination must stop once a short page is seen") } +func TestListWorkflowRunJobs_RetriesOnlyMissingPage(t *testing.T) { + var pages []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + page := r.URL.Query().Get("page") + pages = append(pages, page) + assert.Equal(t, "/repos/org/repo/actions/runs/42/jobs", r.URL.Path) + if page == "1" { + jobs := make([]forge.WorkflowJob, 100) + for i := range jobs { + jobs[i].ID = i + 1 + } + _ = json.NewEncoder(w).Encode(map[string]any{"jobs": jobs}) + return + } + assert.Equal(t, "2", page) + if len(pages) == 2 { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = io.WriteString(w, `{"jobs":[{"id":101,"name":"dispatch / Fix"}]}`) + })) + defer srv.Close() + + jobs, err := newTestClient(t, srv).ListWorkflowRunJobs(context.Background(), "org", "repo", 42) + require.NoError(t, err) + assert.Equal(t, []string{"1", "2", "2"}, pages) + require.Len(t, jobs, 101) + assert.Equal(t, 1, jobs[0].ID) + assert.Equal(t, 100, jobs[99].ID) + assert.Equal(t, 101, jobs[100].ID) +} + // TestListWorkflowRunJobs_PaginationExceeded guards the maxPages safety // valve: if every page is full, pagination must stop with an error instead // of looping indefinitely. From 24ed3e1f020bb08367f99a64f885701921ee76a5 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 16:20:48 -0500 Subject: [PATCH 18/40] ci(e2e): inspect every eligible run in dispatch assertions Use the existing since-bounded workflow pagination for exact dispatch counts and negative assertions. Ten newer runs must not hide an earlier dispatch. Reproduce both false-zero cases before applying the fix. Signed-off-by: Dharit Shah --- .../drivers/ci/githubactions/githubactions.go | 12 ++------ .../ci/githubactions/githubactions_test.go | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 897e51e2e3..83f6d443b8 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1577,15 +1577,11 @@ func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent // harnessRoundPollOnce's guard; cancelled static jobs added #7996 review; // success/failure built-in matches added #7996 review, second pass). func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, agent string, after time.Time) (count, pending int, err error) { - allRuns, err := d.Client.ListWorkflowRuns(ctx, owner, repo, harnessWorkflowFile) + allRuns, err := d.listHarnessRunsAfterPaginated(ctx, owner, repo, after) if err != nil { return 0, 0, err } for _, r := range allRuns { - runTime, parseErr := time.Parse(time.RFC3339, r.CreatedAt) - if parseErr != nil || runTime.Before(after) { - continue - } jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { return 0, 0, err @@ -1749,15 +1745,11 @@ func isConcurrencySuperseded(conclusion string) bool { // than artifacts so that sibling runs for other agents are not mistaken // for evidence. func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, agent string, after time.Time) error { - allRuns, err := d.Client.ListWorkflowRuns(ctx, owner, repo, harnessWorkflowFile) + allRuns, err := d.listHarnessRunsAfterPaginated(ctx, owner, repo, after) if err != nil { return err } for _, r := range allRuns { - runTime, parseErr := time.Parse(time.RFC3339, r.CreatedAt) - if parseErr != nil || runTime.Before(after) { - continue - } jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { return err diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go index 73af730598..ceaffb37d4 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go @@ -541,6 +541,36 @@ func (c *truncatingListWorkflowRunsClient) ListWorkflowRuns(_ context.Context, _ return append([]forge.WorkflowRun(nil), c.truncated...), nil } +func TestHarnessDispatchAssertions_IncludeRunsBeyondFirstPage(t *testing.T) { + t.Parallel() + + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + fake := forge.NewFakeClient() + var runs []forge.WorkflowRun + for id := range 11 { + runs = append(runs, forge.WorkflowRun{ + ID: id + 1, Status: "completed", Conclusion: "success", + CreatedAt: after.Add(time.Duration(id+1) * time.Minute).Format(time.RFC3339), + }) + } + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": runs} + fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{ + 1: {{ID: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}}, + } + d := newTestDriver(&truncatingListWorkflowRunsClient{FakeClient: fake, truncated: runs[1:]}) + + t.Run("exact count", func(t *testing.T) { + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + assert.Equal(t, 1, count, "newer unrelated runs must not hide a dispatch") + }) + t.Run("negative assertion", func(t *testing.T) { + err := d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after) + require.Error(t, err) + assert.Contains(t, err.Error(), "workflow run 1") + }) +} + // TestWaitForHarnessAgentRound_SelectsEarliestEligibleRunBeyondTruncatedPage // is a regression test (#7996 review): listHarnessRunsAfter's shared // listing (used by WaitForHarnessAgent's latest-eligible-run selection) From 1322cdf7d595673d7db4a812a9d74402aa90c849 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 16:43:07 -0500 Subject: [PATCH 19/40] fix(telemetry): canonicalize empty and padded instance ports Remove empty ports and normalize zero-padded nondefault ports while preserving an explicit port zero. Pin fallback and admission convergence, reject noncanonical authenticated fields, and document the v1 port rule. Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 12 +++--- .../telemetry/tracecontext/envelope_test.go | 41 +++++++++++++------ internal/telemetry/tracecontext/identity.go | 21 ++++++---- .../telemetry/tracecontext/identity_test.go | 7 ++++ 4 files changed, 56 insertions(+), 25 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 9eeaff768c..a7fa9882e7 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -41,13 +41,15 @@ installation and `/GitLab`. Path segments and existing escape spelling are preserved, never cleaned or decoded into separators. Use the same configured deployment URL on every launch, rather than an entity or API URL. -Remove the scheme's default port (`443` for HTTPS, `80` for HTTP), including -zero-padded spellings; preserve nondefault ports. Hosts must be ASCII: use -the punycode form for internationalized domain names, and reject Unicode -host spellings instead of converting them. For example, +Remove an empty port and the scheme's default port (`443` for HTTPS, `80` for +HTTP). Strip leading zeros from other ports, preserving an explicit zero as +`:0` rather than treating it as the default. For example, `https://host:` +becomes `https://host`, and `https://host:08443` becomes `https://host:8443`. +Hosts must be ASCII: use the punycode form for internationalized domain +names, and reject Unicode host spellings instead of converting them. For example, `https://GitHub.com:443/` becomes `https://github.com`, and `https://XN--BCHER-KVA.example` becomes `https://xn--bcher-kva.example`. -Bracketed IPv6 hosts follow the same case and default-port rules. +Bracketed IPv6 hosts follow the same case and port rules. `NormalizeInstance` rejects queries, fragments, user info, missing hosts, invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index f6541cc34f..2a81b23eec 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -311,6 +311,8 @@ func TestAdmit_MalformedVerificationKeys(t *testing.T) { func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { for _, instance := range []string{ "https://github.com:443", "https://github.com:0443", "http://github.com:80", + "https://github.com:", "https://[::1]:", "https://github.com:08443", + "https://[::1]:08443", "https://github.com:000", "https://bücher.example", "not-a-url", "https://GitHub.com", "HTTPS://github.com", "https://github.com/", "https://gitlab.example.com/gitlab/", "https://github.com?", "https://github.com#", @@ -345,19 +347,34 @@ func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { } } -func TestAdmit_NormalizedDefaultPort(t *testing.T) { +func TestAdmit_NormalizedPorts(t *testing.T) { t.Parallel() - raw, keys := signedGolden(t, DomainBound, ProvenanceNone) - id := goldenIdentity() - wantFallback, ok := DeriveFallback(id) - require.True(t, ok) - var err error - id.Instance, err = NormalizeInstance("https://GitHub.com:443/") - require.NoError(t, err) - fb, ok := DeriveFallback(id) - require.True(t, ok) - assert.Equal(t, wantFallback, fb) - assert.Equal(t, OutcomeAdmitted, Admit(id, keys, raw).Outcome) + key, keys := goldenKeys(t) + for _, tc := range []struct{ raw, canonical string }{ + {"https://GitHub.com:443/", "https://github.com"}, + {"https://github.com:", "https://github.com"}, + {"https://[::1]:", "https://[::1]"}, + {"https://github.com:08443", "https://github.com:8443"}, + {"https://[::1]:08443", "https://[::1]:8443"}, + {"https://github.com:000", "https://github.com:0"}, + } { + t.Run(tc.raw, func(t *testing.T) { + env := goldenEnvelope(DomainBound, ProvenanceNone) + env.Instance = tc.canonical + require.NoError(t, env.Sign(key)) + id := goldenIdentity() + id.Instance = tc.canonical + wantFallback, ok := DeriveFallback(id) + require.True(t, ok) + var err error + id.Instance, err = NormalizeInstance(tc.raw) + require.NoError(t, err) + fb, ok := DeriveFallback(id) + require.True(t, ok) + assert.Equal(t, wantFallback, fb) + assert.Equal(t, OutcomeAdmitted, Admit(id, keys, env.Marshal()).Outcome) + }) + } } func TestEnvelope_DeploymentPrefixBinding(t *testing.T) { diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index 6e51389971..ddc25c1079 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -126,10 +126,11 @@ func nonzeroFallback(fb Fallback) Fallback { // NormalizeInstance canonicalizes a forge web base URL to the D01 instance // form: lowercase scheme://host with an escaped, case-sensitive deployment // prefix and no trailing slashes, query, fragment, or user info. Only http -// and https are accepted, default ports are removed, and hosts must be ASCII -// (punycode for IDNs). Path segments and escape spelling are preserved -// so distinct deployments cannot alias. All identity and envelope construction -// must use the normalized form so independent launches converge. +// and https are accepted, empty/default ports are removed, other ports lose +// leading zeros, and hosts must be ASCII (punycode for IDNs). Path segments and +// escape spelling are preserved so distinct deployments cannot alias. All +// identity and envelope construction must use the normalized form so independent +// launches converge. func NormalizeInstance(raw string) (string, error) { if !utf8.ValidString(raw) { return "", errors.New("tracecontext: instance must be valid UTF-8") @@ -156,10 +157,14 @@ func NormalizeInstance(raw string) (string, error) { return "", errors.New("tracecontext: instance host must be ASCII; use punycode for IDNs") } } - host := strings.ToLower(u.Host) - port := strings.TrimLeft(u.Port(), "0") - if scheme == "https" && port == "443" || scheme == "http" && port == "80" { - host = strings.TrimSuffix(host, ":"+u.Port()) + rawPort := u.Port() + host := strings.TrimSuffix(strings.ToLower(u.Host), ":"+rawPort) + port := strings.TrimLeft(rawPort, "0") + if port == "" && rawPort != "" { + port = "0" + } + if port != "" && !(scheme == "https" && port == "443" || scheme == "http" && port == "80") { + host += ":" + port } normalized := scheme + "://" + host + strings.TrimRight(u.EscapedPath(), "/") if len(normalized) > 253 { diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index da28886f8a..bc9472565a 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -256,10 +256,17 @@ func TestNormalizeInstance(t *testing.T) { {"https default port", "https://GitHub.com:443/", "https://github.com"}, {"https padded default port", "https://github.com:0443", "https://github.com"}, {"http default port", "http://example.com:80/gitlab/", "http://example.com/gitlab"}, + {"https empty port", "https://GitHub.com:/", "https://github.com"}, + {"http empty port", "http://example.com:/gitlab/", "http://example.com/gitlab"}, {"nondefault port", "https://example.com:8443/gitlab", "https://example.com:8443/gitlab"}, + {"padded nondefault port", "https://example.com:08443/gitlab", "https://example.com:8443/gitlab"}, {"http nondefault port", "http://example.com:443", "http://example.com:443"}, + {"zero port", "https://example.com:0", "https://example.com:0"}, + {"padded zero port", "https://example.com:000", "https://example.com:0"}, {"ipv6 default port", "https://[2001:DB8::1]:443/", "https://[2001:db8::1]"}, + {"ipv6 empty port", "https://[::1]:/gitlab", "https://[::1]/gitlab"}, {"ipv6 nondefault port", "https://[2001:DB8::1]:8443", "https://[2001:db8::1]:8443"}, + {"ipv6 padded nondefault port", "https://[2001:DB8::1]:08443", "https://[2001:db8::1]:8443"}, {"IDN punycode", "https://XN--BCHER-KVA.example", "https://xn--bcher-kva.example"}, {"trailing slash", "https://github.com/", "https://github.com"}, {"gitlab prefix", "https://GitLab.example.com/gitlab/", "https://gitlab.example.com/gitlab"}, From 7498683f0f5a364058f538870f34659c332b82ac Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 16:44:57 -0500 Subject: [PATCH 20/40] docs(telemetry): refresh port normalization evidence Signed-off-by: Dharit Shah --- docs/reference/trace-context.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 8777611c88..7b3b0221de 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -8,10 +8,10 @@ This page covers the Go API and adapter integration. ## Implementation scope At implementation revision -[`fd6ebf496f241c7831fe2c8aa9c81730a1d144a4`](https://github.com/fullsend-ai/fullsend/tree/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext), -[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext/identity.go) +[`1322cdf7d595673d7db4a812a9d74402aa90c849`](https://github.com/fullsend-ai/fullsend/tree/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext), +[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext/identity.go) implements identity resolution and fallback derivation; -[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext/envelope.go) +[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext/envelope.go) implements signing, strict parsing, and admission. The package performs no network I/O or configuration reads and never grants dispatch permission. Carrier publication, key provisioning, production creation activation, @@ -24,15 +24,15 @@ mintcore module. ## Adapter integration -[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/tracker/jira_client.go) +[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/tracker/jira_client.go) exposes the project ID as `tracker.Issue.ContainerID`; Jira -[search requests](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/forge/jira/client.go) +[search requests](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/forge/jira/client.go) include `project`. Missing or invalid project IDs stay zero (unresolved). Jira's create response contains no project ID, so a subsequent trusted read must resolve the container before trace admission. Forge-backed tracker callers must resolve their repository separately through `forge.Client`. -[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/forge/github/github.go) +[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/forge/github/github.go) decodes GitHub's `fullDatabaseId` into an `int64`, accepting numeric or string JSON without floating-point rounding; it does not use the deprecated 32-bit GraphQL `databaseId`. Missing or invalid IDs leave identity unresolved without @@ -64,12 +64,12 @@ database ID; its result alone cannot resolve trace identity. ## Conformance evidence -- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext/identity_test.go) +- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext/identity_test.go) contains independent fallback vectors, deployment-prefix separation checks, cross-process convergence, and SDK exporter lifecycle assertions. -- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/fd6ebf496f241c7831fe2c8aa9c81730a1d144a4/internal/telemetry/tracecontext/envelope_test.go) +- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext/envelope_test.go) contains independent signed-wire vectors for both domains and all provenance - kinds, binding checks, default-port convergence, zero-value fallback, + kinds, binding checks, empty/default/padded-port convergence, zero-value fallback, malformed-input cases, and parser fuzzing. These foundation tests do not establish production runtime integration or From 98467f211860f1d3e5206cc647ff5807eb30078a Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 09:11:40 -0500 Subject: [PATCH 21/40] fix(github): return workflow jobs errors without speculative retries Signed-off-by: Dharit Shah --- internal/forge/github/github.go | 7 +-- internal/forge/github/github_test.go | 74 +++++++++++++--------------- 2 files changed, 36 insertions(+), 45 deletions(-) diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index bd7c446c6a..50640504ff 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -4435,12 +4435,7 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string path := fmt.Sprintf("/repos/%s/%s/actions/runs/%d/jobs?per_page=%d&page=%d", url.PathEscape(owner), url.PathEscape(repo), runID, perPage, page) label := fmt.Sprintf("list workflow run jobs for %s/%s run %d page %d", owner, repo, runID, page) - // A listed run's jobs can briefly return 404; retry that page without losing earlier jobs. - if err := c.retryOnRepoRaceIf(ctx, label, func(apiErr *APIError) bool { - return apiErr.StatusCode == http.StatusNotFound - }, func() error { - return c.getCachedJSON(ctx, path, &result) - }); err != nil { + if err := c.getCachedJSON(ctx, path, &result); err != nil { return nil, fmt.Errorf("%s: %w", label, err) } if len(result.Jobs) == 0 { diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index f38aba4653..a87c244e01 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -5116,15 +5116,13 @@ func TestListWorkflowRunJobs_APIError(t *testing.T) { func TestListWorkflowRunJobs_NotFound(t *testing.T) { for _, tt := range []struct { - name string - status int - failures int - wantCalls int - wantError bool + name string + status int + failures int }{ - {name: "jobs become visible", status: http.StatusNotFound, failures: 2, wantCalls: 3}, - {name: "missing run stays an error", status: http.StatusNotFound, failures: 5, wantCalls: 5, wantError: true}, - {name: "permission failure is not retried", status: http.StatusForbidden, failures: 5, wantCalls: 1, wantError: true}, + {name: "404 is not presumed transient", status: http.StatusNotFound, failures: 1}, + {name: "persistent 404 fails immediately", status: http.StatusNotFound, failures: 5}, + {name: "permission failure is not retried", status: http.StatusForbidden, failures: 5}, } { t.Run(tt.name, func(t *testing.T) { calls := 0 @@ -5140,28 +5138,30 @@ func TestListWorkflowRunJobs_NotFound(t *testing.T) { })) defer srv.Close() - jobs, err := newTestClient(t, srv).ListWorkflowRunJobs(context.Background(), "org", "repo", 42) - assert.Equal(t, tt.wantCalls, calls) - if tt.wantError { - require.Error(t, err) - assert.Nil(t, jobs) - assert.Contains(t, err.Error(), "org/repo") - assert.Contains(t, err.Error(), "run 42") - assert.Contains(t, err.Error(), "page 1") - var apiErr *APIError - require.ErrorAs(t, err, &apiErr) - assert.Equal(t, tt.status, apiErr.StatusCode) - assert.Equal(t, tt.status == http.StatusNotFound, forge.IsNotFound(err)) - return - } - require.NoError(t, err) - require.Len(t, jobs, 1) - assert.Equal(t, "dispatch / Fix", jobs[0].Name) + waits := 0 + client := newTestClient(t, srv).WithAfterFunc(func(time.Duration) <-chan time.Time { + waits++ + ch := make(chan time.Time, 1) + ch <- time.Now() + return ch + }) + jobs, err := client.ListWorkflowRunJobs(context.Background(), "org", "repo", 42) + assert.Equal(t, 1, calls) + assert.Zero(t, waits, "jobs errors must not add retry delays") + require.Error(t, err) + assert.Nil(t, jobs) + assert.Contains(t, err.Error(), "org/repo") + assert.Contains(t, err.Error(), "run 42") + assert.Contains(t, err.Error(), "page 1") + var apiErr *APIError + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, tt.status, apiErr.StatusCode) + assert.Equal(t, tt.status == http.StatusNotFound, forge.IsNotFound(err)) }) } } -func TestListWorkflowRunJobs_NotFoundRetryCancelled(t *testing.T) { +func TestListWorkflowRunJobs_CancelledContext(t *testing.T) { calls := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { calls++ @@ -5169,16 +5169,13 @@ func TestListWorkflowRunJobs_NotFoundRetryCancelled(t *testing.T) { })) defer srv.Close() ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - client := newTestClient(t, srv).WithAfterFunc(func(time.Duration) <-chan time.Time { - cancel() - return make(chan time.Time) - }) + cancel() + client := newTestClient(t, srv) jobs, err := client.ListWorkflowRunJobs(ctx, "org", "repo", 42) require.ErrorIs(t, err, context.Canceled) assert.Nil(t, jobs) - assert.Equal(t, 1, calls) + assert.Zero(t, calls) } // TestListWorkflowRunJobs_PaginatesBeyondFirstPage is a regression test @@ -5230,7 +5227,7 @@ func TestListWorkflowRunJobs_PaginatesBeyondFirstPage(t *testing.T) { assert.Len(t, pageRequests, 2, "pagination must stop once a short page is seen") } -func TestListWorkflowRunJobs_RetriesOnlyMissingPage(t *testing.T) { +func TestListWorkflowRunJobs_MissingPageFailsWithoutPartialResults(t *testing.T) { var pages []string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { page := r.URL.Query().Get("page") @@ -5254,12 +5251,11 @@ func TestListWorkflowRunJobs_RetriesOnlyMissingPage(t *testing.T) { defer srv.Close() jobs, err := newTestClient(t, srv).ListWorkflowRunJobs(context.Background(), "org", "repo", 42) - require.NoError(t, err) - assert.Equal(t, []string{"1", "2", "2"}, pages) - require.Len(t, jobs, 101) - assert.Equal(t, 1, jobs[0].ID) - assert.Equal(t, 100, jobs[99].ID) - assert.Equal(t, 101, jobs[100].ID) + require.Error(t, err) + assert.True(t, forge.IsNotFound(err)) + assert.Contains(t, err.Error(), "org/repo run 42 page 2") + assert.Equal(t, []string{"1", "2"}, pages) + assert.Nil(t, jobs, "an incomplete listing must not look like absence of an agent") } // TestListWorkflowRunJobs_PaginationExceeded guards the maxPages safety From 21a58b31da765bc07a1ca3477502ea1d800e3687 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 09:18:17 -0500 Subject: [PATCH 22/40] ci(e2e): reuse completed workflow attempts during dispatch counts Signed-off-by: Dharit Shah --- docs/contributing/forge-abstraction.md | 7 + internal/forge/forge.go | 2 + internal/forge/github/github.go | 12 ++ .../forge/github/workflow_attempt_test.go | 59 ++++++ .../ci/githubactions/dispatch_reads_test.go | 181 ++++++++++++++++++ .../drivers/ci/githubactions/githubactions.go | 37 +++- .../ci/githubactions/githubactions_test.go | 2 +- 7 files changed, 291 insertions(+), 9 deletions(-) create mode 100644 internal/forge/github/workflow_attempt_test.go create mode 100644 pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go diff --git a/docs/contributing/forge-abstraction.md b/docs/contributing/forge-abstraction.md index 380dcea2fa..6f0cdb581e 100644 --- a/docs/contributing/forge-abstraction.md +++ b/docs/contributing/forge-abstraction.md @@ -14,6 +14,13 @@ All git forge operations (GitHub API calls, PR comments, issue creation, workflo **FakeClient coverage:** Every exported `FakeClient` method must have an entry in `fakeClientCalls` in [`internal/forge/fake_test.go`](../../internal/forge/fake_test.go). `TestFakeClient_ErrorInjection` uses that table to assert each method returns its injected error, `TestFakeClient_ThreadSafety` runs it concurrently under `-race`, and `TestFakeClient_CoversAllMethods` fails when an entry is missing or stale. Fake methods must return copies, never slices, maps, or pointers into the fake's own storage: callers read results without holding the fake's lock. Likewise, store copies of caller-supplied slices and maps that a fake method later changes in place: callers keep their own reference. +**Workflow attempts:** `WorkflowRun.RunAttempt` and `WorkflowJob.RunAttempt` +identify executions when a forge reuses a run ID for reruns. Zero means the +attempt is unavailable. The GitHub Actions dispatch-count assertion reuses +completed job listings only within that assertion, for unchanged run metadata +and completed jobs whose known attempt matches the run. Unknown attempts, +empty listings, and unfinished jobs are read again on subsequent polls. + **When reviewing PRs:** Flag any direct `exec.Command("gh", ...)`, raw GitHub API calls, or other forge-specific operations outside `internal/forge/github/` as a medium-severity or higher finding. This is an architectural violation, not a style preference. **Composite action (`action.yml`):** The forge abstraction extends to `action.yml` bash scripts. New GitHub API operations in action steps should be implemented as `fullsend` CLI subcommands (under `internal/cli/`) that use `forge.Client`, not as inline `gh api` calls. Existing `gh api` calls in `action.yml` that predate this rule are grandfathered but should be migrated when touched. diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 3967ef0e2b..07e16f6e87 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -533,6 +533,7 @@ type PullRequestInfo struct { // WorkflowRun represents a CI/CD workflow execution. type WorkflowRun struct { ID int + RunAttempt int // Attempt number for a rerunnable execution; zero when unavailable. Name string Event string // GitHub trigger event, e.g. "issues", "issue_comment" Status string // "queued", "in_progress", "completed" @@ -544,6 +545,7 @@ type WorkflowRun struct { // WorkflowJob represents a job within a workflow run. type WorkflowJob struct { ID int + RunAttempt int // Execution attempt containing this job; zero when unavailable. Name string Status string // "queued", "in_progress", "completed" Conclusion string // "success", "failure", "cancelled", etc. diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 50640504ff..f776382cf8 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -3208,6 +3208,7 @@ func (c *LiveClient) GetLatestWorkflowRun(ctx context.Context, owner, repo, work var result struct { WorkflowRuns []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -3227,6 +3228,7 @@ func (c *LiveClient) GetLatestWorkflowRun(ctx context.Context, owner, repo, work run := result.WorkflowRuns[0] return &forge.WorkflowRun{ ID: run.ID, + RunAttempt: run.RunAttempt, Name: run.Name, Event: run.Event, Status: run.Status, @@ -3245,6 +3247,7 @@ func (c *LiveClient) GetWorkflowRun(ctx context.Context, owner, repo string, run var run struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -3258,6 +3261,7 @@ func (c *LiveClient) GetWorkflowRun(ctx context.Context, owner, repo string, run return &forge.WorkflowRun{ ID: run.ID, + RunAttempt: run.RunAttempt, Name: run.Name, Event: run.Event, Status: run.Status, @@ -4286,6 +4290,7 @@ func (c *LiveClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow var result struct { WorkflowRuns []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4301,6 +4306,7 @@ func (c *LiveClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow for i, r := range result.WorkflowRuns { runs[i] = forge.WorkflowRun{ ID: r.ID, + RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4329,6 +4335,7 @@ func (c *LiveClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, wor var result struct { WorkflowRuns []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4353,6 +4360,7 @@ func (c *LiveClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, wor } all = append(all, forge.WorkflowRun{ ID: r.ID, + RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4379,6 +4387,7 @@ func (c *LiveClient) ListRecentWorkflowRuns(ctx context.Context, owner, repo str var result struct { WorkflowRuns []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4394,6 +4403,7 @@ func (c *LiveClient) ListRecentWorkflowRuns(ctx context.Context, owner, repo str for i, r := range result.WorkflowRuns { runs[i] = forge.WorkflowRun{ ID: r.ID, + RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4427,6 +4437,7 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string var result struct { Jobs []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Status string `json:"status"` Conclusion string `json:"conclusion"` @@ -4444,6 +4455,7 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string for _, j := range result.Jobs { jobs = append(jobs, forge.WorkflowJob{ ID: j.ID, + RunAttempt: j.RunAttempt, Name: j.Name, Status: j.Status, Conclusion: j.Conclusion, diff --git a/internal/forge/github/workflow_attempt_test.go b/internal/forge/github/workflow_attempt_test.go new file mode 100644 index 0000000000..dd62a804d3 --- /dev/null +++ b/internal/forge/github/workflow_attempt_test.go @@ -0,0 +1,59 @@ +package github + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestWorkflowReaders_RunAttempt(t *testing.T) { + const run = `{"id":42,"run_attempt":2,"status":"completed","created_at":"2026-01-01T00:00:00Z"}` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/org/repo/actions/runs/42": + fmt.Fprint(w, run) + case "/repos/org/repo/actions/runs/42/jobs": + fmt.Fprintf(w, `{"jobs":[%s]}`, run) + default: + fmt.Fprintf(w, `{"workflow_runs":[%s]}`, run) + } + })) + defer srv.Close() + c := newTestClient(t, srv) + ctx := context.Background() + for name, read := range map[string]func() ([]forge.WorkflowRun, error){ + "latest": func() ([]forge.WorkflowRun, error) { + r, err := c.GetLatestWorkflowRun(ctx, "org", "repo", "fullsend.yaml") + require.NoError(t, err) + return []forge.WorkflowRun{*r}, nil + }, + "by ID": func() ([]forge.WorkflowRun, error) { + r, err := c.GetWorkflowRun(ctx, "org", "repo", 42) + require.NoError(t, err) + return []forge.WorkflowRun{*r}, nil + }, + "workflow": func() ([]forge.WorkflowRun, error) { return c.ListWorkflowRuns(ctx, "org", "repo", "fullsend.yaml") }, + "since": func() ([]forge.WorkflowRun, error) { + return c.ListWorkflowRunsSince(ctx, "org", "repo", "fullsend.yaml", time.Time{}) + }, + "recent": func() ([]forge.WorkflowRun, error) { return c.ListRecentWorkflowRuns(ctx, "org", "repo", 10) }, + } { + t.Run(name, func(t *testing.T) { + runs, err := read() + require.NoError(t, err) + require.Len(t, runs, 1) + assert.Equal(t, 2, runs[0].RunAttempt) + }) + } + jobs, err := c.ListWorkflowRunJobs(ctx, "org", "repo", 42) + require.NoError(t, err) + require.Len(t, jobs, 1) + assert.Equal(t, 2, jobs[0].RunAttempt) +} diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go new file mode 100644 index 0000000000..fc9b233676 --- /dev/null +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -0,0 +1,181 @@ +package githubactions + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// dispatchReadsClient measures requests while two runs settle over six polls. +type dispatchReadsClient struct { + *forge.FakeClient + polls int + jobReads map[int]int +} + +func (c *dispatchReadsClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, workflow string, after time.Time) ([]forge.WorkflowRun, error) { + c.polls++ + runs, err := c.FakeClient.ListWorkflowRunsSince(ctx, owner, repo, workflow, after) + for i := range runs { + if runs[i].ID > 30 && c.polls >= 6 { + runs[i].Status = "completed" + } + } + return runs, err +} + +func (c *dispatchReadsClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow string) ([]forge.WorkflowRun, error) { + runs, err := c.ListWorkflowRunsSince(ctx, owner, repo, workflow, time.Time{}) + if len(runs) > 10 { + runs = runs[:10] + } + return runs, err +} + +func (c *dispatchReadsClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string, runID int) ([]forge.WorkflowJob, error) { + c.jobReads[runID]++ + return c.FakeClient.ListWorkflowRunJobs(ctx, owner, repo, runID) +} + +func newDispatchReadsClient(after time.Time) *dispatchReadsClient { + fake := forge.NewFakeClient() + var runs []forge.WorkflowRun + jobs := make(map[int][]forge.WorkflowJob) + for id := 32; id > 0; id-- { + run := forge.WorkflowRun{ID: id, RunAttempt: 1, Status: "completed", Conclusion: "success", CreatedAt: after.Add(time.Duration(id) * time.Second).Format(time.RFC3339)} + switch { + case id > 30: + run.Status = "in_progress" + case id > 10: + run.Conclusion = "skipped" + } + runs = append(runs, run) + jobs[id] = []forge.WorkflowJob{{ID: id, RunAttempt: 1, Name: "dispatch / Route", Status: "completed", Conclusion: "success"}} + } + // The target dispatch is older than the ten newest runs. + jobs[1] = []forge.WorkflowJob{{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}} + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": runs} + fake.WorkflowRunJobs = jobs + return &dispatchReadsClient{FakeClient: fake, jobReads: make(map[int]int)} +} + +func TestHarnessDispatchAssertions_RequestCounts(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + t.Run("count across six polls", func(t *testing.T) { + client := newDispatchReadsClient(after) + d := &Driver{Client: client, afterFunc: instantAfter} + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + var total int + for _, calls := range client.jobReads { + total += calls + } + t.Logf("list calls=%d jobs calls=%d unique jobs URLs=%d count=%d", client.polls, total, len(client.jobReads), count) + assert.Equal(t, 1, count, "the older dispatch must still be counted") + assert.Equal(t, 6, client.polls) + assert.Equal(t, 22, total, "ten completed runs once, two active runs on six polls") + assert.Equal(t, 12, len(client.jobReads), "skipped workflows need no jobs lookup") + }) + t.Run("negative assertion", func(t *testing.T) { + client := newDispatchReadsClient(after) + d := &Driver{Client: client} + require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "absent", after)) + t.Logf("list calls=%d jobs calls=%d", client.polls, len(client.jobReads)) + assert.Len(t, client.jobReads, 12) + for _, calls := range client.jobReads { + assert.Equal(t, 1, calls) + } + }) +} + +func TestHarnessDispatchAssertions_SkippedRunNeedsNoJobs(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + fake := forge.NewFakeClient() + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { + {ID: 1, Status: "completed", Conclusion: "skipped", CreatedAt: after.Format(time.RFC3339)}, + }} + fake.Errors["ListWorkflowRunJobs"] = errors.New("jobs must not be requested for a skipped workflow") + d := &Driver{Client: fake} + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + assert.Zero(t, count) + require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) +} + +func TestHarnessDispatchAssertions_RelevantJobsErrorsRemainFatal(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, run := range []forge.WorkflowRun{ + {Status: "completed", Conclusion: "success"}, + {Status: "completed", Conclusion: "failure"}, + {Status: "completed", Conclusion: "cancelled"}, + {Status: "in_progress", Conclusion: "skipped"}, + {}, + } { + t.Run(run.Status+"/"+run.Conclusion, func(t *testing.T) { + fake := forge.NewFakeClient() + run.ID, run.CreatedAt = 1, after.Format(time.RFC3339) + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": {run}} + lookupErr := errors.New("jobs lookup failed") + fake.Errors["ListWorkflowRunJobs"] = lookupErr + d := &Driver{Client: fake} + _, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.ErrorIs(t, err, lookupErr) + require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), lookupErr) + }) + } +} + +func TestCountHarnessDispatches_CompletedJobCache(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, name := range []string{"rerun", "unknown run attempt", "unknown job attempt", "mismatched job attempt", "unfinished job", "empty jobs", "assertion local", "changed conclusion"} { + t.Run(name, func(t *testing.T) { + client := newDispatchReadsClient(after) + run := &client.WorkflowRunsList["org/repo/fullsend.yaml"][31] + job := &client.WorkflowRunJobs[1][0] + switch name { + case "unknown run attempt": + run.RunAttempt = 0 + case "unknown job attempt": + job.RunAttempt = 0 + case "mismatched job attempt": + job.RunAttempt = 2 + case "unfinished job": + job.Status = "queued" + case "empty jobs": + client.WorkflowRunJobs[1] = nil + } + d := &Driver{Client: client, afterFunc: func(time.Duration) <-chan time.Time { + if client.polls == 1 { + switch name { + case "rerun": + run.RunAttempt = 2 + job.RunAttempt = 2 + case "changed conclusion": + run.Conclusion = "cancelled" + } + client.WorkflowRunJobs[1] = []forge.WorkflowJob{{ID: 100, RunAttempt: run.RunAttempt, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "cancelled"}} + } + return instantAfter(0) + }} + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + if name == "assertion local" { + assert.Equal(t, 1, count, "the completed attempt is reused within the first assertion") + assert.Equal(t, 1, client.jobReads[1]) + count, err = d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + } + assert.Zero(t, count, "a changed or uncertified job listing must be fetched again") + assert.GreaterOrEqual(t, client.jobReads[1], 2) + }) + } +} diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 83f6d443b8..5b348e7e08 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1538,23 +1538,24 @@ func (d *Driver) failedHarnessPollOnce(ctx context.Context, remaining time.Durat // classified by its final conclusion instead of being counted while its // cancellation is still in progress. func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent string, after time.Time) (int, error) { - deadline := time.Now().Add(dispatchWait) + deadline := d.now().Add(dispatchWait) + completedJobs := make(map[forge.WorkflowRun][]forge.WorkflowJob) for { - count, pending, err := d.settleHarnessDispatchCount(ctx, owner, repo, agent, after) + count, pending, err := d.settleHarnessDispatchCount(ctx, owner, repo, agent, after, completedJobs) if err != nil { return 0, err } if pending == 0 { return count, nil } - if time.Now().After(deadline) { + if d.now().After(deadline) { return 0, fmt.Errorf("harness %q dispatch count did not settle: %d run(s) still pending after %s", agent, pending, dispatchWait) } select { case <-ctx.Done(): return 0, ctx.Err() - case <-time.After(countSettlePoll): + case <-d.timerAfter(countSettlePoll): } } } @@ -1576,15 +1577,32 @@ func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent // computing the matrix (#7957 review, third pass — mirrors // harnessRoundPollOnce's guard; cancelled static jobs added #7996 review; // success/failure built-in matches added #7996 review, second pass). -func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, agent string, after time.Time) (count, pending int, err error) { +func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, agent string, after time.Time, completedJobs map[forge.WorkflowRun][]forge.WorkflowJob) (count, pending int, err error) { allRuns, err := d.listHarnessRunsAfterPaginated(ctx, owner, repo, after) if err != nil { return 0, 0, err } for _, r := range allRuns { - jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) - if err != nil { - return 0, 0, err + if r.Status == "completed" && r.Conclusion == "skipped" { + continue + } + jobs, cached := completedJobs[r] + if !cached { + jobs, err = d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) + if err != nil { + return 0, 0, err + } + // Reruns reuse IDs; only reuse completed jobs from the same known attempt. + cacheable := r.Status == "completed" && r.RunAttempt > 0 && len(jobs) > 0 + for _, job := range jobs { + if job.Status != "completed" || job.RunAttempt != r.RunAttempt { + cacheable = false + break + } + } + if cacheable && completedJobs != nil { + completedJobs[r] = jobs + } } hasJob, job := matchAgentJob(jobs, agent) switch { @@ -1750,6 +1768,9 @@ func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, return err } for _, r := range allRuns { + if r.Status == "completed" && r.Conclusion == "skipped" { + continue + } jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { return err diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go index ceaffb37d4..92a1d6c1aa 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go @@ -2520,7 +2520,7 @@ func TestSettleHarnessDispatchCount_SuccessfulBuiltinMatrixUnresolvedPending(t * } d := &Driver{Client: fake} - count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "triage", after) + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "triage", after, nil) require.NoError(t, err) assert.Equal(t, 0, count, "a successful built-in match must not be counted while the custom matrix remains unresolved") assert.Equal(t, 1, pending, "the run must be classified as pending until the real matrix job appears") From 354f5a70b6917684f91f1e153fb8f998cb7ca875 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 09:43:04 -0500 Subject: [PATCH 23/40] ci(e2e): cache only decisive completed dispatch matches Signed-off-by: Dharit Shah --- docs/contributing/forge-abstraction.md | 7 ++-- .../ci/githubactions/dispatch_reads_test.go | 35 +++++++++++++++++-- .../drivers/ci/githubactions/githubactions.go | 8 +++-- 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/docs/contributing/forge-abstraction.md b/docs/contributing/forge-abstraction.md index 6f0cdb581e..308540e7a1 100644 --- a/docs/contributing/forge-abstraction.md +++ b/docs/contributing/forge-abstraction.md @@ -18,8 +18,11 @@ All git forge operations (GitHub API calls, PR comments, issue creation, workflo identify executions when a forge reuses a run ID for reruns. Zero means the attempt is unavailable. The GitHub Actions dispatch-count assertion reuses completed job listings only within that assertion, for unchanged run metadata -and completed jobs whose known attempt matches the run. Unknown attempts, -empty listings, and unfinished jobs are read again on subsequent polls. +and completed jobs whose known attempt matches the run. Reuse also requires +a matching agent job with a nonempty, non-skipped, non-cancelled conclusion: +that job already establishes a counted dispatch. Listings without that +evidence, unknown attempts, and unfinished jobs are read again on subsequent +polls because an absent job may become visible later. **When reviewing PRs:** Flag any direct `exec.Command("gh", ...)`, raw GitHub API calls, or other forge-specific operations outside `internal/forge/github/` as a medium-severity or higher finding. This is an architectural violation, not a style preference. diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index fc9b233676..ea17f96912 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -79,7 +79,7 @@ func TestHarnessDispatchAssertions_RequestCounts(t *testing.T) { t.Logf("list calls=%d jobs calls=%d unique jobs URLs=%d count=%d", client.polls, total, len(client.jobReads), count) assert.Equal(t, 1, count, "the older dispatch must still be counted") assert.Equal(t, 6, client.polls) - assert.Equal(t, 22, total, "ten completed runs once, two active runs on six polls") + assert.Equal(t, 67, total, "one decisive match once, nine inconclusive and two active runs on six polls") assert.Equal(t, 12, len(client.jobReads), "skipped workflows need no jobs lookup") }) t.Run("negative assertion", func(t *testing.T) { @@ -109,6 +109,35 @@ func TestHarnessDispatchAssertions_SkippedRunNeedsNoJobs(t *testing.T) { require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) } +func TestCountHarnessDispatches_CompletedRunJobsBecomeVisible(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, firstJob := range []string{"dispatch / Route", "dispatch / Harness run (${{ matrix.agent }})", "dispatch / Fix", "dispatch / Harness run (fix)"} { + t.Run(firstJob, func(t *testing.T) { + client := newDispatchReadsClient(after) + run := client.WorkflowRunsList["org/repo/fullsend.yaml"][31] + client.WorkflowRunJobs[1] = []forge.WorkflowJob{{ID: 1, RunAttempt: 1, Name: firstJob, Status: "completed", Conclusion: "skipped"}} + if firstJob == "dispatch / Route" { + client.WorkflowRunJobs[1][0].Conclusion = "success" + } + d := &Driver{Client: client, afterFunc: func(time.Duration) <-chan time.Time { + if client.polls == 1 { + client.WorkflowRunJobs[1] = append(client.WorkflowRunJobs[1], forge.WorkflowJob{ + ID: 100, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success", + }) + } + return instantAfter(0) + }} + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + assert.Equal(t, 1, count, "a lagging listing must not permanently hide the completed agent job") + assert.Equal(t, 2, client.jobReads[1], "reread the inconclusive listing, then cache the decisive match") + assert.Equal(t, 6, client.polls, "a pending sibling keeps the assertion polling") + assert.Equal(t, run, client.WorkflowRunsList["org/repo/fullsend.yaml"][31], "completed run metadata stays unchanged") + }) + } +} + func TestHarnessDispatchAssertions_RelevantJobsErrorsRemainFatal(t *testing.T) { t.Parallel() after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) @@ -136,7 +165,7 @@ func TestHarnessDispatchAssertions_RelevantJobsErrorsRemainFatal(t *testing.T) { func TestCountHarnessDispatches_CompletedJobCache(t *testing.T) { t.Parallel() after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - for _, name := range []string{"rerun", "unknown run attempt", "unknown job attempt", "mismatched job attempt", "unfinished job", "empty jobs", "assertion local", "changed conclusion"} { + for _, name := range []string{"rerun", "unknown run attempt", "unknown job attempt", "mismatched job attempt", "unfinished job", "unfinished conclusion", "empty jobs", "assertion local", "changed conclusion"} { t.Run(name, func(t *testing.T) { client := newDispatchReadsClient(after) run := &client.WorkflowRunsList["org/repo/fullsend.yaml"][31] @@ -150,6 +179,8 @@ func TestCountHarnessDispatches_CompletedJobCache(t *testing.T) { job.RunAttempt = 2 case "unfinished job": job.Status = "queued" + case "unfinished conclusion": + job.Conclusion = "" case "empty jobs": client.WorkflowRunJobs[1] = nil } diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 5b348e7e08..578f4d8eac 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1592,8 +1592,13 @@ func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, ag if err != nil { return 0, 0, err } + } + hasJob, job := matchAgentJob(jobs, agent) + if !cached { + // Only a counted terminal match is decisive; missing jobs can still become visible. + cacheable := r.Status == "completed" && r.RunAttempt > 0 && hasJob && + job.Conclusion != "" && !isConcurrencySuperseded(job.Conclusion) // Reruns reuse IDs; only reuse completed jobs from the same known attempt. - cacheable := r.Status == "completed" && r.RunAttempt > 0 && len(jobs) > 0 for _, job := range jobs { if job.Status != "completed" || job.RunAttempt != r.RunAttempt { cacheable = false @@ -1604,7 +1609,6 @@ func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, ag completedJobs[r] = jobs } } - hasJob, job := matchAgentJob(jobs, agent) switch { case hasJob && job.Status != "completed": pending++ From 168124951dc8f8fc5ab9e0ecd84e3fd3f0db1748 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 12:36:09 -0500 Subject: [PATCH 24/40] fix(telemetry): converge root-dot hosts and bound instance ports Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 15 +++-- internal/telemetry/tracecontext/identity.go | 32 +++++++-- .../telemetry/tracecontext/identity_test.go | 66 +++++++++++++++++++ 3 files changed, 102 insertions(+), 11 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index a7fa9882e7..5f8aec5014 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -43,13 +43,18 @@ deployment URL on every launch, rather than an entity or API URL. Remove an empty port and the scheme's default port (`443` for HTTPS, `80` for HTTP). Strip leading zeros from other ports, preserving an explicit zero as -`:0` rather than treating it as the default. For example, `https://host:` -becomes `https://host`, and `https://host:08443` becomes `https://host:8443`. -Hosts must be ASCII: use the punycode form for internationalized domain -names, and reject Unicode host spellings instead of converting them. For example, +`:0` rather than treating it as the default, and reject ports above `65535`. +For example, `https://host:` becomes `https://host`, and +`https://host:08443` becomes `https://host:8443`. Hosts must be ASCII: use +the punycode form for internationalized domain names, and reject Unicode +host spellings instead of converting them. For example, `https://GitHub.com:443/` becomes `https://github.com`, and `https://XN--BCHER-KVA.example` becomes `https://xn--bcher-kva.example`. -Bracketed IPv6 hosts follow the same case and port rules. +Bracketed IPv6 hosts follow the same case and port rules, without zone +identifiers: `https://[FE80::1%25EN0]` rejects — use a routable address — +so a normalized instance always re-normalizes to itself. Trailing DNS root +dots are stripped: `https://github.com.` and `https://github.com` are one +deployment with one fallback identity, never two. `NormalizeInstance` rejects queries, fragments, user info, missing hosts, invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index ddc25c1079..c344357514 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -13,6 +13,7 @@ import ( "errors" "fmt" "net/url" + "strconv" "strings" "unicode/utf8" @@ -126,10 +127,12 @@ func nonzeroFallback(fb Fallback) Fallback { // NormalizeInstance canonicalizes a forge web base URL to the D01 instance // form: lowercase scheme://host with an escaped, case-sensitive deployment // prefix and no trailing slashes, query, fragment, or user info. Only http -// and https are accepted, empty/default ports are removed, other ports lose -// leading zeros, and hosts must be ASCII (punycode for IDNs). Path segments and -// escape spelling are preserved so distinct deployments cannot alias. All -// identity and envelope construction must use the normalized form so independent +// and https are accepted, empty/default ports are removed, other ports +// lose leading zeros and must fit 16 bits, a single DNS root dot is +// stripped from the host, and hosts must be ASCII (punycode for IDNs) +// without an IPv6 zone identifier. Path segments and escape spelling are +// preserved so distinct deployments cannot alias. All identity and +// envelope construction must use the normalized form so independent // launches converge. func NormalizeInstance(raw string) (string, error) { if !utf8.ValidString(raw) { @@ -157,14 +160,31 @@ func NormalizeInstance(raw string) (string, error) { return "", errors.New("tracecontext: instance host must be ASCII; use punycode for IDNs") } } + // Zone identifiers survive parsing in a form the round trip cannot + // re-parse, and lowercasing would corrupt the case-sensitive zone. + if strings.ContainsRune(u.Host, '%') { + return "", errors.New("tracecontext: instance host must not carry an IPv6 zone identifier; use a routable address") + } rawPort := u.Port() host := strings.TrimSuffix(strings.ToLower(u.Host), ":"+rawPort) + // The DNS root dot is not a distinct deployment: strip trailing root + // dots so https://host and https://host. share one identity, and the + // strip stays idempotent for multi-dot spellings. + host = strings.TrimRight(host, ".") + if host == "" { + return "", errors.New("tracecontext: instance URL needs a host") + } port := strings.TrimLeft(rawPort, "0") if port == "" && rawPort != "" { port = "0" } - if port != "" && !(scheme == "https" && port == "443" || scheme == "http" && port == "80") { - host += ":" + port + if port != "" { + if _, err := strconv.ParseUint(port, 10, 16); err != nil { + return "", fmt.Errorf("tracecontext: instance port %q must be at most 65535", rawPort) + } + if !(scheme == "https" && port == "443" || scheme == "http" && port == "80") { + host += ":" + port + } } normalized := scheme + "://" + host + strings.TrimRight(u.EscapedPath(), "/") if len(normalized) > 253 { diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index bc9472565a..69e50387ac 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -284,6 +284,72 @@ func TestNormalizeInstance(t *testing.T) { } } +// TestNormalizeInstance_RootDotDoesNotForkIdentity pins the DNS root-dot +// rule: `host` and `host.` name the same deployment, so they must converge +// to one instance and one fallback, never two trace IDs. +func TestNormalizeInstance_RootDotDoesNotForkIdentity(t *testing.T) { + t.Parallel() + dotted, err := NormalizeInstance("https://GitHub.com.") + require.NoError(t, err) + plain, err := NormalizeInstance("https://github.com") + require.NoError(t, err) + assert.Equal(t, plain, dotted) + + a := v01Identity() + b := v01Identity() + a.Instance, b.Instance = plain, dotted + fa, ok := DeriveFallback(a) + require.True(t, ok) + fb, ok := DeriveFallback(b) + require.True(t, ok) + assert.Equal(t, fa, fb, "one deployment must not fork into two fallback traces") +} + +// TestNormalizeInstance_PortRangeAndZones pins the port and IPv6-zone +// rules: ports must fit 16 bits, and zone identifiers must reject so +// validInstance(NormalizeInstance(x)) always holds. +func TestNormalizeInstance_PortRangeAndZones(t *testing.T) { + t.Parallel() + for _, raw := range []string{"https://example.com:65535", "https://example.com:065535"} { + _, err := NormalizeInstance(raw) + require.NoError(t, err, raw) + } + for _, raw := range []string{ + "https://example.com:65536", + "https://example.com:99999999999999999999", + "https://[FE80::1%25EN0]", + "https://[fe80::1%en0]", + "https://.", + } { + _, err := NormalizeInstance(raw) + assert.Error(t, err, "input %q must be rejected", raw) + } +} + +// FuzzNormalizeInstance asserts the canonicalization invariant: anything +// NormalizeInstance accepts must re-normalize to itself, so the normalized +// form is always a valid instance. +func FuzzNormalizeInstance(f *testing.F) { + f.Add("https://github.com") + f.Add("https://GitLab.example.com:08443/gitlab/") + f.Add("https://[2001:DB8::1]:443/") + f.Add("https://example.com.") + f.Add("https://example.com:65536") + f.Fuzz(func(t *testing.T, raw string) { + normalized, err := NormalizeInstance(raw) + if err != nil { + return + } + again, err := NormalizeInstance(normalized) + if err != nil { + t.Fatalf("normalized instance must re-normalize: %q: %v", normalized, err) + } + if normalized != again { + t.Fatalf("normalization must be idempotent: %q vs %q", normalized, again) + } + }) +} + func TestNormalizeInstance_Rejects(t *testing.T) { for _, raw := range []string{ "", From cd97e9f072b5d99811779c4a7857b31cf4167da7 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 12:36:40 -0500 Subject: [PATCH 25/40] fix(telemetry): keep pending admission on resolved identities Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 25 +++++++++--- internal/telemetry/tracecontext/envelope.go | 7 ++++ .../telemetry/tracecontext/envelope_test.go | 38 +++++++++++++++++++ 3 files changed, 65 insertions(+), 5 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 5f8aec5014..52697c9b20 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -198,8 +198,14 @@ exactly one outcome: - **Admitted**: a verified bound envelope matched every binding component. The result carries the admitted TraceID, parent SpanID, and authenticated provenance. -- **Pending**: a verified pending marker matched the expected scope. It - grants nothing; bounded rereads are caller policy. +- **Pending**: a verified pending marker matched the expected scope — + installation, instance, container, and kind, never the entity, because a + pending marker carries no entity binding by design. A marker replayed + onto another entity in the same container still grants nothing beyond a + bounded wait. It grants no context; callers must bound that wait by a + window from the entity's trusted creation metadata (for example + `created_at`) before rereading and falling back, per + [ADR 0154](../../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). - **Fallback**: nothing was admissible. The caller uses the entity-derived fallback. @@ -207,8 +213,16 @@ The zero-value result selects fallback and grants no context or provenance. Fallback reason codes are redacted diagnostics — `absent`, `malformed`, `oversized`, `unknown-version`, `unknown-key`, `bad-signature`, -`binding-mismatch`, `conflicting-carrier`, `provenance` — never key -material or raw bytes. A plain W3C `traceparent` is never an envelope. +`binding-mismatch`, `conflicting-carrier`, `provenance`, `unresolved` — +never key material or raw bytes. A plain W3C `traceparent` is never an +envelope. + +Any extra or differing candidate deliberately forces fallback, even when +one candidate alone would admit: an actor who can append one carrier to an +editable body must not be able to choose or suppress the admitted context. +Publishing a bound envelope must remove the pending marker it replaces; +leaving both present produces conflicting carriers and fallback, never a +pick between them. The result structurally cannot carry sampling flags, `tracestate`, baggage, or dispatch permission. Trace admission and dispatch @@ -217,7 +231,8 @@ regardless of admission, and an admitted envelope never authorizes anything. An unresolved identity (missing instance, container, kind, or entity) is -explicit: callers must postpone dispatch with diagnostics rather than +explicit: admission returns fallback with reason `unresolved` rather than +pending, and callers must postpone dispatch with diagnostics rather than derive a fallback or guess. ## Compatibility diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index 653763678f..4cb00e15e1 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -420,6 +420,7 @@ const ( ReasonBindingMismatch = "binding-mismatch" ReasonConflictingCarrier = "conflicting-carrier" ReasonProvenance = "provenance" + ReasonUnresolved = "unresolved" ReasonPending = "pending" ) @@ -508,5 +509,11 @@ func Admit(expected Identity, keys map[[8]byte]ed25519.PublicKey, candidates ... Provenance: env.Provenance, } } + // A pending marker binds no entity, but an unresolved expected identity + // must still postpone explicitly (FR-002) rather than wait out the + // pending window on a guessed binding. + if !expected.Resolved() { + return fallback(ReasonUnresolved) + } return Result{Outcome: OutcomePending, Reason: ReasonPending} } diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index 2a81b23eec..0ec1c782b2 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -573,6 +573,44 @@ func TestAdmit_PendingGrantsNothing(t *testing.T) { assert.Equal(t, ReasonBindingMismatch, res.Reason) } +// TestAdmit_PendingRequiresResolvedIdentity pins the README rule: an +// unresolved expected identity never earns the pending outcome; the launch +// must postpone with an explicit fallback reason instead of waiting out +// the pending window on a guessed binding. +func TestAdmit_PendingRequiresResolvedIdentity(t *testing.T) { + t.Parallel() + raw, keys := signedGolden(t, DomainPending, ProvenanceNone) + unresolved := goldenIdentity() + unresolved.Entity = 0 + res := Admit(unresolved, keys, raw) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnresolved}, res) +} + +// TestAdmit_PendingMarkerIsContainerScoped documents that a pending marker +// deliberately carries no entity binding: one replayed onto another entity +// in the same container still grants nothing beyond a bounded pending +// wait, which callers must cap by a window from trusted creation metadata. +func TestAdmit_PendingMarkerIsContainerScoped(t *testing.T) { + t.Parallel() + raw, keys := signedGolden(t, DomainPending, ProvenanceNone) + replayed := goldenIdentity() + replayed.Entity++ + res := Admit(replayed, keys, raw) + assert.Equal(t, Result{Outcome: OutcomePending, Reason: ReasonPending}, res) +} + +// TestAdmit_BoundEnvelopeWithStalePendingMarker pins the fail-closed rule: +// a publisher that leaves the pending marker beside the bound envelope +// produces conflicting carriers, and admission rejects the conflict rather +// than picking either carrier. +func TestAdmit_BoundEnvelopeWithStalePendingMarker(t *testing.T) { + t.Parallel() + bound, keys := signedGolden(t, DomainBound, ProvenanceNone) + pending, _ := signedGolden(t, DomainPending, ProvenanceNone) + res := Admit(goldenIdentity(), keys, bound, pending) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonConflictingCarrier}, res) +} + // TestAdmit_ProvenanceConsistency enforces the D02 rules: an ordinary // source link keeps the destination's own trace; scenario provenance // inherits the scenario trace. From 1d069334a2d3a073b8888e2998955ceb0392c340 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 12:37:22 -0500 Subject: [PATCH 26/40] docs(telemetry): mark the trace-context v1 contract provisional Signed-off-by: Dharit Shah --- ...work-item-and-behaviour-scenario-traces.md | 5 +++- docs/normative/trace-context/v1/README.md | 11 ++++++--- docs/reference/trace-context.md | 24 +++++++++++-------- 3 files changed, 26 insertions(+), 14 deletions(-) diff --git a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md index 066a20414a..f08e33d2d5 100644 --- a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md +++ b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md @@ -19,7 +19,10 @@ Date: 2026-10-22 Accepted -This records the chosen topology; implementation is pending. +This records the chosen topology. The identity, fallback, envelope, and +admission foundation is implemented — see the +[trace-context v1 specification](../normative/trace-context/v1/README.md). +Carrier publication, key provisioning, and runtime integration are pending. The [trace-context v1 specification](../normative/trace-context/v1/README.md) defines the detailed identity, fallback, signed-envelope, and admission diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 52697c9b20..6dc7314850 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -239,6 +239,11 @@ derive a fallback or guess. The [conformance vectors](../../../reference/trace-context.md#conformance-evidence) pin the exact signed bytes of one envelope per domain and provenance kind. -Any change to the wire layout, derivation, or key-selector rules is a -compatibility break that requires a new version byte and a reviewed migration -path. Unknown versions must reject cleanly. + +**v1 is provisional** until the first pull request that publishes carriers +merges. No production carrier exists yet, so the wire layout, derivation, +and key-selector rules may still change without a new version byte while +contract gaps surface in review. From the first carrier-publishing pull +request onward, any such change is a compatibility break that requires a +new version byte and a reviewed migration path. Unknown versions must +reject cleanly. diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 7b3b0221de..c541e91a7f 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -8,10 +8,10 @@ This page covers the Go API and adapter integration. ## Implementation scope At implementation revision -[`1322cdf7d595673d7db4a812a9d74402aa90c849`](https://github.com/fullsend-ai/fullsend/tree/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext), -[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext/identity.go) +[`cd97e9f072b5d99811779c4a7857b31cf4167da7`](https://github.com/fullsend-ai/fullsend/tree/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext), +[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/identity.go) implements identity resolution and fallback derivation; -[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext/envelope.go) +[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/envelope.go) implements signing, strict parsing, and admission. The package performs no network I/O or configuration reads and never grants dispatch permission. Carrier publication, key provisioning, production creation activation, @@ -24,15 +24,15 @@ mintcore module. ## Adapter integration -[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/tracker/jira_client.go) +[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/tracker/jira_client.go) exposes the project ID as `tracker.Issue.ContainerID`; Jira -[search requests](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/forge/jira/client.go) +[search requests](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/forge/jira/client.go) include `project`. Missing or invalid project IDs stay zero (unresolved). Jira's create response contains no project ID, so a subsequent trusted read must resolve the container before trace admission. Forge-backed tracker callers must resolve their repository separately through `forge.Client`. -[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/forge/github/github.go) +[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/forge/github/github.go) decodes GitHub's `fullDatabaseId` into an `int64`, accepting numeric or string JSON without floating-point rounding; it does not use the deprecated 32-bit GraphQL `databaseId`. Missing or invalid IDs leave identity unresolved without @@ -64,13 +64,17 @@ database ID; its result alone cannot resolve trace identity. ## Conformance evidence -- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext/identity_test.go) +- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/identity_test.go) contains independent fallback vectors, deployment-prefix separation checks, - cross-process convergence, and SDK exporter lifecycle assertions. -- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/1322cdf7d595673d7db4a812a9d74402aa90c849/internal/telemetry/tracecontext/envelope_test.go) + cross-process convergence, root-dot/port/IPv6-zone canonicalization, a + normalization fuzz target asserting the canonical form re-normalizes to + itself, and SDK exporter lifecycle assertions. +- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/envelope_test.go) contains independent signed-wire vectors for both domains and all provenance kinds, binding checks, empty/default/padded-port convergence, zero-value fallback, - malformed-input cases, and parser fuzzing. + pending-scope admission (container-scoped markers, unresolved identities, + stale markers beside bound envelopes), malformed-input cases, and parser + fuzzing. These foundation tests do not establish production runtime integration or live-adapter trace continuity. From 87c83d71ddda8143c157f93ff2e59312e1fea5ba Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 14:36:41 -0500 Subject: [PATCH 27/40] fix(telemetry): report unresolved identity before carrier diagnostics Admit returned absent, malformed, or binding-mismatch for an unresolved expected identity depending on the candidate, so callers could not use the reason code to decide FR-002 postponement. Check Resolved() at entry so unresolved always wins, and cover every component and carrier kind. Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 6 +-- docs/reference/trace-context.md | 6 +-- internal/telemetry/tracecontext/envelope.go | 14 +++--- .../telemetry/tracecontext/envelope_test.go | 44 ++++++++++++++++++- 4 files changed, 57 insertions(+), 13 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 6dc7314850..7e66e65e38 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -231,9 +231,9 @@ regardless of admission, and an admitted envelope never authorizes anything. An unresolved identity (missing instance, container, kind, or entity) is -explicit: admission returns fallback with reason `unresolved` rather than -pending, and callers must postpone dispatch with diagnostics rather than -derive a fallback or guess. +explicit: admission returns fallback with reason `unresolved` before +inspecting any candidate, and callers must postpone dispatch with +diagnostics rather than derive a fallback or guess. ## Compatibility diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index c541e91a7f..c918873d53 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -72,9 +72,9 @@ database ID; its result alone cannot resolve trace identity. - [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/envelope_test.go) contains independent signed-wire vectors for both domains and all provenance kinds, binding checks, empty/default/padded-port convergence, zero-value fallback, - pending-scope admission (container-scoped markers, unresolved identities, - stale markers beside bound envelopes), malformed-input cases, and parser - fuzzing. + pending-scope admission (container-scoped markers, stale markers beside bound + envelopes), unresolved identities suppressing every carrier kind, + malformed-input cases, and parser fuzzing. These foundation tests do not establish production runtime integration or live-adapter trace continuity. diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index 4cb00e15e1..3b1d469b0d 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -462,7 +462,14 @@ func reasonForParse(err error) string { // any differing candidates reject. Keys are resolved only from the // supplied trusted set. Admission is independent of dispatch // authorization: this function never returns permission. +// +// An unresolved expected identity reports ReasonUnresolved before any +// carrier is inspected: the caller must postpone dispatch (FR-002) and +// must not read the candidate's own diagnostics as the cause. func Admit(expected Identity, keys map[[8]byte]ed25519.PublicKey, candidates ...[]byte) Result { + if !expected.Resolved() { + return fallback(ReasonUnresolved) + } if len(candidates) == 0 { return fallback(ReasonAbsent) } @@ -509,11 +516,6 @@ func Admit(expected Identity, keys map[[8]byte]ed25519.PublicKey, candidates ... Provenance: env.Provenance, } } - // A pending marker binds no entity, but an unresolved expected identity - // must still postpone explicitly (FR-002) rather than wait out the - // pending window on a guessed binding. - if !expected.Resolved() { - return fallback(ReasonUnresolved) - } + // A pending marker binds no entity, so a resolved scope is enough. return Result{Outcome: OutcomePending, Reason: ReasonPending} } diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index 0ec1c782b2..701e7b947f 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -342,7 +342,10 @@ func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { _, err := Parse(mutated) assert.Error(t, err) _, keys := goldenKeys(t) - assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, Admit(id, keys, mutated)) + // The unresolved identity dominates, but the same malformed + // carrier under a resolved identity still reports malformed. + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnresolved}, Admit(id, keys, mutated)) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, Admit(goldenIdentity(), keys, mutated)) }) } } @@ -586,6 +589,45 @@ func TestAdmit_PendingRequiresResolvedIdentity(t *testing.T) { assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnresolved}, res) } +// TestAdmit_UnresolvedIdentityAlwaysReportsUnresolved pins the README +// contract: an unresolved identity must postpone (FR-002) whatever carrier +// is present, so callers never mistake a carrier rejection for the cause. +func TestAdmit_UnresolvedIdentityAlwaysReportsUnresolved(t *testing.T) { + t.Parallel() + bound, keys := signedGolden(t, DomainBound, ProvenanceNone) + pending, _ := signedGolden(t, DomainPending, ProvenanceNone) + + components := []struct { + name string + mutate func(*Identity) + }{ + {"instance", func(id *Identity) { id.Instance = "" }}, + {"container", func(id *Identity) { id.Container = 0 }}, + {"kind", func(id *Identity) { id.Kind = 0 }}, + {"entity", func(id *Identity) { id.Entity = 0 }}, + } + carriers := []struct { + name string + raw [][]byte + }{ + {"absent", nil}, + {"malformed", [][]byte{[]byte("not-an-envelope")}}, + {"bound", [][]byte{bound}}, + {"pending", [][]byte{pending}}, + } + for _, c := range components { + for _, carrier := range carriers { + t.Run(c.name+"/"+carrier.name, func(t *testing.T) { + t.Parallel() + expected := goldenIdentity() + c.mutate(&expected) + res := Admit(expected, keys, carrier.raw...) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnresolved}, res) + }) + } + } +} + // TestAdmit_PendingMarkerIsContainerScoped documents that a pending marker // deliberately carries no entity binding: one replayed onto another entity // in the same container still grants nothing beyond a bounded pending From fc0e995b06681ff8a167233b97d523a7deeed208 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 15:09:02 -0500 Subject: [PATCH 28/40] fix(behaviourtest): skip the jobs read for runs that have not started settleHarnessDispatchCount and AssertNoHarnessAgentArtifact called ListWorkflowRunJobs for queued, waiting, requested, and pending runs. Those runs classify as pending without the jobs listing, but the read can 404 server-side and the blanket retry was deliberately removed. Skip the read and cover the 404 case. Signed-off-by: Dharit Shah --- .../ci/githubactions/dispatch_reads_test.go | 23 +++++++++++++++++++ .../drivers/ci/githubactions/githubactions.go | 21 +++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index ea17f96912..3246eff8cd 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -109,6 +109,29 @@ func TestHarnessDispatchAssertions_SkippedRunNeedsNoJobs(t *testing.T) { require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) } +func TestHarnessDispatchAssertions_QueuedRunNeedsNoJobs(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, status := range []string{"queued", "waiting", "requested", "pending"} { + t.Run(status, func(t *testing.T) { + t.Parallel() + fake := forge.NewFakeClient() + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { + {ID: 1, Status: status, CreatedAt: after.Format(time.RFC3339)}, + }} + // A queued run's jobs read can 404; it must not be attempted. + fake.Errors["ListWorkflowRunJobs"] = forge.ErrNotFound + d := &Driver{Client: fake} + + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) + require.NoError(t, err) + assert.Zero(t, count) + assert.Equal(t, 1, pending) + require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) + }) + } +} + func TestCountHarnessDispatches_CompletedRunJobsBecomeVisible(t *testing.T) { t.Parallel() after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 980e116048..aeb71678de 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1607,6 +1607,17 @@ func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent } } +// runNotStarted reports whether a workflow run has not begun executing. +// Its jobs listing cannot classify a dispatch and can still 404 while the +// run is queued, awaiting approval, or waiting on another run. +func runNotStarted(status string) bool { + switch status { + case "queued", "waiting", "requested", "pending": + return true + } + return false +} + // settleHarnessDispatchCount classifies harness runs created after the // trigger time into counted dispatches and pending runs. A run is pending // when its agent job exists but has not completed, or when the run itself @@ -1633,6 +1644,12 @@ func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, ag if r.Status == "completed" && r.Conclusion == "skipped" { continue } + if runNotStarted(r.Status) { + // A run that has not started cannot show agent work, so it is + // pending whatever the jobs listing would say. + pending++ + continue + } jobs, cached := completedJobs[r] if !cached { jobs, err = d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) @@ -1825,6 +1842,10 @@ func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, if r.Status == "completed" && r.Conclusion == "skipped" { continue } + if runNotStarted(r.Status) { + // No agent job can exist before the run starts. + continue + } jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { return err From a14dfbf4b54f137a75e2e265249680176428249e Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 15:09:24 -0500 Subject: [PATCH 29/40] docs(telemetry): unpin trace-context references and state the admission contract Link the implementation and conformance evidence at main instead of a stale revision. Document that Parse returns unverified fields and Admit is the only authenticated path, and state that a forged carrier can deny continuity but cannot inject or select an admitted context. Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 8 ++++--- docs/reference/trace-context.md | 22 +++++++++---------- internal/telemetry/tracecontext/envelope.go | 21 +++++++++++------- .../telemetry/tracecontext/envelope_test.go | 10 +++++++++ 4 files changed, 39 insertions(+), 22 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 7e66e65e38..85e1fbf373 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -218,9 +218,11 @@ never key material or raw bytes. A plain W3C `traceparent` is never an envelope. Any extra or differing candidate deliberately forces fallback, even when -one candidate alone would admit: an actor who can append one carrier to an -editable body must not be able to choose or suppress the admitted context. -Publishing a bound envelope must remove the pending marker it replaces; +one candidate alone would admit. An actor who can edit the body can deny +continuity by appending junk or deleting the carrier, but can never choose, +alter, or inject the admitted context; rejection is deliberately fail-closed +so a forged carrier is reported rather than silently ignored. Publishing a +bound envelope must remove the pending marker it replaces; leaving both present produces conflicting carriers and fallback, never a pick between them. diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index c918873d53..e9b4483080 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -7,11 +7,11 @@ This page covers the Go API and adapter integration. ## Implementation scope -At implementation revision -[`cd97e9f072b5d99811779c4a7857b31cf4167da7`](https://github.com/fullsend-ai/fullsend/tree/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext), -[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/identity.go) +The v1 implementation lives in +[`internal/telemetry/tracecontext`](https://github.com/fullsend-ai/fullsend/tree/main/internal/telemetry/tracecontext): +[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/identity.go) implements identity resolution and fallback derivation; -[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/envelope.go) +[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/envelope.go) implements signing, strict parsing, and admission. The package performs no network I/O or configuration reads and never grants dispatch permission. Carrier publication, key provisioning, production creation activation, @@ -24,15 +24,15 @@ mintcore module. ## Adapter integration -[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/tracker/jira_client.go) +[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/main/internal/tracker/jira_client.go) exposes the project ID as `tracker.Issue.ContainerID`; Jira -[search requests](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/forge/jira/client.go) +[search requests](https://github.com/fullsend-ai/fullsend/blob/main/internal/forge/jira/client.go) include `project`. Missing or invalid project IDs stay zero (unresolved). Jira's create response contains no project ID, so a subsequent trusted read must resolve the container before trace admission. Forge-backed tracker callers must resolve their repository separately through `forge.Client`. -[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/forge/github/github.go) +[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/main/internal/forge/github/github.go) decodes GitHub's `fullDatabaseId` into an `int64`, accepting numeric or string JSON without floating-point rounding; it does not use the deprecated 32-bit GraphQL `databaseId`. Missing or invalid IDs leave identity unresolved without @@ -53,10 +53,10 @@ database ID; its result alone cannot resolve trace identity. | `Identity.Resolved` | Whether forge-side identity components are present | | `DeriveFallback` | The v1 deterministic fallback context | | `NormalizeInstance` | Canonical deployment base URL, including its path prefix | -| `Envelope` | A decoded v1 envelope or pending marker | +| `Envelope` | A decoded, unverified v1 envelope or pending marker; fields are safe only after `Admit` admits | | `Envelope.Sign` | Validate and sign with an Ed25519 private key (host-side only) | | `Envelope.Marshal` | Canonical wire bytes | -| `Parse` | Strict bounded decode | +| `Parse` | Strict bounded structural decode; does not verify the signature or binding | | `DecodeCarrier` | Strict base64 carrier decode | | `KeyID` | The 8-byte key selector for a public key | | `Admit` | The pure admission decision | @@ -64,12 +64,12 @@ database ID; its result alone cannot resolve trace identity. ## Conformance evidence -- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/identity_test.go) +- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/identity_test.go) contains independent fallback vectors, deployment-prefix separation checks, cross-process convergence, root-dot/port/IPv6-zone canonicalization, a normalization fuzz target asserting the canonical form re-normalizes to itself, and SDK exporter lifecycle assertions. -- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/cd97e9f072b5d99811779c4a7857b31cf4167da7/internal/telemetry/tracecontext/envelope_test.go) +- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/envelope_test.go) contains independent signed-wire vectors for both domains and all provenance kinds, binding checks, empty/default/padded-port convergence, zero-value fallback, pending-scope admission (container-scoped markers, stale markers beside bound diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index 3b1d469b0d..aea64a3a9c 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -65,9 +65,12 @@ type Provenance struct { ScenarioInvocationID [16]byte } -// Envelope is a decoded v1 envelope or pending marker. The wire layout, -// exact sizes, and strict limits are frozen in -// docs/normative/trace-context/v1/README.md; Marshal is its only legal encoder. +// Envelope is a decoded v1 envelope or pending marker. Its fields are +// unauthenticated: Parse checks structure only, so TraceID, ParentSpanID, +// and Provenance must not be consumed unless Admit returns +// OutcomeAdmitted. The wire layout, exact sizes, and strict limits are +// frozen in docs/normative/trace-context/v1/README.md; Marshal is its only +// legal encoder. type Envelope struct { Domain Domain KeyID [8]byte @@ -254,11 +257,13 @@ func (e *Envelope) Marshal() []byte { return append(e.payload(), e.Signature[:]...) } -// Parse strictly decodes and validates wire bytes. It accepts only the -// exact structural length for the parsed domain and provenance kind; -// duplicate and unknown fields are structurally impossible in the fixed -// layout. Provenance cross-field consistency is checked at admission, not -// here. +// Parse strictly decodes and structurally validates wire bytes. It accepts +// only the exact structural length for the parsed domain and provenance +// kind; duplicate and unknown fields are structurally impossible in the +// fixed layout. Parse does not verify the signature or binding, so its +// result is unauthenticated: Admit is the only authenticated path and the +// only safe source of trace context. Provenance cross-field consistency is +// checked at admission, not here. func Parse(b []byte) (*Envelope, error) { if len(b) > MaxEnvelopeLen { return nil, errOversized diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index 701e7b947f..c83c23703a 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -467,6 +467,16 @@ func TestAdmit_DuplicateCarriers(t *testing.T) { assert.Equal(t, ReasonConflictingCarrier, res.Reason, "conflicting carriers must reject, never first-match") } +// TestAdmit_AppendedJunkForcesFallback documents the accepted +// denial-of-continuity trade-off: an editor can suppress continuity by +// appending an unauthenticated carrier, but cannot inject or select one. +func TestAdmit_AppendedJunkForcesFallback(t *testing.T) { + t.Parallel() + raw, keys := signedGolden(t, DomainBound, ProvenanceNone) + res := Admit(goldenIdentity(), keys, raw, []byte("not-an-envelope")) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, res) +} + func TestAdmit_Oversized(t *testing.T) { _, keys := goldenKeys(t) From 77219ca1ad9710431b48dc9d9b00fca3c6b8f0f3 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 16:10:38 -0500 Subject: [PATCH 30/40] fix(behaviourtest): check waiting runs for already-run agent jobs Signed-off-by: Dharit Shah --- .../ci/githubactions/dispatch_reads_test.go | 21 +++++++++++++++++-- .../drivers/ci/githubactions/githubactions.go | 14 ++++++++----- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index 3246eff8cd..eb3c4d593b 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -109,7 +109,7 @@ func TestHarnessDispatchAssertions_SkippedRunNeedsNoJobs(t *testing.T) { require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) } -func TestHarnessDispatchAssertions_QueuedRunNeedsNoJobs(t *testing.T) { +func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { t.Parallel() after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) for _, status := range []string{"queued", "waiting", "requested", "pending"} { @@ -119,7 +119,7 @@ func TestHarnessDispatchAssertions_QueuedRunNeedsNoJobs(t *testing.T) { fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { {ID: 1, Status: status, CreatedAt: after.Format(time.RFC3339)}, }} - // A queued run's jobs read can 404; it must not be attempted. + // The count path never reads jobs for a not-started run. fake.Errors["ListWorkflowRunJobs"] = forge.ErrNotFound d := &Driver{Client: fake} @@ -127,7 +127,24 @@ func TestHarnessDispatchAssertions_QueuedRunNeedsNoJobs(t *testing.T) { require.NoError(t, err) assert.Zero(t, count) assert.Equal(t, 1, pending) + + // The negative assertion reads the listing and treats a 404 as + // absence: the listing can 404 before the run starts. require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) + + // A waiting run can follow jobs that already ran (environment + // approval), so returned jobs are checked, never skipped. + delete(fake.Errors, "ListWorkflowRunJobs") + fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{1: { + {ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}, + }} + require.Error(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), + "a run awaiting approval can already hold a completed agent job") + + // Any other listing error stays fatal on the negative path. + lookupErr := errors.New("jobs lookup failed") + fake.Errors["ListWorkflowRunJobs"] = lookupErr + require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), lookupErr) }) } } diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index aeb71678de..0378f09265 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1842,13 +1842,17 @@ func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, if r.Status == "completed" && r.Conclusion == "skipped" { continue } - if runNotStarted(r.Status) { - // No agent job can exist before the run starts. - continue - } jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { - return err + // A run that has not started cannot hold agent work, and its + // jobs listing can 404 before the run starts — only that + // absence is tolerated. A waiting run can follow jobs that + // already ran (environment approval), so its listing is + // checked like any other run's. + if !(runNotStarted(r.Status) && forge.IsNotFound(err)) { + return err + } + continue } // Every matching job is inspected independently here, rather than // through matchAgentJob's single "best" match: a job list can From 2fd281e728280559a4f0e7e5d68915c535758b3a Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 17:03:55 -0500 Subject: [PATCH 31/40] fix(behaviourtest): tolerate only first-page jobs listing absence Signed-off-by: Dharit Shah --- internal/forge/forge.go | 7 ++++ internal/forge/github/github.go | 6 +++ internal/forge/github/github_test.go | 34 +++++++++++++++ internal/forge/gitlab/ci.go | 6 +++ internal/forge/gitlab/methods_test.go | 41 +++++++++++++++++++ .../ci/githubactions/dispatch_reads_test.go | 14 +++++-- .../drivers/ci/githubactions/githubactions.go | 11 ++--- 7 files changed, 111 insertions(+), 8 deletions(-) diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 07e16f6e87..d8be8bb6cb 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -249,6 +249,13 @@ func ValidatePipelineVarOverrideRole(role string) error { // ErrNotFound indicates a requested resource was not found on the forge. var ErrNotFound = errors.New("not found") +// ErrJobsListingAbsent indicates that a workflow run's jobs listing was +// reported not found on its first page — for example, a run that has not +// started yet. Adapters attach it only to first-page not-founds: a +// not-found on a later page means the listing was already partially +// readable and must never be read as absence. +var ErrJobsListingAbsent = errors.New("workflow run jobs listing absent") + // IsNotFound reports whether err indicates a resource was not found. func IsNotFound(err error) bool { return errors.Is(err, ErrNotFound) diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index f776382cf8..365d7f3fc6 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -4447,6 +4447,12 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string url.PathEscape(owner), url.PathEscape(repo), runID, perPage, page) label := fmt.Sprintf("list workflow run jobs for %s/%s run %d page %d", owner, repo, runID, page) if err := c.getCachedJSON(ctx, path, &result); err != nil { + if page == 1 && forge.IsNotFound(err) { + // First-page absence means the run's listing does not exist + // yet; a later-page 404 is a partially readable listing and + // must not be readable as absence. + return nil, fmt.Errorf("%s: %w: %w", label, forge.ErrJobsListingAbsent, err) + } return nil, fmt.Errorf("%s: %w", label, err) } if len(result.Jobs) == 0 { diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index a87c244e01..3e565e93d1 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -5157,10 +5157,44 @@ func TestListWorkflowRunJobs_NotFound(t *testing.T) { require.ErrorAs(t, err, &apiErr) assert.Equal(t, tt.status, apiErr.StatusCode) assert.Equal(t, tt.status == http.StatusNotFound, forge.IsNotFound(err)) + if tt.status == http.StatusNotFound { + assert.ErrorIs(t, err, forge.ErrJobsListingAbsent, "a first-page absence is marked as the listing being absent") + } else { + assert.NotErrorIs(t, err, forge.ErrJobsListingAbsent) + } }) } } +// TestListWorkflowRunJobs_LaterPageNotFoundIsNotAbsence is a regression +// test: a 404 on a later pagination page means the listing was partially +// readable — page 1 may already hold jobs — so it must not carry +// ErrJobsListingAbsent, which callers tolerate as a not-yet-started run's +// absent listing. +func TestListWorkflowRunJobs_LaterPageNotFoundIsNotAbsence(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Query().Get("page") { + case "1": + jobs := make([]map[string]any, 100) // full page forces page 2 + for i := range jobs { + jobs[i] = map[string]any{"id": i + 1, "name": "dispatch / Harness run (fix)", "status": "completed", "conclusion": "success"} + } + json.NewEncoder(w).Encode(map[string]any{"jobs": jobs}) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + client := newTestClient(t, srv) + jobs, err := client.ListWorkflowRunJobs(context.Background(), "org", "repo", 42) + require.Error(t, err) + assert.Nil(t, jobs) + assert.True(t, forge.IsNotFound(err), "the 404 stays classified as not found") + assert.NotErrorIs(t, err, forge.ErrJobsListingAbsent, "a partially readable listing is never absence") + assert.Contains(t, err.Error(), "page 2") +} + func TestListWorkflowRunJobs_CancelledContext(t *testing.T) { calls := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { diff --git a/internal/forge/gitlab/ci.go b/internal/forge/gitlab/ci.go index f28b1ca226..9277fcbb9b 100644 --- a/internal/forge/gitlab/ci.go +++ b/internal/forge/gitlab/ci.go @@ -923,6 +923,12 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string proj, runID, perPage, page) resp, err := c.get(ctx, path) if err != nil { + if page == 1 && forge.IsNotFound(err) { + // First-page absence means the pipeline's job listing does + // not exist yet; a later-page 404 is a partially readable + // listing and must not be readable as absence. + return nil, fmt.Errorf("list pipeline jobs page %d: %w: %w", page, forge.ErrJobsListingAbsent, err) + } return nil, fmt.Errorf("list pipeline jobs page %d: %w", page, err) } var jobs []glJob diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index 154ec3fa73..dd40c499ed 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -4006,6 +4006,47 @@ func TestListWorkflowRunJobs_Error(t *testing.T) { }) _, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) require.Error(t, err) + assert.NotErrorIs(t, err, forge.ErrJobsListingAbsent) +} + +// TestListWorkflowRunJobs_FirstPageNotFoundMarksAbsence covers the +// not-found classification adapters attach to a first-page absence, and +// the later-page 404 that must not carry it: a partially readable +// listing is never absence. +func TestListWorkflowRunJobs_FirstPageNotFoundMarksAbsence(t *testing.T) { + t.Run("first page 404 is absence", func(t *testing.T) { + client, mux := setupTest(t) + mux.HandleFunc("/api/v4/projects/o%2Fr/pipelines/10/jobs", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + }) + _, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) + require.Error(t, err) + assert.ErrorIs(t, err, forge.ErrNotFound) + assert.ErrorIs(t, err, forge.ErrJobsListingAbsent, "a first-page absence is marked as the listing being absent") + }) + t.Run("later page 404 is not absence", func(t *testing.T) { + client, mux := setupTest(t) + mux.HandleFunc("/api/v4/projects/o%2Fr/pipelines/10/jobs", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Query().Get("page") { + case "1": + jobs := make([]string, 100) + for i := range jobs { + jobs[i] = fmt.Sprintf(`{"id":%d,"name":"job-%d","status":"success"}`, i+1, i+1) + } + w.Header().Set("X-Next-Page", "2") + fmt.Fprint(w, "["+strings.Join(jobs, ",")+"]") + default: + w.WriteHeader(http.StatusNotFound) + } + }) + jobs, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) + require.Error(t, err) + assert.Nil(t, jobs) + assert.ErrorIs(t, err, forge.ErrNotFound, "the 404 stays classified as not found") + assert.NotErrorIs(t, err, forge.ErrJobsListingAbsent, "a partially readable listing is never absence") + assert.Contains(t, err.Error(), "page 2") + }) } func TestListWorkflowRunArtifacts_Error(t *testing.T) { diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index eb3c4d593b..34d24f3c78 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -3,6 +3,7 @@ package githubactions import ( "context" "errors" + "fmt" "testing" "time" @@ -120,7 +121,7 @@ func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { {ID: 1, Status: status, CreatedAt: after.Format(time.RFC3339)}, }} // The count path never reads jobs for a not-started run. - fake.Errors["ListWorkflowRunJobs"] = forge.ErrNotFound + fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingAbsent d := &Driver{Client: fake} count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) @@ -128,10 +129,17 @@ func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { assert.Zero(t, count) assert.Equal(t, 1, pending) - // The negative assertion reads the listing and treats a 404 as - // absence: the listing can 404 before the run starts. + // The negative assertion reads the listing and tolerates only a + // first-page absence: the listing can 404 before the run starts. require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) + // A 404 on a later page means the listing was partially read — + // page 1 may hold a completed agent job — so it is never + // absence, even for a not-started run. + fake.Errors["ListWorkflowRunJobs"] = fmt.Errorf("list workflow run jobs page 2: %w", forge.ErrNotFound) + require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), forge.ErrNotFound, + "a partially readable listing must fail the assertion") + // A waiting run can follow jobs that already ran (environment // approval), so returned jobs are checked, never skipped. delete(fake.Errors, "ListWorkflowRunJobs") diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 0378f09265..9aa2495705 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1845,11 +1845,12 @@ func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { // A run that has not started cannot hold agent work, and its - // jobs listing can 404 before the run starts — only that - // absence is tolerated. A waiting run can follow jobs that - // already ran (environment approval), so its listing is - // checked like any other run's. - if !(runNotStarted(r.Status) && forge.IsNotFound(err)) { + // jobs listing can be absent before the run starts — only a + // first-page absence is tolerated. A waiting run can follow + // jobs that already ran (environment approval), so its listing + // is checked like any other run's, and a listing that was + // partially read before a later-page 404 is never absence. + if !(runNotStarted(r.Status) && errors.Is(err, forge.ErrJobsListingAbsent)) { return err } continue From 72247c9ee717a21e9a0793f88696fb6c2599e48a Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 4 Nov 2026 17:16:03 -0500 Subject: [PATCH 32/40] fix(behaviourtest): count completed agent jobs in waiting runs Signed-off-by: Dharit Shah --- internal/forge/github/trace_identity_test.go | 34 +++++++++++ .../telemetry/tracecontext/identity_test.go | 14 ----- .../ci/githubactions/dispatch_reads_test.go | 58 +++++++++++++++++++ .../drivers/ci/githubactions/githubactions.go | 35 ++++++++--- 4 files changed, 118 insertions(+), 23 deletions(-) diff --git a/internal/forge/github/trace_identity_test.go b/internal/forge/github/trace_identity_test.go index d5e8648a55..3ed419a9f7 100644 --- a/internal/forge/github/trace_identity_test.go +++ b/internal/forge/github/trace_identity_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "testing" + "github.com/fullsend-ai/fullsend/internal/telemetry/tracecontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -74,6 +75,39 @@ func TestCreateChangeProposal_CapturesImmutableID(t *testing.T) { assert.Equal(t, 12, cp.Number) } +// TestGetIssue_RenameKeepsIdentity covers the D01 rename rule at the +// adapter boundary: a title change on the same immutable ID must not +// change trace identity. +func TestGetIssue_RenameKeepsIdentity(t *testing.T) { + title := "Widget is broken" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 2468913570, + "number": 7, + "title": title, + "html_url": "https://github.com/org/repo/issues/7", + "state": "open", + "labels": []any{}, + }) + })) + defer srv.Close() + + client := newTestClient(t, srv) + identity := func() tracecontext.Identity { + issue, err := client.GetIssue(context.Background(), "org", "repo", 7) + require.NoError(t, err) + return tracecontext.Identity{ + Instance: "https://github.com", + Container: 274390431, + Kind: tracecontext.KindWorkItem, + Entity: issue.ID, + } + } + before := identity() + title = "Widget is fixed (renamed)" + assert.Equal(t, before, identity(), "a rename must not change trace identity") +} + func TestListRepoPullRequests_CapturesImmutableID(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode([]map[string]any{{ diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index 69e50387ac..ba8e6a0199 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -120,20 +120,6 @@ func TestIdentity_Resolved(t *testing.T) { assert.True(t, v01Identity().Resolved()) } -// TestDeriveFallback_RenameStable documents the D01 rename rule: display -// names never enter the tuple, so a rename cannot change the binding. Two -// identities built from different display names for the same database IDs -// are the same identity. -func TestDeriveFallback_RenameStable(t *testing.T) { - before, ok := DeriveFallback(v01Identity()) - require.True(t, ok) - - renamed := v01Identity() // same database IDs; only display names changed - after, ok := DeriveFallback(renamed) - require.True(t, ok) - assert.Equal(t, before, after, "a rename must not change trace identity") -} - // TestDeriveFallback_MoveIsNewBinding documents the D01 move rule: moving an // entity to another bound container changes the binding (container or // entity database ID), which is a new identity, never a rename. diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index 34d24f3c78..f286e3dcb3 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -157,6 +157,64 @@ func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { } } +// TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob pins the +// count-side rule: a workflow waiting on an environment approval can +// already hold a completed agent job, which is conclusive dispatch +// evidence — the count must not wait out the whole run. +func TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + job forge.WorkflowJob + count int + pend int + }{ + { + name: "completed agent job counts", + job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}, + count: 1, + }, + { + name: "running agent job stays pending", + job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "in_progress"}, + pend: 1, + }, + { + name: "no agent job yet stays pending", + job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Route", Status: "completed", Conclusion: "success"}, + pend: 1, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + fake := forge.NewFakeClient() + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { + {ID: 1, RunAttempt: 1, Status: "waiting", CreatedAt: after.Format(time.RFC3339)}, + }} + fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{1: {tc.job}} + d := &Driver{Client: fake} + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) + require.NoError(t, err) + assert.Equal(t, tc.count, count) + assert.Equal(t, tc.pend, pending) + }) + } + t.Run("absent jobs listing stays pending", func(t *testing.T) { + t.Parallel() + fake := forge.NewFakeClient() + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { + {ID: 1, RunAttempt: 1, Status: "waiting", CreatedAt: after.Format(time.RFC3339)}, + }} + fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingAbsent + d := &Driver{Client: fake} + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) + require.NoError(t, err) + assert.Zero(t, count) + assert.Equal(t, 1, pending) + }) +} + func TestCountHarnessDispatches_CompletedRunJobsBecomeVisible(t *testing.T) { t.Parallel() after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 9aa2495705..952f4f276e 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1607,17 +1607,27 @@ func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent } } -// runNotStarted reports whether a workflow run has not begun executing. -// Its jobs listing cannot classify a dispatch and can still 404 while the -// run is queued, awaiting approval, or waiting on another run. -func runNotStarted(status string) bool { +// runUnstarted reports whether a workflow run is queued before any job +// can run. Its jobs listing cannot classify a dispatch and can still 404 +// while the run sits in the queue. +func runUnstarted(status string) bool { switch status { - case "queued", "waiting", "requested", "pending": + case "queued", "requested", "pending": return true } return false } +// runNotStarted reports whether a workflow run has not begun executing, +// including a run waiting on an environment approval whose earlier jobs +// may already have run. The negative assertion tolerates a first-page +// absent jobs listing for these runs; the count path additionally reads +// waiting runs, because a completed agent job in a waiting run is +// conclusive dispatch evidence. +func runNotStarted(status string) bool { + return runUnstarted(status) || status == "waiting" +} + // settleHarnessDispatchCount classifies harness runs created after the // trigger time into counted dispatches and pending runs. A run is pending // when its agent job exists but has not completed, or when the run itself @@ -1644,9 +1654,9 @@ func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, ag if r.Status == "completed" && r.Conclusion == "skipped" { continue } - if runNotStarted(r.Status) { - // A run that has not started cannot show agent work, so it is - // pending whatever the jobs listing would say. + if runUnstarted(r.Status) { + // A run queued before any job can run cannot show agent work, + // so it is pending whatever the jobs listing would say. pending++ continue } @@ -1654,7 +1664,14 @@ func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, ag if !cached { jobs, err = d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { - return 0, 0, err + // A waiting run can follow jobs that already ran + // (environment approval); when its listing is not + // available the run is still settling, not an error. + if !(r.Status == "waiting" && errors.Is(err, forge.ErrJobsListingAbsent)) { + return 0, 0, err + } + pending++ + continue } } hasJob, job := matchAgentJob(jobs, agent) From 0d541db9fa8573e0556c17fe08284e58cb8df807 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 5 Nov 2026 08:57:27 -0500 Subject: [PATCH 33/40] refactor(forge): name the first-page jobs 404 for its response shape The sentinel previously asserted that a not-found jobs listing was absent. Forges have been observed to 404 page 1 for runs that have not started, but the cause is unverified, and the driver's tolerance is gated on run status rather than on the sentinel alone. Rename it to ErrJobsListingNotFoundFirstPage and state the observation, the unverified cause, and that absence still depends on run status (issue #9124). No behaviour change. Signed-off-by: Dharit Shah --- internal/forge/forge.go | 18 ++++++++++------ internal/forge/github/github.go | 10 +++++---- internal/forge/github/github_test.go | 18 ++++++++-------- internal/forge/gitlab/ci.go | 10 +++++---- internal/forge/gitlab/methods_test.go | 20 +++++++++--------- .../ci/githubactions/dispatch_reads_test.go | 11 +++++----- .../drivers/ci/githubactions/githubactions.go | 21 +++++++++++-------- 7 files changed, 61 insertions(+), 47 deletions(-) diff --git a/internal/forge/forge.go b/internal/forge/forge.go index d8be8bb6cb..9b41e26471 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -249,12 +249,18 @@ func ValidatePipelineVarOverrideRole(role string) error { // ErrNotFound indicates a requested resource was not found on the forge. var ErrNotFound = errors.New("not found") -// ErrJobsListingAbsent indicates that a workflow run's jobs listing was -// reported not found on its first page — for example, a run that has not -// started yet. Adapters attach it only to first-page not-founds: a -// not-found on a later page means the listing was already partially -// readable and must never be read as absence. -var ErrJobsListingAbsent = errors.New("workflow run jobs listing absent") +// ErrJobsListingNotFoundFirstPage reports that a workflow run's jobs +// listing returned not found on its first page. Forges have been observed +// to do this for runs that have not started; the cause is unverified (see +// https://github.com/fullsend-ai/fullsend/issues/9124). The sentinel +// describes the response shape only and does not establish that the +// listing — or the run — is absent: callers may treat it as absence only +// when the run status independently shows the run has not started. +// +// Adapters attach it only to first-page not-founds. A not-found on a later +// page means the listing was already partially readable and may hold a +// completed job, so it never carries this sentinel. +var ErrJobsListingNotFoundFirstPage = errors.New("workflow run jobs listing not found on first page") // IsNotFound reports whether err indicates a resource was not found. func IsNotFound(err error) bool { diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 365d7f3fc6..832c0d071b 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -4448,10 +4448,12 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string label := fmt.Sprintf("list workflow run jobs for %s/%s run %d page %d", owner, repo, runID, page) if err := c.getCachedJSON(ctx, path, &result); err != nil { if page == 1 && forge.IsNotFound(err) { - // First-page absence means the run's listing does not exist - // yet; a later-page 404 is a partially readable listing and - // must not be readable as absence. - return nil, fmt.Errorf("%s: %w: %w", label, forge.ErrJobsListingAbsent, err) + // GitHub has been observed to 404 the first page for runs + // that have not started; the cause is unverified (#9124). + // Report the shape only — absence still depends on the run + // status. A later-page 404 is a partially readable listing + // and never carries the sentinel. + return nil, fmt.Errorf("%s: %w: %w", label, forge.ErrJobsListingNotFoundFirstPage, err) } return nil, fmt.Errorf("%s: %w", label, err) } diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 3e565e93d1..375d6225fe 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -5158,20 +5158,20 @@ func TestListWorkflowRunJobs_NotFound(t *testing.T) { assert.Equal(t, tt.status, apiErr.StatusCode) assert.Equal(t, tt.status == http.StatusNotFound, forge.IsNotFound(err)) if tt.status == http.StatusNotFound { - assert.ErrorIs(t, err, forge.ErrJobsListingAbsent, "a first-page absence is marked as the listing being absent") + assert.ErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) } else { - assert.NotErrorIs(t, err, forge.ErrJobsListingAbsent) + assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) } }) } } -// TestListWorkflowRunJobs_LaterPageNotFoundIsNotAbsence is a regression -// test: a 404 on a later pagination page means the listing was partially -// readable — page 1 may already hold jobs — so it must not carry -// ErrJobsListingAbsent, which callers tolerate as a not-yet-started run's -// absent listing. -func TestListWorkflowRunJobs_LaterPageNotFoundIsNotAbsence(t *testing.T) { +// TestListWorkflowRunJobs_LaterPageNotFoundDoesNotCarrySentinel is a +// regression test: a 404 on a later pagination page means the listing was +// partially readable — page 1 may already hold jobs — so it must not carry +// ErrJobsListingNotFoundFirstPage, which callers tolerate only when the run +// status independently shows the run has not started. +func TestListWorkflowRunJobs_LaterPageNotFoundDoesNotCarrySentinel(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Query().Get("page") { case "1": @@ -5191,7 +5191,7 @@ func TestListWorkflowRunJobs_LaterPageNotFoundIsNotAbsence(t *testing.T) { require.Error(t, err) assert.Nil(t, jobs) assert.True(t, forge.IsNotFound(err), "the 404 stays classified as not found") - assert.NotErrorIs(t, err, forge.ErrJobsListingAbsent, "a partially readable listing is never absence") + assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage, "a partially readable listing never carries the sentinel") assert.Contains(t, err.Error(), "page 2") } diff --git a/internal/forge/gitlab/ci.go b/internal/forge/gitlab/ci.go index 9277fcbb9b..e2a9b5f8ab 100644 --- a/internal/forge/gitlab/ci.go +++ b/internal/forge/gitlab/ci.go @@ -924,10 +924,12 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string resp, err := c.get(ctx, path) if err != nil { if page == 1 && forge.IsNotFound(err) { - // First-page absence means the pipeline's job listing does - // not exist yet; a later-page 404 is a partially readable - // listing and must not be readable as absence. - return nil, fmt.Errorf("list pipeline jobs page %d: %w: %w", page, forge.ErrJobsListingAbsent, err) + // GitLab has been observed to 404 the first page for + // pipelines that have not started; the cause is unverified + // (#9124). Report the shape only — absence still depends on + // the run status. A later-page 404 is a partially readable + // listing and never carries the sentinel. + return nil, fmt.Errorf("list pipeline jobs page %d: %w: %w", page, forge.ErrJobsListingNotFoundFirstPage, err) } return nil, fmt.Errorf("list pipeline jobs page %d: %w", page, err) } diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index dd40c499ed..05d11dba93 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -4006,15 +4006,15 @@ func TestListWorkflowRunJobs_Error(t *testing.T) { }) _, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) require.Error(t, err) - assert.NotErrorIs(t, err, forge.ErrJobsListingAbsent) + assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) } -// TestListWorkflowRunJobs_FirstPageNotFoundMarksAbsence covers the -// not-found classification adapters attach to a first-page absence, and -// the later-page 404 that must not carry it: a partially readable -// listing is never absence. -func TestListWorkflowRunJobs_FirstPageNotFoundMarksAbsence(t *testing.T) { - t.Run("first page 404 is absence", func(t *testing.T) { +// TestListWorkflowRunJobs_FirstPageNotFoundCarriesSentinel covers the +// not-found classification adapters attach to a first-page 404, and the +// later-page 404 that must not carry it: page 1 was already readable and +// may hold a completed job. +func TestListWorkflowRunJobs_FirstPageNotFoundCarriesSentinel(t *testing.T) { + t.Run("first page 404 carries the sentinel", func(t *testing.T) { client, mux := setupTest(t) mux.HandleFunc("/api/v4/projects/o%2Fr/pipelines/10/jobs", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) @@ -4022,9 +4022,9 @@ func TestListWorkflowRunJobs_FirstPageNotFoundMarksAbsence(t *testing.T) { _, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) require.Error(t, err) assert.ErrorIs(t, err, forge.ErrNotFound) - assert.ErrorIs(t, err, forge.ErrJobsListingAbsent, "a first-page absence is marked as the listing being absent") + assert.ErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) }) - t.Run("later page 404 is not absence", func(t *testing.T) { + t.Run("later page 404 does not carry it", func(t *testing.T) { client, mux := setupTest(t) mux.HandleFunc("/api/v4/projects/o%2Fr/pipelines/10/jobs", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") @@ -4044,7 +4044,7 @@ func TestListWorkflowRunJobs_FirstPageNotFoundMarksAbsence(t *testing.T) { require.Error(t, err) assert.Nil(t, jobs) assert.ErrorIs(t, err, forge.ErrNotFound, "the 404 stays classified as not found") - assert.NotErrorIs(t, err, forge.ErrJobsListingAbsent, "a partially readable listing is never absence") + assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage, "a partially readable listing never carries the sentinel") assert.Contains(t, err.Error(), "page 2") }) } diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index f286e3dcb3..5764984e86 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -120,8 +120,9 @@ func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { {ID: 1, Status: status, CreatedAt: after.Format(time.RFC3339)}, }} - // The count path never reads jobs for a not-started run. - fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingAbsent + // A queued run is pending without a jobs read; a waiting run + // reads the listing and stays pending when it 404s on page 1. + fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingNotFoundFirstPage d := &Driver{Client: fake} count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) @@ -129,8 +130,8 @@ func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { assert.Zero(t, count) assert.Equal(t, 1, pending) - // The negative assertion reads the listing and tolerates only a - // first-page absence: the listing can 404 before the run starts. + // The negative assertion reads the listing and tolerates the + // first-page 404 only when the run has not started. require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) // A 404 on a later page means the listing was partially read — @@ -206,7 +207,7 @@ func TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob(t *testing.T) { fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { {ID: 1, RunAttempt: 1, Status: "waiting", CreatedAt: after.Format(time.RFC3339)}, }} - fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingAbsent + fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingNotFoundFirstPage d := &Driver{Client: fake} count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) require.NoError(t, err) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 952f4f276e..acf2680660 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1665,9 +1665,10 @@ func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, ag jobs, err = d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { // A waiting run can follow jobs that already ran - // (environment approval); when its listing is not - // available the run is still settling, not an error. - if !(r.Status == "waiting" && errors.Is(err, forge.ErrJobsListingAbsent)) { + // (environment approval). A first-page 404 is not evidence + // of absence on its own, but for a waiting run it leaves + // nothing to count yet, so the run stays pending. + if !(r.Status == "waiting" && errors.Is(err, forge.ErrJobsListingNotFoundFirstPage)) { return 0, 0, err } pending++ @@ -1862,12 +1863,14 @@ func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { // A run that has not started cannot hold agent work, and its - // jobs listing can be absent before the run starts — only a - // first-page absence is tolerated. A waiting run can follow - // jobs that already ran (environment approval), so its listing - // is checked like any other run's, and a listing that was - // partially read before a later-page 404 is never absence. - if !(runNotStarted(r.Status) && errors.Is(err, forge.ErrJobsListingAbsent)) { + // jobs listing has been observed to 404 on the first page + // before the run starts — only that shape is tolerated, and + // only when the status independently says not started. A + // waiting run can follow jobs that already ran (environment + // approval), so its listing is checked like any other run's. A + // later-page 404 means the listing was partially read and may + // hold a completed agent job, so it is never tolerated. + if !(runNotStarted(r.Status) && errors.Is(err, forge.ErrJobsListingNotFoundFirstPage)) { return err } continue From 89f0c04eeff79c49f1e5767948a6f6ccd2ae764d Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 5 Nov 2026 09:32:49 -0500 Subject: [PATCH 34/40] fix(behaviourtest): fail the negative assertion on a waiting run's unreadable jobs listing A waiting run can already hold a completed agent job, so skipping it when its jobs listing 404s on the first page could pass the negative assertion although an agent ran. Tolerate the first-page sentinel only for runs that have not started; a waiting run's unreadable listing now fails the assertion. RED reproduced the false pass before the change. Signed-off-by: Dharit Shah --- .../ci/githubactions/dispatch_reads_test.go | 10 +++++++-- .../drivers/ci/githubactions/githubactions.go | 22 +++++-------------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index 5764984e86..e74938a5f9 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -131,8 +131,14 @@ func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { assert.Equal(t, 1, pending) // The negative assertion reads the listing and tolerates the - // first-page 404 only when the run has not started. - require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) + // first-page 404 only for a run that has not started. A waiting + // run can already hold a completed agent job, so an unreadable + // listing must fail the assertion rather than skip the run. + if status == "waiting" { + require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), forge.ErrJobsListingNotFoundFirstPage) + } else { + require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) + } // A 404 on a later page means the listing was partially read — // page 1 may hold a completed agent job — so it is never diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index acf2680660..07b6fa258c 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1618,16 +1618,6 @@ func runUnstarted(status string) bool { return false } -// runNotStarted reports whether a workflow run has not begun executing, -// including a run waiting on an environment approval whose earlier jobs -// may already have run. The negative assertion tolerates a first-page -// absent jobs listing for these runs; the count path additionally reads -// waiting runs, because a completed agent job in a waiting run is -// conclusive dispatch evidence. -func runNotStarted(status string) bool { - return runUnstarted(status) || status == "waiting" -} - // settleHarnessDispatchCount classifies harness runs created after the // trigger time into counted dispatches and pending runs. A run is pending // when its agent job exists but has not completed, or when the run itself @@ -1865,12 +1855,12 @@ func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, // A run that has not started cannot hold agent work, and its // jobs listing has been observed to 404 on the first page // before the run starts — only that shape is tolerated, and - // only when the status independently says not started. A - // waiting run can follow jobs that already ran (environment - // approval), so its listing is checked like any other run's. A - // later-page 404 means the listing was partially read and may - // hold a completed agent job, so it is never tolerated. - if !(runNotStarted(r.Status) && errors.Is(err, forge.ErrJobsListingNotFoundFirstPage)) { + // only for those statuses. A waiting run can follow jobs that + // already ran (environment approval), so an unreadable listing + // fails the assertion rather than skipping the run. A later-page + // 404 means the listing was partially read and may hold a + // completed agent job, so it is never tolerated. + if !(runUnstarted(r.Status) && errors.Is(err, forge.ErrJobsListingNotFoundFirstPage)) { return err } continue From 920f4dbb671d000cd24de0e9e77a3f49a2aed8af Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 5 Nov 2026 09:38:25 -0500 Subject: [PATCH 35/40] refactor(behaviourtest): classify jobs listing errors in one place The dispatch-count and negative-assertion paths each carried their own status predicates for tolerating jobs-listing errors, and review rounds kept finding drift between them. Route both through a single classifyJobsError(status, err) returning skip, retryLater, or fatal, with the count path keeping retryable runs pending and the one-shot negative path failing closed on them. An exhaustive status-by-error matrix test pins the table, so changes are semantic decisions rather than silent drift. No behaviour change. Signed-off-by: Dharit Shah --- .../ci/githubactions/dispatch_reads_test.go | 34 +++++++++ .../drivers/ci/githubactions/githubactions.go | 75 ++++++++++++++----- 2 files changed, 90 insertions(+), 19 deletions(-) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index e74938a5f9..b8c886c461 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -168,6 +168,40 @@ func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { // count-side rule: a workflow waiting on an environment approval can // already hold a completed agent job, which is conclusive dispatch // evidence — the count must not wait out the whole run. +// TestClassifyJobsError pins the full status × listing-error table that +// both dispatch paths route through. Changing an entry here is a +// semantic decision about run statuses, not a mechanical drift fix. +func TestClassifyJobsError(t *testing.T) { + t.Parallel() + firstPage404 := fmt.Errorf("list workflow run jobs page 1: %w: %w", forge.ErrJobsListingNotFoundFirstPage, forge.ErrNotFound) + laterPage404 := fmt.Errorf("list workflow run jobs page 2: %w", forge.ErrNotFound) + otherErr := errors.New("jobs lookup failed") + for _, tc := range []struct { + name string + status string + err error + want jobsReadOutcome + }{ + {"queued first-page 404 skips", "queued", firstPage404, jobsSkipRun}, + {"requested first-page 404 skips", "requested", firstPage404, jobsSkipRun}, + {"pending first-page 404 skips", "pending", firstPage404, jobsSkipRun}, + {"waiting first-page 404 retries later", "waiting", firstPage404, jobsRetryLater}, + {"in_progress first-page 404 is fatal", "in_progress", firstPage404, jobsFatal}, + {"completed first-page 404 is fatal", "completed", firstPage404, jobsFatal}, + {"queued later-page 404 is fatal", "queued", laterPage404, jobsFatal}, + {"waiting later-page 404 is fatal", "waiting", laterPage404, jobsFatal}, + {"completed later-page 404 is fatal", "completed", laterPage404, jobsFatal}, + {"queued other error is fatal", "queued", otherErr, jobsFatal}, + {"waiting other error is fatal", "waiting", otherErr, jobsFatal}, + {"completed other error is fatal", "completed", otherErr, jobsFatal}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, classifyJobsError(tc.status, tc.err)) + }) + } +} + func TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob(t *testing.T) { t.Parallel() after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 07b6fa258c..5559bfe8bc 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1618,6 +1618,49 @@ func runUnstarted(status string) bool { return false } +// jobsReadOutcome classifies a workflow run whose jobs listing could not +// be read. +type jobsReadOutcome int + +const ( + // jobsSkipRun: the run cannot hold agent work yet, so the caller + // ignores it — no dispatch, no violation. + jobsSkipRun jobsReadOutcome = iota + // jobsRetryLater: the run may hold agent work but its listing is not + // readable yet. A settling caller keeps the run pending; a one-shot + // caller fails closed, because an unreadable listing is not evidence + // that no agent job ran. + jobsRetryLater + // jobsFatal: the listing error is unexpected and must fail the caller. + jobsFatal +) + +// classifyJobsError is the only place that maps a run's status and a +// jobs-listing error to a tolerance rule. The dispatch-count and +// negative-assertion paths both route their listing errors through it +// and must not grow status predicates of their own. +// +// A run that has not started cannot hold agent work, and its listing has +// been observed to 404 on the first page before the run starts, so that +// shape skips the run. A waiting run — one held on an environment +// approval — can already hold a completed agent job, so its unreadable +// listing is retry material, never evidence of absence. Any other error +// is fatal; in particular a later-page 404 means page 1 was already +// readable and may hold a completed agent job, so it is never tolerated. +func classifyJobsError(status string, err error) jobsReadOutcome { + if !errors.Is(err, forge.ErrJobsListingNotFoundFirstPage) { + return jobsFatal + } + switch { + case runUnstarted(status): + return jobsSkipRun + case status == "waiting": + return jobsRetryLater + default: + return jobsFatal + } +} + // settleHarnessDispatchCount classifies harness runs created after the // trigger time into counted dispatches and pending runs. A run is pending // when its agent job exists but has not completed, or when the run itself @@ -1645,8 +1688,9 @@ func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, ag continue } if runUnstarted(r.Status) { - // A run queued before any job can run cannot show agent work, - // so it is pending whatever the jobs listing would say. + // classifyJobsError would skip these runs anyway; skipping + // before the read also avoids a listing call that 404s while + // the run sits in the queue. pending++ continue } @@ -1654,15 +1698,13 @@ func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, ag if !cached { jobs, err = d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { - // A waiting run can follow jobs that already ran - // (environment approval). A first-page 404 is not evidence - // of absence on its own, but for a waiting run it leaves - // nothing to count yet, so the run stays pending. - if !(r.Status == "waiting" && errors.Is(err, forge.ErrJobsListingNotFoundFirstPage)) { - return 0, 0, err + // Settling, so both skippable and retryable runs stay + // pending rather than fail the count. + if outcome := classifyJobsError(r.Status, err); outcome == jobsSkipRun || outcome == jobsRetryLater { + pending++ + continue } - pending++ - continue + return 0, 0, err } } hasJob, job := matchAgentJob(jobs, agent) @@ -1852,15 +1894,10 @@ func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, } jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { - // A run that has not started cannot hold agent work, and its - // jobs listing has been observed to 404 on the first page - // before the run starts — only that shape is tolerated, and - // only for those statuses. A waiting run can follow jobs that - // already ran (environment approval), so an unreadable listing - // fails the assertion rather than skipping the run. A later-page - // 404 means the listing was partially read and may hold a - // completed agent job, so it is never tolerated. - if !(runUnstarted(r.Status) && errors.Is(err, forge.ErrJobsListingNotFoundFirstPage)) { + // One-shot, so only a run that cannot hold agent work yet is + // skipped: an unreadable listing is not evidence that no + // agent job ran, so retryable and fatal both fail closed. + if classifyJobsError(r.Status, err) != jobsSkipRun { return err } continue From 7fae148f74611a7dd64d65674701c5df9693142b Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 5 Nov 2026 11:13:23 -0500 Subject: [PATCH 36/40] refactor(behaviourtest): restore main's dispatch assertions and jobs listing The dispatch-assertion rework and the workflow-jobs error handling are a behaviour-test reliability change, separate from the trace-context foundation. Restore main's GitHub Actions driver, ListWorkflowRunJobs, and workflow run types, and remove the first-page not-found sentinel and its tests. The change moves to its own issue and pull request. Signed-off-by: Dharit Shah --- docs/contributing/forge-abstraction.md | 10 - internal/forge/forge.go | 15 - internal/forge/github/github.go | 23 +- internal/forge/github/github_test.go | 129 ------- .../forge/github/workflow_attempt_test.go | 59 --- internal/forge/gitlab/ci.go | 8 - internal/forge/gitlab/methods_test.go | 41 -- .../ci/githubactions/dispatch_reads_test.go | 359 ------------------ .../drivers/ci/githubactions/githubactions.go | 114 +----- .../ci/githubactions/githubactions_test.go | 32 +- 10 files changed, 14 insertions(+), 776 deletions(-) delete mode 100644 internal/forge/github/workflow_attempt_test.go delete mode 100644 pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go diff --git a/docs/contributing/forge-abstraction.md b/docs/contributing/forge-abstraction.md index 308540e7a1..380dcea2fa 100644 --- a/docs/contributing/forge-abstraction.md +++ b/docs/contributing/forge-abstraction.md @@ -14,16 +14,6 @@ All git forge operations (GitHub API calls, PR comments, issue creation, workflo **FakeClient coverage:** Every exported `FakeClient` method must have an entry in `fakeClientCalls` in [`internal/forge/fake_test.go`](../../internal/forge/fake_test.go). `TestFakeClient_ErrorInjection` uses that table to assert each method returns its injected error, `TestFakeClient_ThreadSafety` runs it concurrently under `-race`, and `TestFakeClient_CoversAllMethods` fails when an entry is missing or stale. Fake methods must return copies, never slices, maps, or pointers into the fake's own storage: callers read results without holding the fake's lock. Likewise, store copies of caller-supplied slices and maps that a fake method later changes in place: callers keep their own reference. -**Workflow attempts:** `WorkflowRun.RunAttempt` and `WorkflowJob.RunAttempt` -identify executions when a forge reuses a run ID for reruns. Zero means the -attempt is unavailable. The GitHub Actions dispatch-count assertion reuses -completed job listings only within that assertion, for unchanged run metadata -and completed jobs whose known attempt matches the run. Reuse also requires -a matching agent job with a nonempty, non-skipped, non-cancelled conclusion: -that job already establishes a counted dispatch. Listings without that -evidence, unknown attempts, and unfinished jobs are read again on subsequent -polls because an absent job may become visible later. - **When reviewing PRs:** Flag any direct `exec.Command("gh", ...)`, raw GitHub API calls, or other forge-specific operations outside `internal/forge/github/` as a medium-severity or higher finding. This is an architectural violation, not a style preference. **Composite action (`action.yml`):** The forge abstraction extends to `action.yml` bash scripts. New GitHub API operations in action steps should be implemented as `fullsend` CLI subcommands (under `internal/cli/`) that use `forge.Client`, not as inline `gh api` calls. Existing `gh api` calls in `action.yml` that predate this rule are grandfathered but should be migrated when touched. diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 9b41e26471..3967ef0e2b 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -249,19 +249,6 @@ func ValidatePipelineVarOverrideRole(role string) error { // ErrNotFound indicates a requested resource was not found on the forge. var ErrNotFound = errors.New("not found") -// ErrJobsListingNotFoundFirstPage reports that a workflow run's jobs -// listing returned not found on its first page. Forges have been observed -// to do this for runs that have not started; the cause is unverified (see -// https://github.com/fullsend-ai/fullsend/issues/9124). The sentinel -// describes the response shape only and does not establish that the -// listing — or the run — is absent: callers may treat it as absence only -// when the run status independently shows the run has not started. -// -// Adapters attach it only to first-page not-founds. A not-found on a later -// page means the listing was already partially readable and may hold a -// completed job, so it never carries this sentinel. -var ErrJobsListingNotFoundFirstPage = errors.New("workflow run jobs listing not found on first page") - // IsNotFound reports whether err indicates a resource was not found. func IsNotFound(err error) bool { return errors.Is(err, ErrNotFound) @@ -546,7 +533,6 @@ type PullRequestInfo struct { // WorkflowRun represents a CI/CD workflow execution. type WorkflowRun struct { ID int - RunAttempt int // Attempt number for a rerunnable execution; zero when unavailable. Name string Event string // GitHub trigger event, e.g. "issues", "issue_comment" Status string // "queued", "in_progress", "completed" @@ -558,7 +544,6 @@ type WorkflowRun struct { // WorkflowJob represents a job within a workflow run. type WorkflowJob struct { ID int - RunAttempt int // Execution attempt containing this job; zero when unavailable. Name string Status string // "queued", "in_progress", "completed" Conclusion string // "success", "failure", "cancelled", etc. diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 832c0d071b..c22055adbe 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -3208,7 +3208,6 @@ func (c *LiveClient) GetLatestWorkflowRun(ctx context.Context, owner, repo, work var result struct { WorkflowRuns []struct { ID int `json:"id"` - RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -3228,7 +3227,6 @@ func (c *LiveClient) GetLatestWorkflowRun(ctx context.Context, owner, repo, work run := result.WorkflowRuns[0] return &forge.WorkflowRun{ ID: run.ID, - RunAttempt: run.RunAttempt, Name: run.Name, Event: run.Event, Status: run.Status, @@ -3247,7 +3245,6 @@ func (c *LiveClient) GetWorkflowRun(ctx context.Context, owner, repo string, run var run struct { ID int `json:"id"` - RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -3261,7 +3258,6 @@ func (c *LiveClient) GetWorkflowRun(ctx context.Context, owner, repo string, run return &forge.WorkflowRun{ ID: run.ID, - RunAttempt: run.RunAttempt, Name: run.Name, Event: run.Event, Status: run.Status, @@ -4290,7 +4286,6 @@ func (c *LiveClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow var result struct { WorkflowRuns []struct { ID int `json:"id"` - RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4306,7 +4301,6 @@ func (c *LiveClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow for i, r := range result.WorkflowRuns { runs[i] = forge.WorkflowRun{ ID: r.ID, - RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4335,7 +4329,6 @@ func (c *LiveClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, wor var result struct { WorkflowRuns []struct { ID int `json:"id"` - RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4360,7 +4353,6 @@ func (c *LiveClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, wor } all = append(all, forge.WorkflowRun{ ID: r.ID, - RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4387,7 +4379,6 @@ func (c *LiveClient) ListRecentWorkflowRuns(ctx context.Context, owner, repo str var result struct { WorkflowRuns []struct { ID int `json:"id"` - RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4403,7 +4394,6 @@ func (c *LiveClient) ListRecentWorkflowRuns(ctx context.Context, owner, repo str for i, r := range result.WorkflowRuns { runs[i] = forge.WorkflowRun{ ID: r.ID, - RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4437,7 +4427,6 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string var result struct { Jobs []struct { ID int `json:"id"` - RunAttempt int `json:"run_attempt"` Name string `json:"name"` Status string `json:"status"` Conclusion string `json:"conclusion"` @@ -4445,17 +4434,8 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string } path := fmt.Sprintf("/repos/%s/%s/actions/runs/%d/jobs?per_page=%d&page=%d", url.PathEscape(owner), url.PathEscape(repo), runID, perPage, page) - label := fmt.Sprintf("list workflow run jobs for %s/%s run %d page %d", owner, repo, runID, page) if err := c.getCachedJSON(ctx, path, &result); err != nil { - if page == 1 && forge.IsNotFound(err) { - // GitHub has been observed to 404 the first page for runs - // that have not started; the cause is unverified (#9124). - // Report the shape only — absence still depends on the run - // status. A later-page 404 is a partially readable listing - // and never carries the sentinel. - return nil, fmt.Errorf("%s: %w: %w", label, forge.ErrJobsListingNotFoundFirstPage, err) - } - return nil, fmt.Errorf("%s: %w", label, err) + return nil, fmt.Errorf("list workflow run jobs page %d: %w", page, err) } if len(result.Jobs) == 0 { return jobs, nil @@ -4463,7 +4443,6 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string for _, j := range result.Jobs { jobs = append(jobs, forge.WorkflowJob{ ID: j.ID, - RunAttempt: j.RunAttempt, Name: j.Name, Status: j.Status, Conclusion: j.Conclusion, diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 375d6225fe..a530cba63a 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -5114,104 +5114,6 @@ func TestListWorkflowRunJobs_APIError(t *testing.T) { require.Error(t, err) } -func TestListWorkflowRunJobs_NotFound(t *testing.T) { - for _, tt := range []struct { - name string - status int - failures int - }{ - {name: "404 is not presumed transient", status: http.StatusNotFound, failures: 1}, - {name: "persistent 404 fails immediately", status: http.StatusNotFound, failures: 5}, - {name: "permission failure is not retried", status: http.StatusForbidden, failures: 5}, - } { - t.Run(tt.name, func(t *testing.T) { - calls := 0 - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - assert.Equal(t, "/repos/org/repo/actions/runs/42/jobs", r.URL.Path) - assert.Equal(t, "1", r.URL.Query().Get("page")) - if calls <= tt.failures { - w.WriteHeader(tt.status) - return - } - _, _ = io.WriteString(w, `{"jobs":[{"id":1,"name":"dispatch / Fix","status":"completed","conclusion":"success"}]}`) - })) - defer srv.Close() - - waits := 0 - client := newTestClient(t, srv).WithAfterFunc(func(time.Duration) <-chan time.Time { - waits++ - ch := make(chan time.Time, 1) - ch <- time.Now() - return ch - }) - jobs, err := client.ListWorkflowRunJobs(context.Background(), "org", "repo", 42) - assert.Equal(t, 1, calls) - assert.Zero(t, waits, "jobs errors must not add retry delays") - require.Error(t, err) - assert.Nil(t, jobs) - assert.Contains(t, err.Error(), "org/repo") - assert.Contains(t, err.Error(), "run 42") - assert.Contains(t, err.Error(), "page 1") - var apiErr *APIError - require.ErrorAs(t, err, &apiErr) - assert.Equal(t, tt.status, apiErr.StatusCode) - assert.Equal(t, tt.status == http.StatusNotFound, forge.IsNotFound(err)) - if tt.status == http.StatusNotFound { - assert.ErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) - } else { - assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) - } - }) - } -} - -// TestListWorkflowRunJobs_LaterPageNotFoundDoesNotCarrySentinel is a -// regression test: a 404 on a later pagination page means the listing was -// partially readable — page 1 may already hold jobs — so it must not carry -// ErrJobsListingNotFoundFirstPage, which callers tolerate only when the run -// status independently shows the run has not started. -func TestListWorkflowRunJobs_LaterPageNotFoundDoesNotCarrySentinel(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Query().Get("page") { - case "1": - jobs := make([]map[string]any, 100) // full page forces page 2 - for i := range jobs { - jobs[i] = map[string]any{"id": i + 1, "name": "dispatch / Harness run (fix)", "status": "completed", "conclusion": "success"} - } - json.NewEncoder(w).Encode(map[string]any{"jobs": jobs}) - default: - w.WriteHeader(http.StatusNotFound) - } - })) - defer srv.Close() - - client := newTestClient(t, srv) - jobs, err := client.ListWorkflowRunJobs(context.Background(), "org", "repo", 42) - require.Error(t, err) - assert.Nil(t, jobs) - assert.True(t, forge.IsNotFound(err), "the 404 stays classified as not found") - assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage, "a partially readable listing never carries the sentinel") - assert.Contains(t, err.Error(), "page 2") -} - -func TestListWorkflowRunJobs_CancelledContext(t *testing.T) { - calls := 0 - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - calls++ - w.WriteHeader(http.StatusNotFound) - })) - defer srv.Close() - ctx, cancel := context.WithCancel(context.Background()) - cancel() - client := newTestClient(t, srv) - - jobs, err := client.ListWorkflowRunJobs(ctx, "org", "repo", 42) - require.ErrorIs(t, err, context.Canceled) - assert.Nil(t, jobs) - assert.Zero(t, calls) -} - // TestListWorkflowRunJobs_PaginatesBeyondFirstPage is a regression test // (#7996 review): ListWorkflowRunJobs previously issued a single // per_page=100 request with no pagination, so a run with more than 100 @@ -5261,37 +5163,6 @@ func TestListWorkflowRunJobs_PaginatesBeyondFirstPage(t *testing.T) { assert.Len(t, pageRequests, 2, "pagination must stop once a short page is seen") } -func TestListWorkflowRunJobs_MissingPageFailsWithoutPartialResults(t *testing.T) { - var pages []string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - page := r.URL.Query().Get("page") - pages = append(pages, page) - assert.Equal(t, "/repos/org/repo/actions/runs/42/jobs", r.URL.Path) - if page == "1" { - jobs := make([]forge.WorkflowJob, 100) - for i := range jobs { - jobs[i].ID = i + 1 - } - _ = json.NewEncoder(w).Encode(map[string]any{"jobs": jobs}) - return - } - assert.Equal(t, "2", page) - if len(pages) == 2 { - w.WriteHeader(http.StatusNotFound) - return - } - _, _ = io.WriteString(w, `{"jobs":[{"id":101,"name":"dispatch / Fix"}]}`) - })) - defer srv.Close() - - jobs, err := newTestClient(t, srv).ListWorkflowRunJobs(context.Background(), "org", "repo", 42) - require.Error(t, err) - assert.True(t, forge.IsNotFound(err)) - assert.Contains(t, err.Error(), "org/repo run 42 page 2") - assert.Equal(t, []string{"1", "2"}, pages) - assert.Nil(t, jobs, "an incomplete listing must not look like absence of an agent") -} - // TestListWorkflowRunJobs_PaginationExceeded guards the maxPages safety // valve: if every page is full, pagination must stop with an error instead // of looping indefinitely. diff --git a/internal/forge/github/workflow_attempt_test.go b/internal/forge/github/workflow_attempt_test.go deleted file mode 100644 index dd62a804d3..0000000000 --- a/internal/forge/github/workflow_attempt_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package github - -import ( - "context" - "fmt" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/fullsend-ai/fullsend/internal/forge" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestWorkflowReaders_RunAttempt(t *testing.T) { - const run = `{"id":42,"run_attempt":2,"status":"completed","created_at":"2026-01-01T00:00:00Z"}` - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/repos/org/repo/actions/runs/42": - fmt.Fprint(w, run) - case "/repos/org/repo/actions/runs/42/jobs": - fmt.Fprintf(w, `{"jobs":[%s]}`, run) - default: - fmt.Fprintf(w, `{"workflow_runs":[%s]}`, run) - } - })) - defer srv.Close() - c := newTestClient(t, srv) - ctx := context.Background() - for name, read := range map[string]func() ([]forge.WorkflowRun, error){ - "latest": func() ([]forge.WorkflowRun, error) { - r, err := c.GetLatestWorkflowRun(ctx, "org", "repo", "fullsend.yaml") - require.NoError(t, err) - return []forge.WorkflowRun{*r}, nil - }, - "by ID": func() ([]forge.WorkflowRun, error) { - r, err := c.GetWorkflowRun(ctx, "org", "repo", 42) - require.NoError(t, err) - return []forge.WorkflowRun{*r}, nil - }, - "workflow": func() ([]forge.WorkflowRun, error) { return c.ListWorkflowRuns(ctx, "org", "repo", "fullsend.yaml") }, - "since": func() ([]forge.WorkflowRun, error) { - return c.ListWorkflowRunsSince(ctx, "org", "repo", "fullsend.yaml", time.Time{}) - }, - "recent": func() ([]forge.WorkflowRun, error) { return c.ListRecentWorkflowRuns(ctx, "org", "repo", 10) }, - } { - t.Run(name, func(t *testing.T) { - runs, err := read() - require.NoError(t, err) - require.Len(t, runs, 1) - assert.Equal(t, 2, runs[0].RunAttempt) - }) - } - jobs, err := c.ListWorkflowRunJobs(ctx, "org", "repo", 42) - require.NoError(t, err) - require.Len(t, jobs, 1) - assert.Equal(t, 2, jobs[0].RunAttempt) -} diff --git a/internal/forge/gitlab/ci.go b/internal/forge/gitlab/ci.go index e2a9b5f8ab..f28b1ca226 100644 --- a/internal/forge/gitlab/ci.go +++ b/internal/forge/gitlab/ci.go @@ -923,14 +923,6 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string proj, runID, perPage, page) resp, err := c.get(ctx, path) if err != nil { - if page == 1 && forge.IsNotFound(err) { - // GitLab has been observed to 404 the first page for - // pipelines that have not started; the cause is unverified - // (#9124). Report the shape only — absence still depends on - // the run status. A later-page 404 is a partially readable - // listing and never carries the sentinel. - return nil, fmt.Errorf("list pipeline jobs page %d: %w: %w", page, forge.ErrJobsListingNotFoundFirstPage, err) - } return nil, fmt.Errorf("list pipeline jobs page %d: %w", page, err) } var jobs []glJob diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index 05d11dba93..154ec3fa73 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -4006,47 +4006,6 @@ func TestListWorkflowRunJobs_Error(t *testing.T) { }) _, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) require.Error(t, err) - assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) -} - -// TestListWorkflowRunJobs_FirstPageNotFoundCarriesSentinel covers the -// not-found classification adapters attach to a first-page 404, and the -// later-page 404 that must not carry it: page 1 was already readable and -// may hold a completed job. -func TestListWorkflowRunJobs_FirstPageNotFoundCarriesSentinel(t *testing.T) { - t.Run("first page 404 carries the sentinel", func(t *testing.T) { - client, mux := setupTest(t) - mux.HandleFunc("/api/v4/projects/o%2Fr/pipelines/10/jobs", func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusNotFound) - }) - _, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) - require.Error(t, err) - assert.ErrorIs(t, err, forge.ErrNotFound) - assert.ErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) - }) - t.Run("later page 404 does not carry it", func(t *testing.T) { - client, mux := setupTest(t) - mux.HandleFunc("/api/v4/projects/o%2Fr/pipelines/10/jobs", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch r.URL.Query().Get("page") { - case "1": - jobs := make([]string, 100) - for i := range jobs { - jobs[i] = fmt.Sprintf(`{"id":%d,"name":"job-%d","status":"success"}`, i+1, i+1) - } - w.Header().Set("X-Next-Page", "2") - fmt.Fprint(w, "["+strings.Join(jobs, ",")+"]") - default: - w.WriteHeader(http.StatusNotFound) - } - }) - jobs, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) - require.Error(t, err) - assert.Nil(t, jobs) - assert.ErrorIs(t, err, forge.ErrNotFound, "the 404 stays classified as not found") - assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage, "a partially readable listing never carries the sentinel") - assert.Contains(t, err.Error(), "page 2") - }) } func TestListWorkflowRunArtifacts_Error(t *testing.T) { diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go deleted file mode 100644 index b8c886c461..0000000000 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ /dev/null @@ -1,359 +0,0 @@ -package githubactions - -import ( - "context" - "errors" - "fmt" - "testing" - "time" - - "github.com/fullsend-ai/fullsend/internal/forge" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// dispatchReadsClient measures requests while two runs settle over six polls. -type dispatchReadsClient struct { - *forge.FakeClient - polls int - jobReads map[int]int -} - -func (c *dispatchReadsClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, workflow string, after time.Time) ([]forge.WorkflowRun, error) { - c.polls++ - runs, err := c.FakeClient.ListWorkflowRunsSince(ctx, owner, repo, workflow, after) - for i := range runs { - if runs[i].ID > 30 && c.polls >= 6 { - runs[i].Status = "completed" - } - } - return runs, err -} - -func (c *dispatchReadsClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow string) ([]forge.WorkflowRun, error) { - runs, err := c.ListWorkflowRunsSince(ctx, owner, repo, workflow, time.Time{}) - if len(runs) > 10 { - runs = runs[:10] - } - return runs, err -} - -func (c *dispatchReadsClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string, runID int) ([]forge.WorkflowJob, error) { - c.jobReads[runID]++ - return c.FakeClient.ListWorkflowRunJobs(ctx, owner, repo, runID) -} - -func newDispatchReadsClient(after time.Time) *dispatchReadsClient { - fake := forge.NewFakeClient() - var runs []forge.WorkflowRun - jobs := make(map[int][]forge.WorkflowJob) - for id := 32; id > 0; id-- { - run := forge.WorkflowRun{ID: id, RunAttempt: 1, Status: "completed", Conclusion: "success", CreatedAt: after.Add(time.Duration(id) * time.Second).Format(time.RFC3339)} - switch { - case id > 30: - run.Status = "in_progress" - case id > 10: - run.Conclusion = "skipped" - } - runs = append(runs, run) - jobs[id] = []forge.WorkflowJob{{ID: id, RunAttempt: 1, Name: "dispatch / Route", Status: "completed", Conclusion: "success"}} - } - // The target dispatch is older than the ten newest runs. - jobs[1] = []forge.WorkflowJob{{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}} - fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": runs} - fake.WorkflowRunJobs = jobs - return &dispatchReadsClient{FakeClient: fake, jobReads: make(map[int]int)} -} - -func TestHarnessDispatchAssertions_RequestCounts(t *testing.T) { - t.Parallel() - after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - t.Run("count across six polls", func(t *testing.T) { - client := newDispatchReadsClient(after) - d := &Driver{Client: client, afterFunc: instantAfter} - count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) - require.NoError(t, err) - var total int - for _, calls := range client.jobReads { - total += calls - } - t.Logf("list calls=%d jobs calls=%d unique jobs URLs=%d count=%d", client.polls, total, len(client.jobReads), count) - assert.Equal(t, 1, count, "the older dispatch must still be counted") - assert.Equal(t, 6, client.polls) - assert.Equal(t, 67, total, "one decisive match once, nine inconclusive and two active runs on six polls") - assert.Equal(t, 12, len(client.jobReads), "skipped workflows need no jobs lookup") - }) - t.Run("negative assertion", func(t *testing.T) { - client := newDispatchReadsClient(after) - d := &Driver{Client: client} - require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "absent", after)) - t.Logf("list calls=%d jobs calls=%d", client.polls, len(client.jobReads)) - assert.Len(t, client.jobReads, 12) - for _, calls := range client.jobReads { - assert.Equal(t, 1, calls) - } - }) -} - -func TestHarnessDispatchAssertions_SkippedRunNeedsNoJobs(t *testing.T) { - t.Parallel() - after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - fake := forge.NewFakeClient() - fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { - {ID: 1, Status: "completed", Conclusion: "skipped", CreatedAt: after.Format(time.RFC3339)}, - }} - fake.Errors["ListWorkflowRunJobs"] = errors.New("jobs must not be requested for a skipped workflow") - d := &Driver{Client: fake} - count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) - require.NoError(t, err) - assert.Zero(t, count) - require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) -} - -func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { - t.Parallel() - after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - for _, status := range []string{"queued", "waiting", "requested", "pending"} { - t.Run(status, func(t *testing.T) { - t.Parallel() - fake := forge.NewFakeClient() - fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { - {ID: 1, Status: status, CreatedAt: after.Format(time.RFC3339)}, - }} - // A queued run is pending without a jobs read; a waiting run - // reads the listing and stays pending when it 404s on page 1. - fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingNotFoundFirstPage - d := &Driver{Client: fake} - - count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) - require.NoError(t, err) - assert.Zero(t, count) - assert.Equal(t, 1, pending) - - // The negative assertion reads the listing and tolerates the - // first-page 404 only for a run that has not started. A waiting - // run can already hold a completed agent job, so an unreadable - // listing must fail the assertion rather than skip the run. - if status == "waiting" { - require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), forge.ErrJobsListingNotFoundFirstPage) - } else { - require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) - } - - // A 404 on a later page means the listing was partially read — - // page 1 may hold a completed agent job — so it is never - // absence, even for a not-started run. - fake.Errors["ListWorkflowRunJobs"] = fmt.Errorf("list workflow run jobs page 2: %w", forge.ErrNotFound) - require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), forge.ErrNotFound, - "a partially readable listing must fail the assertion") - - // A waiting run can follow jobs that already ran (environment - // approval), so returned jobs are checked, never skipped. - delete(fake.Errors, "ListWorkflowRunJobs") - fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{1: { - {ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}, - }} - require.Error(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), - "a run awaiting approval can already hold a completed agent job") - - // Any other listing error stays fatal on the negative path. - lookupErr := errors.New("jobs lookup failed") - fake.Errors["ListWorkflowRunJobs"] = lookupErr - require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), lookupErr) - }) - } -} - -// TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob pins the -// count-side rule: a workflow waiting on an environment approval can -// already hold a completed agent job, which is conclusive dispatch -// evidence — the count must not wait out the whole run. -// TestClassifyJobsError pins the full status × listing-error table that -// both dispatch paths route through. Changing an entry here is a -// semantic decision about run statuses, not a mechanical drift fix. -func TestClassifyJobsError(t *testing.T) { - t.Parallel() - firstPage404 := fmt.Errorf("list workflow run jobs page 1: %w: %w", forge.ErrJobsListingNotFoundFirstPage, forge.ErrNotFound) - laterPage404 := fmt.Errorf("list workflow run jobs page 2: %w", forge.ErrNotFound) - otherErr := errors.New("jobs lookup failed") - for _, tc := range []struct { - name string - status string - err error - want jobsReadOutcome - }{ - {"queued first-page 404 skips", "queued", firstPage404, jobsSkipRun}, - {"requested first-page 404 skips", "requested", firstPage404, jobsSkipRun}, - {"pending first-page 404 skips", "pending", firstPage404, jobsSkipRun}, - {"waiting first-page 404 retries later", "waiting", firstPage404, jobsRetryLater}, - {"in_progress first-page 404 is fatal", "in_progress", firstPage404, jobsFatal}, - {"completed first-page 404 is fatal", "completed", firstPage404, jobsFatal}, - {"queued later-page 404 is fatal", "queued", laterPage404, jobsFatal}, - {"waiting later-page 404 is fatal", "waiting", laterPage404, jobsFatal}, - {"completed later-page 404 is fatal", "completed", laterPage404, jobsFatal}, - {"queued other error is fatal", "queued", otherErr, jobsFatal}, - {"waiting other error is fatal", "waiting", otherErr, jobsFatal}, - {"completed other error is fatal", "completed", otherErr, jobsFatal}, - } { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - assert.Equal(t, tc.want, classifyJobsError(tc.status, tc.err)) - }) - } -} - -func TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob(t *testing.T) { - t.Parallel() - after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - for _, tc := range []struct { - name string - job forge.WorkflowJob - count int - pend int - }{ - { - name: "completed agent job counts", - job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}, - count: 1, - }, - { - name: "running agent job stays pending", - job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "in_progress"}, - pend: 1, - }, - { - name: "no agent job yet stays pending", - job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Route", Status: "completed", Conclusion: "success"}, - pend: 1, - }, - } { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - fake := forge.NewFakeClient() - fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { - {ID: 1, RunAttempt: 1, Status: "waiting", CreatedAt: after.Format(time.RFC3339)}, - }} - fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{1: {tc.job}} - d := &Driver{Client: fake} - count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) - require.NoError(t, err) - assert.Equal(t, tc.count, count) - assert.Equal(t, tc.pend, pending) - }) - } - t.Run("absent jobs listing stays pending", func(t *testing.T) { - t.Parallel() - fake := forge.NewFakeClient() - fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { - {ID: 1, RunAttempt: 1, Status: "waiting", CreatedAt: after.Format(time.RFC3339)}, - }} - fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingNotFoundFirstPage - d := &Driver{Client: fake} - count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) - require.NoError(t, err) - assert.Zero(t, count) - assert.Equal(t, 1, pending) - }) -} - -func TestCountHarnessDispatches_CompletedRunJobsBecomeVisible(t *testing.T) { - t.Parallel() - after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - for _, firstJob := range []string{"dispatch / Route", "dispatch / Harness run (${{ matrix.agent }})", "dispatch / Fix", "dispatch / Harness run (fix)"} { - t.Run(firstJob, func(t *testing.T) { - client := newDispatchReadsClient(after) - run := client.WorkflowRunsList["org/repo/fullsend.yaml"][31] - client.WorkflowRunJobs[1] = []forge.WorkflowJob{{ID: 1, RunAttempt: 1, Name: firstJob, Status: "completed", Conclusion: "skipped"}} - if firstJob == "dispatch / Route" { - client.WorkflowRunJobs[1][0].Conclusion = "success" - } - d := &Driver{Client: client, afterFunc: func(time.Duration) <-chan time.Time { - if client.polls == 1 { - client.WorkflowRunJobs[1] = append(client.WorkflowRunJobs[1], forge.WorkflowJob{ - ID: 100, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success", - }) - } - return instantAfter(0) - }} - count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) - require.NoError(t, err) - assert.Equal(t, 1, count, "a lagging listing must not permanently hide the completed agent job") - assert.Equal(t, 2, client.jobReads[1], "reread the inconclusive listing, then cache the decisive match") - assert.Equal(t, 6, client.polls, "a pending sibling keeps the assertion polling") - assert.Equal(t, run, client.WorkflowRunsList["org/repo/fullsend.yaml"][31], "completed run metadata stays unchanged") - }) - } -} - -func TestHarnessDispatchAssertions_RelevantJobsErrorsRemainFatal(t *testing.T) { - t.Parallel() - after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - for _, run := range []forge.WorkflowRun{ - {Status: "completed", Conclusion: "success"}, - {Status: "completed", Conclusion: "failure"}, - {Status: "completed", Conclusion: "cancelled"}, - {Status: "in_progress", Conclusion: "skipped"}, - {}, - } { - t.Run(run.Status+"/"+run.Conclusion, func(t *testing.T) { - fake := forge.NewFakeClient() - run.ID, run.CreatedAt = 1, after.Format(time.RFC3339) - fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": {run}} - lookupErr := errors.New("jobs lookup failed") - fake.Errors["ListWorkflowRunJobs"] = lookupErr - d := &Driver{Client: fake} - _, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) - require.ErrorIs(t, err, lookupErr) - require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), lookupErr) - }) - } -} - -func TestCountHarnessDispatches_CompletedJobCache(t *testing.T) { - t.Parallel() - after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - for _, name := range []string{"rerun", "unknown run attempt", "unknown job attempt", "mismatched job attempt", "unfinished job", "unfinished conclusion", "empty jobs", "assertion local", "changed conclusion"} { - t.Run(name, func(t *testing.T) { - client := newDispatchReadsClient(after) - run := &client.WorkflowRunsList["org/repo/fullsend.yaml"][31] - job := &client.WorkflowRunJobs[1][0] - switch name { - case "unknown run attempt": - run.RunAttempt = 0 - case "unknown job attempt": - job.RunAttempt = 0 - case "mismatched job attempt": - job.RunAttempt = 2 - case "unfinished job": - job.Status = "queued" - case "unfinished conclusion": - job.Conclusion = "" - case "empty jobs": - client.WorkflowRunJobs[1] = nil - } - d := &Driver{Client: client, afterFunc: func(time.Duration) <-chan time.Time { - if client.polls == 1 { - switch name { - case "rerun": - run.RunAttempt = 2 - job.RunAttempt = 2 - case "changed conclusion": - run.Conclusion = "cancelled" - } - client.WorkflowRunJobs[1] = []forge.WorkflowJob{{ID: 100, RunAttempt: run.RunAttempt, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "cancelled"}} - } - return instantAfter(0) - }} - count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) - require.NoError(t, err) - if name == "assertion local" { - assert.Equal(t, 1, count, "the completed attempt is reused within the first assertion") - assert.Equal(t, 1, client.jobReads[1]) - count, err = d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) - require.NoError(t, err) - } - assert.Zero(t, count, "a changed or uncertified job listing must be fetched again") - assert.GreaterOrEqual(t, client.jobReads[1], 2) - }) - } -} diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index 5559bfe8bc..4f50397299 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1582,9 +1582,8 @@ func (d *Driver) failedHarnessPollOnce(ctx context.Context, remaining time.Durat // cancellation is still in progress. func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent string, after time.Time) (int, error) { deadline := d.now().Add(dispatchWait) - completedJobs := make(map[forge.WorkflowRun][]forge.WorkflowJob) for { - count, pending, err := d.settleHarnessDispatchCount(ctx, owner, repo, agent, after, completedJobs) + count, pending, err := d.settleHarnessDispatchCount(ctx, owner, repo, agent, after) if err != nil { return 0, err } @@ -1607,60 +1606,6 @@ func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent } } -// runUnstarted reports whether a workflow run is queued before any job -// can run. Its jobs listing cannot classify a dispatch and can still 404 -// while the run sits in the queue. -func runUnstarted(status string) bool { - switch status { - case "queued", "requested", "pending": - return true - } - return false -} - -// jobsReadOutcome classifies a workflow run whose jobs listing could not -// be read. -type jobsReadOutcome int - -const ( - // jobsSkipRun: the run cannot hold agent work yet, so the caller - // ignores it — no dispatch, no violation. - jobsSkipRun jobsReadOutcome = iota - // jobsRetryLater: the run may hold agent work but its listing is not - // readable yet. A settling caller keeps the run pending; a one-shot - // caller fails closed, because an unreadable listing is not evidence - // that no agent job ran. - jobsRetryLater - // jobsFatal: the listing error is unexpected and must fail the caller. - jobsFatal -) - -// classifyJobsError is the only place that maps a run's status and a -// jobs-listing error to a tolerance rule. The dispatch-count and -// negative-assertion paths both route their listing errors through it -// and must not grow status predicates of their own. -// -// A run that has not started cannot hold agent work, and its listing has -// been observed to 404 on the first page before the run starts, so that -// shape skips the run. A waiting run — one held on an environment -// approval — can already hold a completed agent job, so its unreadable -// listing is retry material, never evidence of absence. Any other error -// is fatal; in particular a later-page 404 means page 1 was already -// readable and may hold a completed agent job, so it is never tolerated. -func classifyJobsError(status string, err error) jobsReadOutcome { - if !errors.Is(err, forge.ErrJobsListingNotFoundFirstPage) { - return jobsFatal - } - switch { - case runUnstarted(status): - return jobsSkipRun - case status == "waiting": - return jobsRetryLater - default: - return jobsFatal - } -} - // settleHarnessDispatchCount classifies harness runs created after the // trigger time into counted dispatches and pending runs. A run is pending // when its agent job exists but has not completed, or when the run itself @@ -1678,51 +1623,21 @@ func classifyJobsError(status string, err error) jobsReadOutcome { // computing the matrix (#7957 review, third pass — mirrors // harnessRoundPollOnce's guard; cancelled static jobs added #7996 review; // success/failure built-in matches added #7996 review, second pass). -func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, agent string, after time.Time, completedJobs map[forge.WorkflowRun][]forge.WorkflowJob) (count, pending int, err error) { - allRuns, err := d.listHarnessRunsAfterPaginated(ctx, owner, repo, after) +func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, agent string, after time.Time) (count, pending int, err error) { + allRuns, err := d.Client.ListWorkflowRuns(ctx, owner, repo, harnessWorkflowFile) if err != nil { return 0, 0, err } for _, r := range allRuns { - if r.Status == "completed" && r.Conclusion == "skipped" { - continue - } - if runUnstarted(r.Status) { - // classifyJobsError would skip these runs anyway; skipping - // before the read also avoids a listing call that 404s while - // the run sits in the queue. - pending++ + runTime, parseErr := time.Parse(time.RFC3339, r.CreatedAt) + if parseErr != nil || runTime.Before(after) { continue } - jobs, cached := completedJobs[r] - if !cached { - jobs, err = d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) - if err != nil { - // Settling, so both skippable and retryable runs stay - // pending rather than fail the count. - if outcome := classifyJobsError(r.Status, err); outcome == jobsSkipRun || outcome == jobsRetryLater { - pending++ - continue - } - return 0, 0, err - } + jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) + if err != nil { + return 0, 0, err } hasJob, job := matchAgentJob(jobs, agent) - if !cached { - // Only a counted terminal match is decisive; missing jobs can still become visible. - cacheable := r.Status == "completed" && r.RunAttempt > 0 && hasJob && - job.Conclusion != "" && !isConcurrencySuperseded(job.Conclusion) - // Reruns reuse IDs; only reuse completed jobs from the same known attempt. - for _, job := range jobs { - if job.Status != "completed" || job.RunAttempt != r.RunAttempt { - cacheable = false - break - } - } - if cacheable && completedJobs != nil { - completedJobs[r] = jobs - } - } switch { case hasJob && job.Status != "completed": pending++ @@ -1884,23 +1799,18 @@ func isConcurrencySuperseded(conclusion string) bool { // than artifacts so that sibling runs for other agents are not mistaken // for evidence. func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, agent string, after time.Time) error { - allRuns, err := d.listHarnessRunsAfterPaginated(ctx, owner, repo, after) + allRuns, err := d.Client.ListWorkflowRuns(ctx, owner, repo, harnessWorkflowFile) if err != nil { return err } for _, r := range allRuns { - if r.Status == "completed" && r.Conclusion == "skipped" { + runTime, parseErr := time.Parse(time.RFC3339, r.CreatedAt) + if parseErr != nil || runTime.Before(after) { continue } jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { - // One-shot, so only a run that cannot hold agent work yet is - // skipped: an unreadable listing is not evidence that no - // agent job ran, so retryable and fatal both fail closed. - if classifyJobsError(r.Status, err) != jobsSkipRun { - return err - } - continue + return err } // Every matching job is inspected independently here, rather than // through matchAgentJob's single "best" match: a job list can diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go index 2a93101e0a..ab6098cb15 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go @@ -541,36 +541,6 @@ func (c *truncatingListWorkflowRunsClient) ListWorkflowRuns(_ context.Context, _ return append([]forge.WorkflowRun(nil), c.truncated...), nil } -func TestHarnessDispatchAssertions_IncludeRunsBeyondFirstPage(t *testing.T) { - t.Parallel() - - after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) - fake := forge.NewFakeClient() - var runs []forge.WorkflowRun - for id := range 11 { - runs = append(runs, forge.WorkflowRun{ - ID: id + 1, Status: "completed", Conclusion: "success", - CreatedAt: after.Add(time.Duration(id+1) * time.Minute).Format(time.RFC3339), - }) - } - fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": runs} - fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{ - 1: {{ID: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}}, - } - d := newTestDriver(&truncatingListWorkflowRunsClient{FakeClient: fake, truncated: runs[1:]}) - - t.Run("exact count", func(t *testing.T) { - count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) - require.NoError(t, err) - assert.Equal(t, 1, count, "newer unrelated runs must not hide a dispatch") - }) - t.Run("negative assertion", func(t *testing.T) { - err := d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after) - require.Error(t, err) - assert.Contains(t, err.Error(), "workflow run 1") - }) -} - // TestWaitForHarnessAgentRound_SelectsEarliestEligibleRunBeyondTruncatedPage // is a regression test (#7996 review): listHarnessRunsAfter's shared // listing (used by WaitForHarnessAgent's latest-eligible-run selection) @@ -2520,7 +2490,7 @@ func TestSettleHarnessDispatchCount_SuccessfulBuiltinMatrixUnresolvedPending(t * } d := &Driver{Client: fake} - count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "triage", after, nil) + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "triage", after) require.NoError(t, err) assert.Equal(t, 0, count, "a successful built-in match must not be counted while the custom matrix remains unresolved") assert.Equal(t, 1, pending, "the run must be classified as pending until the real matrix job appears") From 4a97d9aa4d53e68534cc7eafc53e980160a58558 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 5 Nov 2026 11:15:35 -0500 Subject: [PATCH 37/40] docs(telemetry): describe the v1 wire format as provisional in code The normative README marks v1 provisional until the first carrier-publishing pull request merges, but the envelope comments, the golden-vector comment, and the golden test's failure message still called the format frozen. Align them with the README, and state that CI runs only the FuzzParse seeds. Signed-off-by: Dharit Shah --- internal/telemetry/tracecontext/envelope.go | 6 +++--- .../telemetry/tracecontext/envelope_test.go | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index aea64a3a9c..83c759f29f 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -69,8 +69,8 @@ type Provenance struct { // unauthenticated: Parse checks structure only, so TraceID, ParentSpanID, // and Provenance must not be consumed unless Admit returns // OutcomeAdmitted. The wire layout, exact sizes, and strict limits are -// frozen in docs/normative/trace-context/v1/README.md; Marshal is its only -// legal encoder. +// specified in docs/normative/trace-context/v1/README.md, provisional until +// the first carrier-publishing PR merges; Marshal is its only legal encoder. type Envelope struct { Domain Domain KeyID [8]byte @@ -97,7 +97,7 @@ const MaxEnvelopeLen = 439 // base64.StdEncoding of MaxEnvelopeLen bytes without line breaks. const MaxCarrierLen = 588 -// Wire constants of the frozen v1 format. +// Wire constants of the v1 format. var magic = [4]byte{'F', 'S', 'T', 'C'} const versionV1 = 0x01 diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index c83c23703a..df3b366ca7 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -19,8 +19,7 @@ import ( // The tests in this file cover ADR 0154: exact signed-byte // fixtures, tamper-every-field, cross-binding replay, strict parser limits, // duplicate/oversized/zero-ID rejection, retained keys, and pending markers -// granting nothing. Golden hex constants pin the frozen v1 wire format for -// every later PR. +// granting nothing. Golden hex constants pin the v1 wire format. // goldenKey is a deterministic Ed25519 key for reproducible fixtures. func goldenKey() ed25519.PrivateKey { @@ -117,7 +116,7 @@ func signedGolden(t *testing.T, domain Domain, prov ProvenanceKind) ([]byte, map return mustHex(t, wire), keys } -// specLayout mirrors the frozen v1 wire layout from +// specLayout mirrors the v1 wire layout from // docs/normative/trace-context/v1/README.md so tests locate fields independently of // the implementation, pinning the format from the spec side. type specLayout struct { @@ -172,8 +171,9 @@ func mustHex(t *testing.T, s string) []byte { return b } -// Golden hex constants: frozen from the first green run; any later change -// to the wire format is a compatibility break. Independently reconstructed +// Golden hex constants: the v1 conformance vectors. While v1 is provisional +// (README Compatibility), a deliberate wire-format change updates the README +// and these vectors together. Independently reconstructed // with Python struct + cryptography Ed25519 during corrective review; the // pending provenance vectors were first generated by that independent code. var ( @@ -207,10 +207,10 @@ func TestGoldenVectors(t *testing.T) { raw := env.Marshal() want := mustHex(t, *tc.hex) if !bytes.Equal(raw, want) { - t.Fatalf("golden wire bytes changed or not yet frozen:\n got %x\nwant %x", raw, want) + t.Fatalf("golden wire bytes differ from the v1 conformance vector:\n got %x\nwant %x", raw, want) } - // Layout is exactly the frozen spec's size. + // Layout is exactly the spec's size. assert.Equal(t, layout(tc.dom, tc.prov, len(goldenIdentity().Instance)).total, len(raw)) // Parse round-trips byte-for-byte. @@ -841,8 +841,8 @@ func TestParse_Truncations(t *testing.T) { } func FuzzParse(f *testing.F) { - // The frozen golden vectors, their truncations, and oversized inputs - // seed the corpus; CI fuzzing grows it from there. + // The golden vectors, their truncations, and oversized inputs seed the + // corpus. CI runs only these seeds; go test -fuzz=FuzzParse fuzzes. for _, h := range []string{goldenBoundNoneHex, goldenBoundSourceLinkHex, goldenBoundScenarioHex, goldenPendingNoneHex, goldenPendingSourceLinkHex, goldenPendingScenarioHex} { b, err := hex.DecodeString(h) if err != nil { From daa1ac53fb6f2d552b48d8624e1570d255c45df1 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 5 Nov 2026 11:18:21 -0500 Subject: [PATCH 38/40] fix(telemetry): reject mixed-escape instance paths and canonicalize IPv6 hosts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit net/url keeps a path's original escapes only when the whole path is validly escaped. A prefix such as /café%2Fx was therefore re-escaped to /caf%C3%A9/x, so two distinct deployments shared one instance and one fallback TraceID, and an envelope signed for one was admitted under the other. NormalizeInstance now rejects such mixed paths and asks for the fully escaped prefix. Different spellings of one IPv6 address, such as 2001:db8::1 and 2001:db8:0:0:0:0:0:1, still produced different instances; bracketed hosts now take their RFC 5952 form. The README port rule now states the order the code applies (strip zeros, then drop the default port), and the doc comment says that every trailing root dot is stripped. Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 36 ++++++++++--------- docs/reference/trace-context.md | 3 +- internal/telemetry/tracecontext/identity.go | 26 ++++++++++---- .../telemetry/tracecontext/identity_test.go | 12 +++++++ 4 files changed, 53 insertions(+), 24 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 85e1fbf373..067e303035 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -38,23 +38,27 @@ URL-escaped deployment path prefix, with trailing slashes removed. For example, `https://GitLab.example.com/gitlab/` becomes `https://gitlab.example.com/gitlab`; it is distinct from both the root installation and `/GitLab`. Path segments and existing escape spelling are -preserved, never cleaned or decoded into separators. Use the same configured -deployment URL on every launch, rather than an entity or API URL. - -Remove an empty port and the scheme's default port (`443` for HTTPS, `80` for -HTTP). Strip leading zeros from other ports, preserving an explicit zero as -`:0` rather than treating it as the default, and reject ports above `65535`. -For example, `https://host:` becomes `https://host`, and -`https://host:08443` becomes `https://host:8443`. Hosts must be ASCII: use -the punycode form for internationalized domain names, and reject Unicode -host spellings instead of converting them. For example, -`https://GitHub.com:443/` becomes `https://github.com`, and +preserved, never cleaned or decoded into separators. A path that mixes +percent-escapes with characters that still need escaping, such as +`/a%2Fb/c d`, rejects; write the fully escaped prefix (`/a%2Fb/c%20d`). Use +the same configured deployment URL on every launch, rather than an entity or +API URL. + +Strip leading zeros from the port, keeping an all-zero port as `:0` rather +than treating it as the default, and reject ports above `65535`. Then remove +an empty port and the scheme's default port (`443` for HTTPS, `80` for +HTTP). For example, `https://host:` and `https://host:0443` become +`https://host`, and `https://host:08443` becomes `https://host:8443`. +Hosts must be ASCII: use the punycode form for internationalized domain +names, and reject Unicode host spellings instead of converting them. For +example, `https://GitHub.com:443/` becomes `https://github.com`, and `https://XN--BCHER-KVA.example` becomes `https://xn--bcher-kva.example`. -Bracketed IPv6 hosts follow the same case and port rules, without zone -identifiers: `https://[FE80::1%25EN0]` rejects — use a routable address — -so a normalized instance always re-normalizes to itself. Trailing DNS root -dots are stripped: `https://github.com.` and `https://github.com` are one -deployment with one fallback identity, never two. +Bracketed IPv6 hosts follow the same port rules and take their RFC 5952 +form: `https://[2001:DB8:0:0:0:0:0:1]` becomes `https://[2001:db8::1]`. +Zone identifiers reject (`https://[FE80::1%25EN0]`; use a routable +address), so a normalized instance always re-normalizes to itself. +Trailing DNS root dots are stripped: `https://github.com.` and +`https://github.com` are one deployment with one fallback identity. `NormalizeInstance` rejects queries, fragments, user info, missing hosts, invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index e9b4483080..8a345d83f4 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -66,7 +66,8 @@ database ID; its result alone cannot resolve trace identity. - [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/identity_test.go) contains independent fallback vectors, deployment-prefix separation checks, - cross-process convergence, root-dot/port/IPv6-zone canonicalization, a + cross-process convergence, root-dot, port, and IPv6 spelling and zone + canonicalization, mixed-escape path rejection, a normalization fuzz target asserting the canonical form re-normalizes to itself, and SDK exporter lifecycle assertions. - [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/envelope_test.go) diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index c344357514..459a3b58d1 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -12,6 +12,7 @@ import ( "encoding/binary" "errors" "fmt" + "net/netip" "net/url" "strconv" "strings" @@ -127,13 +128,14 @@ func nonzeroFallback(fb Fallback) Fallback { // NormalizeInstance canonicalizes a forge web base URL to the D01 instance // form: lowercase scheme://host with an escaped, case-sensitive deployment // prefix and no trailing slashes, query, fragment, or user info. Only http -// and https are accepted, empty/default ports are removed, other ports -// lose leading zeros and must fit 16 bits, a single DNS root dot is -// stripped from the host, and hosts must be ASCII (punycode for IDNs) -// without an IPv6 zone identifier. Path segments and escape spelling are -// preserved so distinct deployments cannot alias. All identity and -// envelope construction must use the normalized form so independent -// launches converge. +// and https are accepted. Ports lose leading zeros (an all-zero port stays +// :0) and must fit 16 bits; empty and default ports are then removed. +// Trailing DNS root dots are stripped, hosts must be ASCII (punycode for +// IDNs), and IPv6 hosts take their RFC 5952 form without a zone +// identifier. Path segments and escape spelling are preserved so distinct +// deployments cannot alias; a path mixing percent-escapes with characters +// that still need escaping rejects. All identity and envelope construction +// must use the normalized form so independent launches converge. func NormalizeInstance(raw string) (string, error) { if !utf8.ValidString(raw) { return "", errors.New("tracecontext: instance must be valid UTF-8") @@ -151,6 +153,12 @@ func NormalizeInstance(raw string) (string, error) { if !utf8.ValidString(u.Path) || strings.ContainsRune(u.Path, '\x00') { return "", errors.New("tracecontext: instance path must be valid UTF-8 without NUL") } + // net/url keeps the original escapes only when the whole path is validly + // escaped; otherwise EscapedPath re-escapes the decoded path and %2F + // becomes a separator, aliasing two deployments. + if strings.Contains(u.RawPath, "%") && u.EscapedPath() != u.RawPath { + return "", errors.New("tracecontext: instance path mixes percent-escapes with unescaped characters; use the fully escaped prefix") + } scheme := strings.ToLower(u.Scheme) if scheme != "http" && scheme != "https" { return "", fmt.Errorf("tracecontext: unsupported instance scheme %q", u.Scheme) @@ -174,6 +182,10 @@ func NormalizeInstance(raw string) (string, error) { if host == "" { return "", errors.New("tracecontext: instance URL needs a host") } + // One IPv6 address has one spelling: use its RFC 5952 form. + if addr, err := netip.ParseAddr(u.Hostname()); err == nil && addr.Is6() { + host = "[" + addr.String() + "]" + } port := strings.TrimLeft(rawPort, "0") if port == "" && rawPort != "" { port = "0" diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go index ba8e6a0199..abbed0786e 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -253,12 +253,18 @@ func TestNormalizeInstance(t *testing.T) { {"ipv6 empty port", "https://[::1]:/gitlab", "https://[::1]/gitlab"}, {"ipv6 nondefault port", "https://[2001:DB8::1]:8443", "https://[2001:db8::1]:8443"}, {"ipv6 padded nondefault port", "https://[2001:DB8::1]:08443", "https://[2001:db8::1]:8443"}, + {"ipv6 expanded spelling", "https://[2001:DB8:0:0:0:0:0:1]", "https://[2001:db8::1]"}, + {"ipv6 padded group", "https://[2001:db8::0001]:443", "https://[2001:db8::1]"}, + {"ipv4-mapped ipv6 hex spelling", "https://[::ffff:c000:201]", "https://[::ffff:192.0.2.1]"}, + {"multiple root dots", "https://GitHub.com..", "https://github.com"}, {"IDN punycode", "https://XN--BCHER-KVA.example", "https://xn--bcher-kva.example"}, {"trailing slash", "https://github.com/", "https://github.com"}, {"gitlab prefix", "https://GitLab.example.com/gitlab/", "https://gitlab.example.com/gitlab"}, {"nested case-sensitive prefix", "https://gitlab.example.com/Services/GitLab///", "https://gitlab.example.com/Services/GitLab"}, {"escaped prefix", "https://gitlab.example.com/a%2Fb/", "https://gitlab.example.com/a%2Fb"}, {"unicode prefix", "https://gitlab.example.com/café/", "https://gitlab.example.com/caf%C3%A9"}, + {"fully escaped prefix with separator escape", "https://gitlab.example.com/a%2Fb/c%20d", "https://gitlab.example.com/a%2Fb/c%20d"}, + {"fully escaped unicode prefix with separator escape", "https://gitlab.example.com/caf%C3%A9%2Fx", "https://gitlab.example.com/caf%C3%A9%2Fx"}, {"maximum prefix", "https://example.com/" + strings.Repeat("a", 233), "https://example.com/" + strings.Repeat("a", 233)}, } for _, tc := range cases { @@ -321,6 +327,8 @@ func FuzzNormalizeInstance(f *testing.F) { f.Add("https://[2001:DB8::1]:443/") f.Add("https://example.com.") f.Add("https://example.com:65536") + f.Add("https://[2001:DB8:0:0:0:0:0:1]:08443") + f.Add("https://gitlab.example.com/a%2Fb/c d") f.Fuzz(func(t *testing.T, raw string) { normalized, err := NormalizeInstance(raw) if err != nil { @@ -354,6 +362,10 @@ func TestNormalizeInstance_Rejects(t *testing.T) { "https://\xff.example", "https://bücher.example", "https://b%C3%BCcher.example", + // Mixed escapes would decode %2F into a separator and alias + // /a/b/c%20d or /caf%C3%A9/x. + "https://gitlab.example.com/a%2Fb/c d", + "https://gitlab.example.com/café%2Fx", } { _, err := NormalizeInstance(raw) assert.Error(t, err, "input %q must be rejected", raw) From b4dc29d8fce13e4459b85082a7dde49020698f9c Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 5 Nov 2026 11:19:57 -0500 Subject: [PATCH 39/40] docs(telemetry): align the v1 admission text with Admit The README and Go docs said a fallback outcome always means "use the fallback", although an unresolved identity must postpone dispatch. They also said Admit takes carrier bytes (it takes decoded envelope bytes), that any extra candidate forces fallback (identical duplicates admit), and that an editor can never choose the admitted context (Admit has no freshness check). State what the code does, document that a changed deployment URL is a new binding, and note that a forge-backed tracker.Issue.ID for a GitHub PR is the issue-space id. Signed-off-by: Dharit Shah --- docs/normative/trace-context/v1/README.md | 48 ++++++++++++--------- docs/reference/trace-context.md | 2 +- internal/telemetry/tracecontext/envelope.go | 22 ++++++---- internal/telemetry/tracecontext/identity.go | 4 +- internal/tracker/tracker.go | 4 +- 5 files changed, 47 insertions(+), 33 deletions(-) diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md index 067e303035..13e3a8ff90 100644 --- a/docs/normative/trace-context/v1/README.md +++ b/docs/normative/trace-context/v1/README.md @@ -10,8 +10,8 @@ provisioning, and runtime integration are outside this contract. ## Identity Every forge entity is addressed by an immutable five-part tuple. Display -names, URLs, GitHub numbers, GitLab IIDs, and Jira keys are not identity -components. +names, entity URLs, GitHub numbers, GitLab IIDs, and Jira keys are not +identity components. | Component | GitHub | GitLab | Jira | |-----------|--------|--------|------| @@ -64,9 +64,9 @@ Trailing DNS root dots are stripped: `https://github.com.` and invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes (including the escaped prefix). Identity resolution, signing, and parsing require the already canonical value; they never silently rewrite an -authenticated field. Root-instance vectors, wire layout, and size limits -are unchanged; prefixed deployments use the same v1 length-delimited field -and fallback derivation with the full normalized instance bytes. +authenticated field. Prefixed deployments use the same v1 length-delimited +instance field and fallback derivation with the full normalized instance +bytes. The installation ID is generated during key provisioning and identifies one install's key set. It is authenticated inside every envelope and must @@ -77,7 +77,7 @@ traces regardless of key state. ### Rename and move rules - Renames (issue titles, repository names, Jira project keys) never - change identity: every component is a database ID. + change identity: the container and entity components are database IDs. - Repository transfers on GitHub and GitLab preserve the database ID, so identity survives a transfer. - An entity moved between containers (a GitHub issue transfer, a Jira @@ -85,6 +85,9 @@ traces regardless of key state. ID — and therefore a new identity. A previously published envelope fails the binding check and the moved entity falls back. A move is never treated as a rename. +- Changing the configured deployment URL (a Jira site rename, a GHES + hostname change, a GitLab `external_url` change) is also a new binding: + published envelopes fail the binding check and entities fall back. ### Fallback derivation (v1) @@ -146,7 +149,7 @@ the magic through the nonce — there are no unsigned fields. | · | 8 | Parent/anchor Span ID | nonzero | | · | 1 | Provenance kind | `0x00` none, `0x01` source link, `0x02` scenario | | · | 0/24/32 | Provenance fields | none; source link = 16B source TraceID + 8B source SpanID; scenario = 16B scenario TraceID + 16B invocation ID | -| · | 16 | Nonce | `crypto/rand`, nonzero, unique per creation intent | +| · | 16 | Nonce | nonzero (checked); signers draw it from `crypto/rand`, unique per creation intent (not checked at admission) | | end−64 | 64 | Ed25519 signature | over bytes `[0, end−64)` | The maximum legal size is 439 bytes (bound envelope, scenario provenance, @@ -196,8 +199,8 @@ without context or provenance; they never reach Ed25519 verification. `Admit(expected Identity, keys, candidates...)` is the pure decision operation. It takes the trusted expected binding, the configured eligible -verification keys, and bounded candidate carrier bytes, and returns -exactly one outcome: +verification keys, and bounded candidate envelope bytes, each decoded from +its carrier with `DecodeCarrier`, and returns exactly one outcome: - **Admitted**: a verified bound envelope matched every binding component. The result carries the admitted TraceID, parent SpanID, and @@ -211,7 +214,8 @@ exactly one outcome: `created_at`) before rereading and falling back, per [ADR 0154](../../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). - **Fallback**: nothing was admissible. The caller uses the - entity-derived fallback. + entity-derived fallback, except for reason `unresolved`, where it + postpones dispatch (see below). The zero-value result selects fallback and grants no context or provenance. @@ -221,12 +225,15 @@ Fallback reason codes are redacted diagnostics — `absent`, `malformed`, never key material or raw bytes. A plain W3C `traceparent` is never an envelope. -Any extra or differing candidate deliberately forces fallback, even when -one candidate alone would admit. An actor who can edit the body can deny -continuity by appending junk or deleting the carrier, but can never choose, -alter, or inject the admitted context; rejection is deliberately fail-closed -so a forged carrier is reported rather than silently ignored. Publishing a -bound envelope must remove the pending marker it replaces; +Any differing extra candidate, whether junk or a second envelope, +deliberately forces fallback even when one candidate alone would admit; +identical duplicates do not. An actor who can edit the body can deny +continuity by appending junk or deleting the carrier, but can never alter +or inject a context: only an envelope the installation signed for this +entity admits. Admission has no freshness check, so an older valid +envelope for the same entity still admits. Rejection is deliberately +fail-closed so a forged carrier is reported rather than silently ignored. +Publishing a bound envelope must remove the pending marker it replaces; leaving both present produces conflicting carriers and fallback, never a pick between them. @@ -236,10 +243,11 @@ authorization are independent decisions; a denied actor never dispatches regardless of admission, and an admitted envelope never authorizes anything. -An unresolved identity (missing instance, container, kind, or entity) is -explicit: admission returns fallback with reason `unresolved` before -inspecting any candidate, and callers must postpone dispatch with -diagnostics rather than derive a fallback or guess. +An unresolved identity (a missing or invalid instance, container, kind, or +entity, including a non-canonical instance) is explicit: admission returns +fallback with reason `unresolved` before inspecting any candidate, and +callers must postpone dispatch with diagnostics rather than derive a +fallback or guess. ## Compatibility diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 8a345d83f4..b9f2e62125 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -50,7 +50,7 @@ database ID; its result alone cannot resolve trace identity. | Symbol | Purpose | |--------|---------| | `Identity` | The immutable binding tuple | -| `Identity.Resolved` | Whether forge-side identity components are present | +| `Identity.Resolved` | Whether the forge-side components are present and valid: a canonical instance, IDs ≥ 1, and a defined kind | | `DeriveFallback` | The v1 deterministic fallback context | | `NormalizeInstance` | Canonical deployment base URL, including its path prefix | | `Envelope` | A decoded, unverified v1 envelope or pending marker; fields are safe only after `Admit` admits | diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index 83c759f29f..6c974e9a72 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -402,14 +402,17 @@ type Outcome int const ( // OutcomeFallback means no carrier was admissible; the caller uses - // the deterministic entity-derived fallback. It is the zero value. + // the deterministic entity-derived fallback, except for + // ReasonUnresolved, where it must postpone dispatch. It is the zero + // value. OutcomeFallback Outcome = iota // OutcomeAdmitted means a verified bound envelope matched the // expected binding; the admitted IDs are available. OutcomeAdmitted // OutcomePending means a verified pending marker matched the expected - // scope. It grants neither context nor links; bounded rereads are - // caller policy. + // scope. It grants neither context nor links; callers bound the reread + // by a window from the entity's trusted creation metadata, then fall + // back. OutcomePending ) @@ -461,12 +464,13 @@ func reasonForParse(err error) string { } } -// Admit parses, verifies, and binds candidate carrier wire bytes against -// the expected identity and the configured eligible verification keys -// (active plus retained). Identical duplicate candidates are acceptable; -// any differing candidates reject. Keys are resolved only from the -// supplied trusted set. Admission is independent of dispatch -// authorization: this function never returns permission. +// Admit parses, verifies, and binds candidate envelope wire bytes, each +// decoded from its carrier with DecodeCarrier, against the expected +// identity and the configured eligible verification keys (active plus +// retained). Identical duplicate candidates are acceptable; any differing +// candidates reject. Keys are resolved only from the supplied trusted set. +// Admission is independent of dispatch authorization: this function never +// returns permission. // // An unresolved expected identity reports ReasonUnresolved before any // carrier is inspected: the caller must postpone dispatch (FR-002) and diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index 459a3b58d1..7502e46bec 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -41,8 +41,8 @@ func (k EntityKind) Valid() bool { // Identity is the immutable binding of a forge entity (ADR 0154, D01): // installation, forge instance, container, entity kind, and entity -// database ID. Display names, URLs, GitHub numbers, GitLab IIDs, and Jira -// keys are not identity components; docs/normative/trace-context/v1/README.md holds +// database ID. Display names, entity URLs, GitHub numbers, GitLab IIDs, +// and Jira keys are not identity components; docs/normative/trace-context/v1/README.md holds // the per-forge field mapping. type Identity struct { // Installation is the 128-bit installation identifier provisioned diff --git a/internal/tracker/tracker.go b/internal/tracker/tracker.go index b025bd8f90..2fbcc5c40a 100644 --- a/internal/tracker/tracker.go +++ b/internal/tracker/tracker.go @@ -66,7 +66,9 @@ type Issue struct { // GitLab's database issue id (not the IID), or Jira's numeric issue // id string parsed to an integer. It is 0 when the backend did not // report one; trace admission treats that as unresolved identity - // rather than guessing. + // rather than guessing. For a GitHub PR number, a forge-backed GetIssue + // returns the issue-space id; never use it as KindChangeProposal + // identity (see forge.Issue.ID). ID int64 // ContainerID is the immutable Jira project ID supplied by GetIssue. // Zero means unresolved: create responses and forge-backed reads need From a1721930ea3181551ff95edc8099195f6754bc8c Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 5 Nov 2026 11:23:45 -0500 Subject: [PATCH 40/40] docs(adr): state the ADR 0154 implementation status in one note The status note linked the trace-context specification twice in consecutive paragraphs. Keep one paragraph that says what is implemented, where its contract lives, and what is still pending. Signed-off-by: Dharit Shah --- ...rrelate-work-item-and-behaviour-scenario-traces.md | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md index f08e33d2d5..2301036c05 100644 --- a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md +++ b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md @@ -20,13 +20,10 @@ Date: 2026-10-22 Accepted This records the chosen topology. The identity, fallback, envelope, and -admission foundation is implemented — see the -[trace-context v1 specification](../normative/trace-context/v1/README.md). -Carrier publication, key provisioning, and runtime integration are pending. - -The [trace-context v1 specification](../normative/trace-context/v1/README.md) -defines the detailed identity, fallback, signed-envelope, and admission -contract. +admission foundation is implemented; the +[trace-context v1 specification](../normative/trace-context/v1/README.md) +defines its contract. Carrier publication, key provisioning, and runtime +integration are pending. ## Context