Repository navigation
feat(trace): capture pinned Pi subagent evidence #3760
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
waveywaves
wants to merge
2
commits into
chainloop-dev:main
from
waveywaves:feat/pi-subagent-evidence
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| // Copyright 2026 The Chainloop Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package e2e | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "math" | ||
| "math/big" | ||
| "reflect" | ||
|
|
||
| "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials/aicodingsession" | ||
| ) | ||
|
|
||
| type piSourceRecord struct { | ||
| Type string `json:"type"` | ||
| ID string `json:"id"` | ||
| Message struct { | ||
| Role string `json:"role"` | ||
| ToolName string `json:"toolName"` | ||
| Usage map[string]json.RawMessage `json:"usage"` | ||
| Details struct { | ||
| Mode string `json:"mode"` | ||
| Results []json.RawMessage `json:"results"` | ||
| } `json:"details"` | ||
| } `json:"message"` | ||
| } | ||
|
|
||
| type piSourceChild struct { | ||
| Agent string `json:"agent"` | ||
| Task string `json:"task"` | ||
| Usage map[string]json.RawMessage `json:"usage"` | ||
| Messages []json.RawMessage `json:"messages"` | ||
| } | ||
|
|
||
| // Compare stored children with native completed results, independently of the | ||
| // provider parser. Nonempty aggregate metadata alone cannot pass this check. | ||
| func checkPiSubagents(d *aicodingsession.Data) error { | ||
| var expected []aicodingsession.Subagent | ||
| hasToolResult := false | ||
| for _, raw := range d.RawSession["main"] { | ||
| var r piSourceRecord | ||
| if json.Unmarshal(raw, &r) != nil || !piSourceSubagent(r) { | ||
| continue | ||
| } | ||
| for index, rawChild := range r.Message.Details.Results { | ||
| var child piSourceChild | ||
| if err := json.Unmarshal(rawChild, &child); err != nil { | ||
| return fmt.Errorf("decode Pi source child: %w", err) | ||
| } | ||
| id := fmt.Sprintf("subagent-%s-%d", r.ID, index+1) | ||
| var usage aicodingsession.Usage | ||
| addPiSourceUsage(&usage, child.Usage, child.Usage["cost"]) | ||
| expected = append(expected, aicodingsession.Subagent{ | ||
| ID: id, Type: child.Agent, Description: child.Task, | ||
| Tokens: aicodingsession.SubagentTokens{Input: usage.InputTokens, Output: usage.OutputTokens}, | ||
| }) | ||
| stream := d.RawSession[id] | ||
| if len(stream) == 0 || len(stream) != len(child.Messages) { | ||
| return fmt.Errorf("Pi child %s conversation is missing or incomplete", id) | ||
| } | ||
| for i, source := range child.Messages { | ||
| var entry struct { | ||
| Message json.RawMessage `json:"message"` | ||
| } | ||
| if json.Unmarshal(stream[i], &entry) != nil { | ||
| return fmt.Errorf("Pi child %s has an invalid stored message", id) | ||
| } | ||
| // Material assembly may indent or reorder fields. | ||
| var stored, original bytes.Buffer | ||
| if json.Compact(&stored, entry.Message) != nil || json.Compact(&original, source) != nil { | ||
| return fmt.Errorf("Pi child %s has invalid message JSON", id) | ||
| } | ||
| var got, want map[string]json.RawMessage | ||
| if json.Unmarshal(stored.Bytes(), &got) != nil || json.Unmarshal(original.Bytes(), &want) != nil || !reflect.DeepEqual(got, want) { | ||
| return fmt.Errorf("Pi child %s message %d differs from source content", id, i+1) | ||
| } | ||
| var message struct { | ||
| Role string `json:"role"` | ||
| Content []struct { | ||
| Text string `json:"text"` | ||
| } `json:"content"` | ||
| } | ||
| if json.Unmarshal(source, &message) == nil && message.Role == "toolResult" { | ||
| for _, block := range message.Content { | ||
| hasToolResult = hasToolResult || block.Text != "" | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if len(expected) == 0 || !reflect.DeepEqual(expected, d.Subagents) { | ||
| return errors.New("Pi subagents do not match native completed results") | ||
| } | ||
| if !hasToolResult { | ||
| return errors.New("Pi subagent scenario has no readable child tool result") | ||
| } | ||
| if len(d.RawSession) != len(expected)+1 { | ||
| return errors.New("Pi evidence has unrelated child streams") | ||
| } | ||
| want := piSourceUsage(d.RawSession["main"]) | ||
| if d.SchemaVersion != "v1" || d.Usage == nil || *d.Usage != want { | ||
| return fmt.Errorf("Pi usage does not count parent and child aggregates exactly once: got %+v, want %+v", d.Usage, want) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func piSourceSubagent(r piSourceRecord) bool { | ||
| if r.Type != "message" || r.Message.Role != "toolResult" || r.Message.ToolName != "subagent" { | ||
| return false | ||
| } | ||
| switch r.Message.Details.Mode { | ||
| case "single", "parallel", "chain": | ||
| return true | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| func piSourceUsage(records []json.RawMessage) aicodingsession.Usage { | ||
| var total aicodingsession.Usage | ||
| for _, raw := range records { | ||
| var r piSourceRecord | ||
| if json.Unmarshal(raw, &r) != nil || r.Type != "message" { | ||
| continue | ||
| } | ||
| if r.Message.Role == "assistant" { | ||
| var cost struct { | ||
| Total json.RawMessage `json:"total"` | ||
| } | ||
| if json.Unmarshal(r.Message.Usage["cost"], &cost) != nil { | ||
| cost.Total = nil | ||
| } | ||
| addPiSourceUsage(&total, r.Message.Usage, cost.Total) | ||
| } | ||
| if piSourceSubagent(r) { | ||
| for _, rawChild := range r.Message.Details.Results { | ||
| var child piSourceChild | ||
| if json.Unmarshal(rawChild, &child) == nil && child.Agent != "" { | ||
| addPiSourceUsage(&total, child.Usage, child.Usage["cost"]) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if total.OutputTokens <= int(^uint(0)>>1)-total.InputTokens { | ||
| total.TotalTokens = total.InputTokens + total.OutputTokens | ||
| } | ||
| if total.EstimatedCostUSD <= math.MaxFloat64/10000 { | ||
| total.EstimatedCostUSD = math.Round(total.EstimatedCostUSD*10000) / 10000 | ||
| } | ||
| return total | ||
| } | ||
|
|
||
| func addPiSourceUsage(total *aicodingsession.Usage, usage map[string]json.RawMessage, rawCost json.RawMessage) { | ||
| for _, field := range []struct { | ||
| name string | ||
| total *int | ||
| }{ | ||
| {"input", &total.InputTokens}, | ||
| {"output", &total.OutputTokens}, | ||
| {"cacheRead", &total.CacheReadInputTokens}, | ||
| {"cacheWrite", &total.CacheCreationInputTokens}, | ||
| } { | ||
| value, ok := new(big.Rat).SetString(string(usage[field.name])) | ||
| if !ok || value.Sign() < 0 || !value.IsInt() || !value.Num().IsInt64() { | ||
| continue | ||
| } | ||
| count := value.Num().Int64() | ||
| if count <= int64(int(^uint(0)>>1)-*field.total) { | ||
| *field.total += int(count) | ||
| } | ||
| } | ||
| var cost float64 | ||
| if json.Unmarshal(rawCost, &cost) == nil && cost >= 0 && !math.IsInf(cost+total.EstimatedCostUSD, 0) { | ||
| total.EstimatedCostUSD += cost | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| // Copyright 2026 The Chainloop Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package e2e | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
|
|
||
| "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" | ||
| "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials/aicodingsession" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| const piCheckChildID = "subagent-result-1" | ||
|
|
||
| func piSubagentCheckSession() *Session { | ||
| const assistant = `{"role":"assistant","content":[{"type":"toolCall","id":"read-1","name":"read","arguments":{"path":"README.md"}}],"usage":{"input":3,"output":5,"cacheRead":11,"cacheWrite":19,"cost":{"total":0.025}}}` | ||
| const toolResult = `{"role":"toolResult","toolCallId":"read-1","toolName":"read","content":[{"type":"text","text":"file contents"}]}` | ||
| s := cacheSession(pi.Name, | ||
| `{"type":"message","id":"root","message":{"role":"assistant","usage":{"input":7,"output":9,"cacheRead":13,"cacheWrite":17,"cost":{"total":0.1}}}}`, | ||
| `{"type":"message","id":"result","message":{"role":"toolResult","toolName":"subagent","details":{"mode":"single","results":[{"agent":"worker","task":"read","usage":{"input":3,"output":5,"cacheRead":11,"cacheWrite":19,"cost":0.025},"messages":[`+assistant+`,`+toolResult+`]}]}}}`, | ||
| ) | ||
| d := evidence(s) | ||
| d.Usage = &aicodingsession.Usage{ | ||
| InputTokens: 10, OutputTokens: 14, TotalTokens: 24, | ||
| CacheReadInputTokens: 24, CacheCreationInputTokens: 36, EstimatedCostUSD: 0.125, | ||
| } | ||
| d.Subagents = []aicodingsession.Subagent{{ | ||
| ID: piCheckChildID, Type: "worker", Description: "read", | ||
| Tokens: aicodingsession.SubagentTokens{Input: 3, Output: 5}, | ||
| }} | ||
| d.RawSession[piCheckChildID] = []json.RawMessage{ | ||
| json.RawMessage(`{"type":"message","message":` + assistant + `}`), | ||
| json.RawMessage(`{"type":"message","message":` + toolResult + `}`), | ||
| } | ||
| return s | ||
| } | ||
|
|
||
| func TestCheckPiSubagentsWhenStoredEvidenceChanges(t *testing.T) { | ||
| for _, tc := range []struct { | ||
| name string | ||
| change func(*aicodingsession.Data) | ||
| }{ | ||
| {name: "complete child content and exact usage"}, | ||
| {name: "missing child conversation", change: func(d *aicodingsession.Data) { delete(d.RawSession, piCheckChildID) }}, | ||
| {name: "lost tool result", change: func(d *aicodingsession.Data) { | ||
| d.RawSession[piCheckChildID] = d.RawSession[piCheckChildID][:1] | ||
| }}, | ||
| {name: "changed tool content", change: func(d *aicodingsession.Data) { | ||
| d.RawSession[piCheckChildID][1] = json.RawMessage(`{"message":{"role":"toolResult","content":[{"type":"text","text":"truncated"}]}}`) | ||
| }}, | ||
| {name: "wrong child identity", change: func(d *aicodingsession.Data) { d.Subagents[0].ID = "wrong" }}, | ||
| {name: "lost child tokens", change: func(d *aicodingsession.Data) { d.Subagents[0].Tokens.Input = 0 }}, | ||
| {name: "double counted usage", change: func(d *aicodingsession.Data) { d.Usage.InputTokens += 3; d.Usage.TotalTokens += 3 }}, | ||
| {name: "lost cache", change: func(d *aicodingsession.Data) { d.Usage.CacheReadInputTokens = 13 }}, | ||
| {name: "lost native cost", change: func(d *aicodingsession.Data) { d.Usage.EstimatedCostUSD = 0.1 }}, | ||
| {name: "unrelated stream", change: func(d *aicodingsession.Data) { d.RawSession["unrelated"] = nil }}, | ||
| {name: "wrong evidence version", change: func(d *aicodingsession.Data) { d.SchemaVersion = "v2" }}, | ||
| } { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| // Given | ||
| session := piSubagentCheckSession() | ||
| if tc.change != nil { | ||
| tc.change(evidence(session)) | ||
| } | ||
| // When | ||
| err := checkSubagents(session) | ||
| // Then | ||
| if tc.change == nil { | ||
| require.NoError(t, err) | ||
| require.NoError(t, checkCacheTokenAccounting(session)) | ||
| } else { | ||
| require.Error(t, err) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestPiSubagentSourcePinWhenMissingOrModified(t *testing.T) { | ||
| for _, modified := range []bool{false, true} { | ||
| t.Run(map[bool]string{false: "missing", true: "modified"}[modified], func(t *testing.T) { | ||
| // Given | ||
| dir := t.TempDir() | ||
| if modified { | ||
| require.NoError(t, os.WriteFile(filepath.Join(dir, "index.ts"), []byte("different extension"), 0o600)) | ||
| } | ||
| // When | ||
| err := verifyPiSubagentSource(dir) | ||
| // Then | ||
| require.Error(t, err) | ||
| if modified { | ||
| assert.ErrorContains(t, err, piSubagentCommit) | ||
| } | ||
| }) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: The Pi Subagents cell is set to Partial without any end-to-end or manual result. This file says Pi cells stay Unknown until a live result or explicit manual check exists, and the new live scenario did not run. Set this cell back to Unknown until the pinned-format scenario passes.
Prompt for AI agents