feat(tasks): attribute events, changes and config to the attempt that produced them
The events table had no attempt column, so two attempts of the same task were indistinguishable: a retried task's stage events interleaved into one timeline and nothing could say which run produced a given result. - events gains an `attempt` column through the existing presence-gated migrateTasks loop rather than a version bump, so user_version stays 3 and an existing archie.db is migrated in place. A legacy-database test builds the pre-change schema and proves both that existing rows survive unattributed (attempt = 0) and that a new value round-trips. - Event.attempt = 11 and ReadTaskLogRequest.stage = 9 are field additions to existing messages: no new RPC, no new table, and no change to any canonical error message that crosses the state-store wire. - Every task event the workflow engine emits now carries the attempt. Producers that have no attempt yet (task_queued, binding_dispatch_failure) stay unattributed rather than guessing one. - Changed files are captured as a durable changes_captured event at commit and push time, reusing the existing three-dot diff primitive: paths from FilePatches(), counts from Stats(), base_sha recorded as the merge base actually diffed rather than the base tip, a 200-file cap with totals kept complete. Consumption goes through an unexported optional interface so workflow.Trees -- the yaegi capability surface for interpreted stage plugins -- is not widened. A capture is also taken once the pull request exists, so the capture can link it. - The per-attempt configuration is captured as a durable config_captured event carrying the non-secret config.TaskConfig, instead of a new table plus two new state-store RPCs: events are already this system's per-attempt provenance stream, so a table would have given one feature two provenance mechanisms. Redaction is proven against canary secrets. Measured payload: 539 bytes typical, 2333 bytes at 20 models. - Captures carry a schema marker and are refused unless their key set matches the declared payload shape, so drift surfaces as "recorded but could not be read" rather than as a capture of zeroes. - Three read endpoints serve the attempt rail, the changed-file captures and a raw debug view, mapping to UI-owned response types rather than dumping store types. - The task-log read gains a stage filter, bound to the stage logger for that stage's own lines; agent and tool output records no stage. A task-scoped grant may already insert events on its own task, so this provenance is exactly as trustworthy as the rest of that task's event stream. That limit is documented rather than papered over.
This commit is contained in:
1 parent
14e7512d14
commit
2c09f42ff4
39 files changed
+4264
-83
No files matched your search
@@ -0,0 +1,343 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// Stage/attempt statuses the attempt rail reports. They are one vocabulary
|
||||
// because the rail renders one status per stage and one for the attempt it
|
||||
// belongs to; "unknown" exists only for an attempt whose events carry no stage
|
||||
// information at all, so a rail never claims a verdict it did not observe.
|
||||
const (
|
||||
attemptStatusOK = "ok"
|
||||
attemptStatusFailed = "failed"
|
||||
attemptStatusInterrupted = "interrupted"
|
||||
attemptStatusRunning = "running"
|
||||
attemptStatusUnknown = "unknown"
|
||||
)
|
||||
|
||||
// taskAttemptsView is GET /api/tasks/{id}/attempts: every attempt of one task
|
||||
// with its stages inline, so the rail and the attempt selector cannot disagree
|
||||
// and the page makes no per-attempt calls of its own.
|
||||
type taskAttemptsView struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
// CurrentAttempt is the task's own attempt, echoed so the page can show
|
||||
// which run the daemon is on even when that attempt has no events yet.
|
||||
CurrentAttempt int `json:"current_attempt"`
|
||||
// UnattributedEvents counts events whose attempt is 0. It exists so the
|
||||
// page can say honestly that older activity cannot be attributed instead
|
||||
// of presenting it as a first run.
|
||||
UnattributedEvents int `json:"unattributed_events"`
|
||||
Attempts []taskAttemptView `json:"attempts"`
|
||||
}
|
||||
|
||||
// taskAttemptView is one attempt's rail entry. The bounds and duration are
|
||||
// measured from the attempt's own events: the span between its first and last
|
||||
// recorded event, which therefore includes any waiting-for-a-human gap rather
|
||||
// than understating wall time (design AMENDMENTS 0.1, F3). Every optional
|
||||
// field is omitted when it is not known rather than sent as a zero.
|
||||
type taskAttemptView struct {
|
||||
Attempt int `json:"attempt"`
|
||||
Status string `json:"status"`
|
||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
||||
DurationMS *int64 `json:"duration_ms,omitempty"`
|
||||
EventCount int `json:"event_count"`
|
||||
Stages []taskStageView `json:"stages"`
|
||||
}
|
||||
|
||||
// taskStageView is one stage occurrence within an attempt. Error is always
|
||||
// present (empty when the stage recorded none) so a consumer can tell "no error
|
||||
// text" from a field it did not receive.
|
||||
type taskStageView struct {
|
||||
Name string `json:"name"`
|
||||
Seq int `json:"seq"`
|
||||
Status string `json:"status"`
|
||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||
DurationMS *int64 `json:"duration_ms,omitempty"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// handleTaskAttempts serves the stage rail: one task's attempts, each with the
|
||||
// stages it recorded.
|
||||
func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
|
||||
t, ok := s.taskByPathID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
evs, err := s.Store.TaskEvents(r.Context(), t.ID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
attempts, unattributed := attemptsFromEvents(evs, t.Status, t.Attempt)
|
||||
writeJSON(w, taskAttemptsView{
|
||||
TaskID: t.ID,
|
||||
CurrentAttempt: t.Attempt,
|
||||
UnattributedEvents: unattributed,
|
||||
Attempts: attempts,
|
||||
})
|
||||
}
|
||||
|
||||
// taskByPathID resolves a task route's {id} to the task it names, answering the
|
||||
// request itself and reporting false when it cannot. An unknown task is 404
|
||||
// plain text -- TaskByID says "no such row" the same way it says "here is the
|
||||
// row", so the distinction is drawn here rather than leaked to the page.
|
||||
func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Task, bool) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
return nil, false
|
||||
}
|
||||
t, err := s.Store.TaskByID(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return nil, false
|
||||
}
|
||||
if t == nil {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
return t, true
|
||||
}
|
||||
|
||||
// taskAttemptTarget resolves a per-attempt read: the task its {id} names and the
|
||||
// attempt it asks for. An absent or zero "attempt" parameter selects the task's
|
||||
// current attempt, which is what a human means by "why did this park?" -- the
|
||||
// most recent run, not an arbitrary earlier retry. Zero is not an attempt: it is
|
||||
// the value that means "unattributed" on an event, so reading "attempt zero"
|
||||
// would read a bucket rather than a run.
|
||||
func (s *Server) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) {
|
||||
t, ok := s.taskByPathID(w, r)
|
||||
if !ok {
|
||||
return nil, 0, false
|
||||
}
|
||||
attempt := t.Attempt
|
||||
raw := strings.TrimSpace(r.URL.Query().Get("attempt"))
|
||||
if raw == "" {
|
||||
return t, attempt, true
|
||||
}
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
http.Error(w, "bad attempt", http.StatusBadRequest)
|
||||
return nil, 0, false
|
||||
}
|
||||
if parsed != 0 {
|
||||
attempt = parsed
|
||||
}
|
||||
return t, attempt, true
|
||||
}
|
||||
|
||||
// attemptsFromEvents folds a task's timeline into its rail: one entry per
|
||||
// attempt the events attribute to, ordered by attempt, plus the number of events
|
||||
// that carry no attempt at all.
|
||||
//
|
||||
// Events with attempt 0 are counted and then dropped, never grouped. Zero means
|
||||
// unattributed -- every row written before the column existed and every
|
||||
// deliberately task-agnostic producer carries it -- so grouping them would
|
||||
// present unrelated activity as attempt zero's rail.
|
||||
func attemptsFromEvents(evs []events.Event, taskStatus string, currentAttempt int) ([]taskAttemptView, int) {
|
||||
grouped := make(map[int][]events.Event)
|
||||
numbers := make([]int, 0, 4)
|
||||
unattributed := 0
|
||||
for _, e := range evs {
|
||||
if e.Attempt == 0 {
|
||||
unattributed++
|
||||
continue
|
||||
}
|
||||
if _, seen := grouped[e.Attempt]; !seen {
|
||||
numbers = append(numbers, e.Attempt)
|
||||
}
|
||||
grouped[e.Attempt] = append(grouped[e.Attempt], e)
|
||||
}
|
||||
sort.Ints(numbers)
|
||||
|
||||
attempts := make([]taskAttemptView, 0, len(numbers))
|
||||
for _, number := range numbers {
|
||||
attempts = append(attempts, attemptRail(number, grouped[number], taskStatus, currentAttempt))
|
||||
}
|
||||
return attempts, unattributed
|
||||
}
|
||||
|
||||
// attemptRail derives one attempt's status, bounds and stages from its events.
|
||||
func attemptRail(number int, evs []events.Event, taskStatus string, currentAttempt int) taskAttemptView {
|
||||
// The task's own record is the only honest source for "is this still
|
||||
// happening": an unpaired start on any other attempt ended without
|
||||
// finishing -- parked, retried, crashed or restarted -- so it is reported
|
||||
// as interrupted rather than left looking permanently in flight.
|
||||
inFlight := number == currentAttempt && taskStatus == task.StatusRunning
|
||||
|
||||
first, last := attemptBounds(evs)
|
||||
stages := foldStages(evs, inFlight)
|
||||
attempt := taskAttemptView{
|
||||
Attempt: number,
|
||||
Status: attemptStatus(stages, inFlight),
|
||||
EventCount: len(evs),
|
||||
Stages: stages,
|
||||
}
|
||||
if !first.IsZero() {
|
||||
attempt.StartedAt = &first
|
||||
}
|
||||
// A finished_at is only claimed for an attempt that has an end: a running
|
||||
// one has none yet, and an unknown one never had stage information to time.
|
||||
if !last.IsZero() && attempt.Status != attemptStatusRunning && attempt.Status != attemptStatusUnknown {
|
||||
attempt.FinishedAt = &last
|
||||
if !first.IsZero() {
|
||||
span := last.Sub(first).Milliseconds()
|
||||
attempt.DurationMS = &span
|
||||
}
|
||||
}
|
||||
return attempt
|
||||
}
|
||||
|
||||
// attemptBounds is the span of an attempt's own recorded events: the earliest
|
||||
// and latest timestamp any of them carries. A zero time contributes nothing -- a
|
||||
// record whose timestamp did not parse is not evidence of when it happened.
|
||||
func attemptBounds(evs []events.Event) (first, last time.Time) {
|
||||
for _, e := range evs {
|
||||
if e.At.IsZero() {
|
||||
continue
|
||||
}
|
||||
if first.IsZero() || e.At.Before(first) {
|
||||
first = e.At
|
||||
}
|
||||
if last.IsZero() || e.At.After(last) {
|
||||
last = e.At
|
||||
}
|
||||
}
|
||||
return first, last
|
||||
}
|
||||
|
||||
// foldStages builds an attempt's ordered stage occurrences. A stage start is
|
||||
// folded as an OPEN stage (status empty) until a matching finish closes it;
|
||||
// resolving what is left needs the task's own record, so an open stage is
|
||||
// running only while the daemon is executing this attempt and interrupted
|
||||
// otherwise.
|
||||
func foldStages(evs []events.Event, inFlight bool) []taskStageView {
|
||||
stages := []taskStageView{}
|
||||
for _, e := range evs {
|
||||
switch e.Kind {
|
||||
case events.KindStageStart:
|
||||
started := e.At
|
||||
stages = append(stages, taskStageView{Name: e.Stage, Seq: len(stages), StartedAt: &started})
|
||||
case events.KindStageFinish:
|
||||
stages = finishStage(stages, e)
|
||||
}
|
||||
}
|
||||
for i := range stages {
|
||||
if stages[i].Status != "" {
|
||||
continue
|
||||
}
|
||||
stages[i].Status = attemptStatusInterrupted
|
||||
if inFlight {
|
||||
stages[i].Status = attemptStatusRunning
|
||||
}
|
||||
}
|
||||
return stages
|
||||
}
|
||||
|
||||
// attemptStatus reads one status off an attempt's stages. The task's own record
|
||||
// outranks the events: an attempt the daemon is executing right now is running
|
||||
// whatever its events have recorded so far -- including the ones that have
|
||||
// recorded no stages at all. Otherwise no stage is left RUNNING to read: every
|
||||
// stage still open when the daemon is not executing this attempt is folded as
|
||||
// interrupted, which is what the next case reports.
|
||||
func attemptStatus(stages []taskStageView, inFlight bool) string {
|
||||
if inFlight {
|
||||
return attemptStatusRunning
|
||||
}
|
||||
switch {
|
||||
case anyStageStatus(stages, attemptStatusFailed):
|
||||
return attemptStatusFailed
|
||||
case anyStageStatus(stages, attemptStatusInterrupted):
|
||||
return attemptStatusInterrupted
|
||||
case len(stages) == 0:
|
||||
// The attempt exists only because events attributed to it do; if none
|
||||
// of them recorded a stage there is no verdict to report.
|
||||
return attemptStatusUnknown
|
||||
default:
|
||||
return attemptStatusOK
|
||||
}
|
||||
}
|
||||
|
||||
// finishStage applies one stage_finish event, closing the earliest still-open
|
||||
// stage of the same name. A finish with no matching start still yields the
|
||||
// stage -- with no start time rather than an invented one -- because the stage
|
||||
// demonstrably ran and dropping it would hide a failure.
|
||||
func finishStage(stages []taskStageView, e events.Event) []taskStageView {
|
||||
status, errText := stageOutcome(e.Data)
|
||||
recorded, hasRecorded := durationMillis(e.Data["duration_ms"])
|
||||
|
||||
idx := -1
|
||||
for i := range stages {
|
||||
if stages[i].Name == e.Stage && stages[i].Status == "" {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if idx < 0 {
|
||||
stages = append(stages, taskStageView{Name: e.Stage, Seq: len(stages)})
|
||||
idx = len(stages) - 1
|
||||
}
|
||||
stages[idx].Status = status
|
||||
stages[idx].Error = errText
|
||||
switch {
|
||||
case hasRecorded:
|
||||
// The producer's own measurement of the stage body, preferred over the
|
||||
// gap between two event timestamps.
|
||||
stages[idx].DurationMS = &recorded
|
||||
case stages[idx].StartedAt != nil && !e.At.IsZero():
|
||||
span := e.At.Sub(*stages[idx].StartedAt).Milliseconds()
|
||||
stages[idx].DurationMS = &span
|
||||
}
|
||||
return stages
|
||||
}
|
||||
|
||||
// stageOutcome reads a stage_finish event's own verdict. An interrupted finish
|
||||
// is interrupted even though it also carries the cancellation error text; a
|
||||
// non-empty error is a failure; anything else is ok. There is no exit code
|
||||
// anywhere in this system, so no stage is ever badged as passing -- the status
|
||||
// reports how the stage ended, not how well it went.
|
||||
func stageOutcome(data map[string]any) (status, errText string) {
|
||||
errText, _ = data["error"].(string)
|
||||
if interrupted, _ := data["interrupted"].(bool); interrupted {
|
||||
return attemptStatusInterrupted, errText
|
||||
}
|
||||
if errText != "" {
|
||||
return attemptStatusFailed, errText
|
||||
}
|
||||
return attemptStatusOK, ""
|
||||
}
|
||||
|
||||
// durationMillis reads a millisecond duration a producer recorded in an event's
|
||||
// data. A value that crossed JSON is float64 and one built in this process is
|
||||
// an integer, so both spellings are accepted; anything else is reported as "not
|
||||
// recorded" rather than as zero.
|
||||
func durationMillis(v any) (int64, bool) {
|
||||
switch n := v.(type) {
|
||||
case int:
|
||||
return int64(n), true
|
||||
case int64:
|
||||
return n, true
|
||||
case float64:
|
||||
return int64(n), true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func anyStageStatus(stages []taskStageView, status string) bool {
|
||||
for _, s := range stages {
|
||||
if s.Status == status {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// railBase is the fixed clock the rail fixtures hang off, so every timestamp
|
||||
// and duration asserted below is a literal rather than a tolerance.
|
||||
var railBase = time.Date(2026, 9, 18, 7, 0, 0, 0, time.UTC)
|
||||
|
||||
func stageStartEvent(taskID int64, attempt int, stage string, at time.Time) events.Event {
|
||||
return events.Event{Kind: events.KindStageStart, TaskID: taskID, Attempt: attempt, Stage: stage, At: at}
|
||||
}
|
||||
|
||||
func stageFinishEvent(taskID int64, attempt int, stage string, at time.Time, data map[string]any) events.Event {
|
||||
return events.Event{Kind: events.KindStageFinish, TaskID: taskID, Attempt: attempt, Stage: stage, At: at, Data: data}
|
||||
}
|
||||
|
||||
func insertTaskEvent(t *testing.T, srv *Server, ev events.Event) {
|
||||
t.Helper()
|
||||
if _, err := srv.Store.InsertEvent(t.Context(), ev); err != nil {
|
||||
t.Fatalf("insert %s event: %v", ev.Kind, err)
|
||||
}
|
||||
}
|
||||
|
||||
// getTaskAPI issues one task-detail request through the real mux. A route that
|
||||
// is not registered falls through to the SPA asset handler and answers 200 with
|
||||
// an HTML page, so using the mux makes a missing registration fail the shape
|
||||
// assertions below rather than passing quietly.
|
||||
func getTaskAPI(t *testing.T, srv *Server, url string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func taskRoute(id int64, suffix string) string {
|
||||
return "/api/tasks/" + strconv.FormatInt(id, 10) + suffix
|
||||
}
|
||||
|
||||
// twoAttemptTask drives one task through the lifecycle the rail has to read:
|
||||
// claim (attempt 1), park, retry, claim (attempt 2), leaving the task running
|
||||
// on its second attempt. No test writes an attempt number directly, so the
|
||||
// attempt under test is the one the real lifecycle produced.
|
||||
func twoAttemptTask(t *testing.T, srv *Server) *workflow.Task {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == nil {
|
||||
t.Fatal("ClaimNext returned no task")
|
||||
}
|
||||
if first.Attempt != 1 {
|
||||
t.Fatalf("first claim attempt = %d, want 1", first.Attempt)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, first.ID, workflow.StatusRunning, workflow.StatusParked, "stage implement: builder exited 1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := srv.Store.RetryTask(ctx, first.ID, workflow.StatusParked, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second == nil {
|
||||
t.Fatal("second claim returned no task")
|
||||
}
|
||||
if second.Attempt != 2 || second.Status != workflow.StatusRunning {
|
||||
t.Fatalf("second claim = attempt %d status %q, want attempt 2 running", second.Attempt, second.Status)
|
||||
}
|
||||
return second
|
||||
}
|
||||
|
||||
// summarizeAttemptRail renders a folded rail as one line per attempt so a table
|
||||
// case states the derivation it expects without a struct literal per stage:
|
||||
// "attempt:status[name:status:duration[#error][@nostart],...] duration".
|
||||
func summarizeAttemptRail(attempts []taskAttemptView) string {
|
||||
lines := make([]string, 0, len(attempts))
|
||||
for _, a := range attempts {
|
||||
stages := make([]string, 0, len(a.Stages))
|
||||
for _, s := range a.Stages {
|
||||
stage := s.Name + ":" + s.Status + ":" + durationToken(s.DurationMS)
|
||||
if s.StartedAt == nil {
|
||||
stage += "@nostart"
|
||||
}
|
||||
if s.Error != "" {
|
||||
stage += "#" + s.Error
|
||||
}
|
||||
stages = append(stages, stage)
|
||||
}
|
||||
line := strconv.Itoa(a.Attempt) + ":" + a.Status + "[" + strings.Join(stages, ",") + "] " + durationToken(a.DurationMS)
|
||||
lines = append(lines, line)
|
||||
}
|
||||
return strings.Join(lines, " | ")
|
||||
}
|
||||
|
||||
func durationToken(ms *int64) string {
|
||||
if ms == nil {
|
||||
return "?"
|
||||
}
|
||||
return strconv.FormatInt(*ms, 10)
|
||||
}
|
||||
|
||||
// TestAttemptsFromEventsDerivesEveryRailRule is the table behind R1: every
|
||||
// status rule the attempt rail depends on, one case each, plus the cases that
|
||||
// would otherwise be answered by inventing data (a finish with no start, an
|
||||
// event set with no stage information, events carrying no attempt at all).
|
||||
func TestAttemptsFromEventsDerivesEveryRailRule(t *testing.T) {
|
||||
at := railBase.Add
|
||||
duration := func(ms int64) map[string]any { return map[string]any{"duration_ms": ms} }
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
taskStatus string
|
||||
currentAttempt int
|
||||
evs []events.Event
|
||||
want string
|
||||
wantUnattributed int
|
||||
}{
|
||||
{
|
||||
name: "a finished stage is ok and the attempt reports its measured span",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
stageStartEvent(1, 1, "prepare", at(0)),
|
||||
stageFinishEvent(1, 1, "prepare", at(time.Second), duration(1000)),
|
||||
},
|
||||
want: "1:ok[prepare:ok:1000] 1000",
|
||||
},
|
||||
{
|
||||
name: "a failed stage fails the attempt and carries the error text",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
stageStartEvent(1, 1, "implement", at(0)),
|
||||
stageFinishEvent(1, 1, "implement", at(2*time.Second), map[string]any{
|
||||
"duration_ms": int64(2000),
|
||||
"error": "stage implement: builder exited 1",
|
||||
}),
|
||||
},
|
||||
want: "1:failed[implement:failed:2000#stage implement: builder exited 1] 2000",
|
||||
},
|
||||
{
|
||||
name: "an interrupted stage reads interrupted even though the error text is recorded",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
stageStartEvent(1, 1, "implement", at(0)),
|
||||
stageFinishEvent(1, 1, "implement", at(time.Second), map[string]any{
|
||||
"duration_ms": int64(1000),
|
||||
"error": "context canceled",
|
||||
"interrupted": true,
|
||||
}),
|
||||
},
|
||||
want: "1:interrupted[implement:interrupted:1000#context canceled] 1000",
|
||||
},
|
||||
{
|
||||
name: "a failed stage outranks an interrupted one",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
stageStartEvent(1, 1, "a", at(0)),
|
||||
stageFinishEvent(1, 1, "a", at(time.Second), map[string]any{"duration_ms": int64(1000), "error": "boom"}),
|
||||
stageStartEvent(1, 1, "b", at(2*time.Second)),
|
||||
stageFinishEvent(1, 1, "b", at(3*time.Second), map[string]any{
|
||||
"duration_ms": int64(1000), "error": "canceled", "interrupted": true,
|
||||
}),
|
||||
},
|
||||
want: "1:failed[a:failed:1000#boom,b:interrupted:1000#canceled] 3000",
|
||||
},
|
||||
{
|
||||
name: "an unpaired start on the task's current in-flight attempt is running",
|
||||
taskStatus: workflow.StatusRunning, currentAttempt: 2,
|
||||
evs: []events.Event{stageStartEvent(1, 2, "implement", at(0))},
|
||||
want: "2:running[implement:running:?] ?",
|
||||
},
|
||||
{
|
||||
name: "an unpaired start on a superseded attempt is interrupted",
|
||||
taskStatus: workflow.StatusRunning, currentAttempt: 2,
|
||||
evs: []events.Event{stageStartEvent(1, 1, "implement", at(0))},
|
||||
want: "1:interrupted[implement:interrupted:?] 0",
|
||||
},
|
||||
{
|
||||
name: "an unpaired start on a parked task's own attempt is interrupted",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{stageStartEvent(1, 1, "implement", at(0))},
|
||||
want: "1:interrupted[implement:interrupted:?] 0",
|
||||
},
|
||||
{
|
||||
name: "a finish with no start yields the stage without an invented start time",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
stageFinishEvent(1, 1, "commit", at(0), duration(4000)),
|
||||
},
|
||||
want: "1:ok[commit:ok:4000@nostart] 0",
|
||||
},
|
||||
{
|
||||
name: "a finish without a recorded duration derives it from its own start",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
stageStartEvent(1, 1, "prepare", at(0)),
|
||||
stageFinishEvent(1, 1, "prepare", at(10*time.Second), nil),
|
||||
},
|
||||
want: "1:ok[prepare:ok:10000] 10000",
|
||||
},
|
||||
{
|
||||
name: "a repeated stage name yields one rail entry per occurrence",
|
||||
taskStatus: workflow.StatusRunning, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
stageStartEvent(1, 1, "implement", at(0)),
|
||||
stageFinishEvent(1, 1, "implement", at(time.Second), duration(1000)),
|
||||
stageStartEvent(1, 1, "implement", at(2*time.Second)),
|
||||
},
|
||||
want: "1:running[implement:ok:1000,implement:running:?] ?",
|
||||
},
|
||||
{
|
||||
name: "a later attempt does not absorb the earlier attempt's stages",
|
||||
taskStatus: workflow.StatusRunning, currentAttempt: 2,
|
||||
evs: []events.Event{
|
||||
stageStartEvent(1, 1, "prepare", at(0)),
|
||||
stageFinishEvent(1, 1, "prepare", at(time.Second), duration(1000)),
|
||||
stageStartEvent(1, 2, "implement", at(2*time.Second)),
|
||||
},
|
||||
want: "1:ok[prepare:ok:1000] 1000 | 2:running[implement:running:?] ?",
|
||||
},
|
||||
{
|
||||
name: "events carrying no attempt are counted, never grouped",
|
||||
taskStatus: workflow.StatusQueued, currentAttempt: 0,
|
||||
evs: []events.Event{
|
||||
{Kind: events.KindStageStart, TaskID: 1, Stage: "prepare", At: at(0)},
|
||||
{Kind: events.KindStageFinish, TaskID: 1, Stage: "prepare", At: at(time.Second), Data: duration(1000)},
|
||||
},
|
||||
wantUnattributed: 2,
|
||||
},
|
||||
{
|
||||
name: "a task with no events has no attempts and nothing unattributed",
|
||||
taskStatus: workflow.StatusQueued, currentAttempt: 0,
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "an attempt whose events carry no stage information is unknown",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
{Kind: events.KindAgentFinish, TaskID: 1, Attempt: 1, At: at(0), Data: map[string]any{"status": "ok"}},
|
||||
},
|
||||
want: "1:unknown[] ?",
|
||||
},
|
||||
{
|
||||
name: "the task's own record keeps the current attempt running with no stage events",
|
||||
taskStatus: workflow.StatusRunning, currentAttempt: 1,
|
||||
evs: []events.Event{
|
||||
{Kind: events.KindAgentFinish, TaskID: 1, Attempt: 1, At: at(0), Data: map[string]any{"status": "ok"}},
|
||||
},
|
||||
want: "1:running[] ?",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
attempts, unattributed := attemptsFromEvents(tt.evs, tt.taskStatus, tt.currentAttempt)
|
||||
if got := summarizeAttemptRail(attempts); got != tt.want {
|
||||
t.Errorf("rail = %q, want %q", got, tt.want)
|
||||
}
|
||||
if unattributed != tt.wantUnattributed {
|
||||
t.Errorf("unattributed = %d, want %d", unattributed, tt.wantUnattributed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskAttemptsRendersBothAttemptsOfARetry pins the wire shape: an
|
||||
// attempt's ordered stages with name, start time, duration, terminal status and
|
||||
// error text, the task's current attempt, and attempt 1's rail excluding
|
||||
// attempt 2's stages.
|
||||
func TestHandleTaskAttemptsRendersBothAttemptsOfARetry(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
at := railBase.Add
|
||||
|
||||
insertTaskEvent(t, srv, stageStartEvent(current.ID, 1, "prepare", at(0)))
|
||||
insertTaskEvent(t, srv, stageFinishEvent(current.ID, 1, "prepare", at(1200*time.Millisecond),
|
||||
map[string]any{"duration_ms": int64(1200)}))
|
||||
insertTaskEvent(t, srv, stageStartEvent(current.ID, 1, "implement", at(1323*time.Millisecond)))
|
||||
insertTaskEvent(t, srv, stageFinishEvent(current.ID, 1, "implement", at(231323*time.Millisecond),
|
||||
map[string]any{"duration_ms": int64(230000), "error": "stage implement: builder exited 1"}))
|
||||
insertTaskEvent(t, srv, stageStartEvent(current.ID, 2, "implement", at(time.Hour)))
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/attempts"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if raw := w.Body.String(); !strings.Contains(raw, `"error":""`) {
|
||||
t.Errorf("body = %s, want the ok stage's error field present and empty rather than omitted", raw)
|
||||
}
|
||||
|
||||
var body struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
CurrentAttempt int `json:"current_attempt"`
|
||||
UnattributedEvents int `json:"unattributed_events"`
|
||||
Attempts []struct {
|
||||
Attempt int `json:"attempt"`
|
||||
Status string `json:"status"`
|
||||
StartedAt *time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
DurationMS *int64 `json:"duration_ms"`
|
||||
EventCount int `json:"event_count"`
|
||||
Stages []struct {
|
||||
Name string `json:"name"`
|
||||
Seq int `json:"seq"`
|
||||
Status string `json:"status"`
|
||||
StartedAt *time.Time `json:"started_at"`
|
||||
DurationMS *int64 `json:"duration_ms"`
|
||||
Error string `json:"error"`
|
||||
} `json:"stages"`
|
||||
} `json:"attempts"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.TaskID != current.ID || body.CurrentAttempt != 2 || body.UnattributedEvents != 0 {
|
||||
t.Fatalf("envelope = task %d, current attempt %d, unattributed %d; want %d, 2, 0",
|
||||
body.TaskID, body.CurrentAttempt, body.UnattributedEvents, current.ID)
|
||||
}
|
||||
if len(body.Attempts) != 2 {
|
||||
t.Fatalf("attempts = %d, want 2 (%s)", len(body.Attempts), w.Body)
|
||||
}
|
||||
|
||||
first := body.Attempts[0]
|
||||
if first.Attempt != 1 || first.Status != "failed" {
|
||||
t.Errorf("attempt 1 = %d/%q, want 1/failed", first.Attempt, first.Status)
|
||||
}
|
||||
if first.EventCount != 4 {
|
||||
t.Errorf("attempt 1 event_count = %d, want 4", first.EventCount)
|
||||
}
|
||||
if first.StartedAt == nil || !first.StartedAt.Equal(at(0)) {
|
||||
t.Errorf("attempt 1 started_at = %v, want %v", first.StartedAt, at(0))
|
||||
}
|
||||
if first.FinishedAt == nil || !first.FinishedAt.Equal(at(231323*time.Millisecond)) {
|
||||
t.Errorf("attempt 1 finished_at = %v, want %v", first.FinishedAt, at(231323*time.Millisecond))
|
||||
}
|
||||
if first.DurationMS == nil || *first.DurationMS != 231323 {
|
||||
t.Errorf("attempt 1 duration_ms = %v, want 231323", first.DurationMS)
|
||||
}
|
||||
if len(first.Stages) != 2 {
|
||||
t.Fatalf("attempt 1 stages = %d, want 2 (%s)", len(first.Stages), w.Body)
|
||||
}
|
||||
prepare := first.Stages[0]
|
||||
if prepare.Name != "prepare" || prepare.Seq != 0 || prepare.Status != "ok" || prepare.Error != "" {
|
||||
t.Errorf("stage 0 = %+v, want prepare/0/ok with no error", prepare)
|
||||
}
|
||||
if prepare.DurationMS == nil || *prepare.DurationMS != 1200 {
|
||||
t.Errorf("stage 0 duration_ms = %v, want 1200", prepare.DurationMS)
|
||||
}
|
||||
if prepare.StartedAt == nil || !prepare.StartedAt.Equal(at(0)) {
|
||||
t.Errorf("stage 0 started_at = %v, want %v", prepare.StartedAt, at(0))
|
||||
}
|
||||
implement := first.Stages[1]
|
||||
if implement.Name != "implement" || implement.Seq != 1 || implement.Status != "failed" {
|
||||
t.Errorf("stage 1 = %+v, want implement/1/failed", implement)
|
||||
}
|
||||
if implement.Error != "stage implement: builder exited 1" {
|
||||
t.Errorf("stage 1 error = %q, want the recorded error text", implement.Error)
|
||||
}
|
||||
if implement.DurationMS == nil || *implement.DurationMS != 230000 {
|
||||
t.Errorf("stage 1 duration_ms = %v, want 230000", implement.DurationMS)
|
||||
}
|
||||
|
||||
second := body.Attempts[1]
|
||||
if second.Attempt != 2 || second.Status != "running" || second.EventCount != 1 {
|
||||
t.Errorf("attempt 2 = %d/%q with %d events, want 2/running with 1", second.Attempt, second.Status, second.EventCount)
|
||||
}
|
||||
if second.FinishedAt != nil || second.DurationMS != nil {
|
||||
t.Errorf("attempt 2 finished_at = %v, duration_ms = %v; both must be omitted for a running attempt",
|
||||
second.FinishedAt, second.DurationMS)
|
||||
}
|
||||
if len(second.Stages) != 1 || second.Stages[0].Name != "implement" || second.Stages[0].Status != "running" {
|
||||
t.Fatalf("attempt 2 stages = %+v, want one running implement", second.Stages)
|
||||
}
|
||||
if second.Stages[0].Error != "" {
|
||||
t.Errorf("attempt 2 stage error = %q, want empty", second.Stages[0].Error)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskAttemptsSeparatesUnattributedEventsFromAFirstRun pins the
|
||||
// honesty requirement: events that carry no attempt cannot be presented as
|
||||
// attempt 1, and a task with nothing recorded at all is a different answer from
|
||||
// a task whose events predate attribution.
|
||||
func TestHandleTaskAttemptsSeparatesUnattributedEventsFromAFirstRun(t *testing.T) {
|
||||
t.Run("a task with no events at all", func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(t.Context(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(task.ID, "/attempts"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
raw := w.Body.String()
|
||||
if !strings.Contains(raw, `"attempts":[]`) {
|
||||
t.Errorf("body = %s, want an empty attempts array rather than null", raw)
|
||||
}
|
||||
if !strings.Contains(raw, `"unattributed_events":0`) {
|
||||
t.Errorf("body = %s, want unattributed_events 0 for a task with nothing recorded", raw)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("events that carry no attempt", func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(t.Context(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
insertTaskEvent(t, srv, stageStartEvent(task.ID, 0, "prepare", railBase))
|
||||
insertTaskEvent(t, srv, stageFinishEvent(task.ID, 0, "prepare", railBase.Add(time.Second),
|
||||
map[string]any{"duration_ms": int64(1000)}))
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(task.ID, "/attempts"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
UnattributedEvents int `json:"unattributed_events"`
|
||||
Attempts []struct {
|
||||
Attempt int `json:"attempt"`
|
||||
} `json:"attempts"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.UnattributedEvents != 2 {
|
||||
t.Errorf("unattributed_events = %d, want 2", body.UnattributedEvents)
|
||||
}
|
||||
if len(body.Attempts) != 0 {
|
||||
t.Errorf("attempts = %+v, want none: events carrying no attempt must never be presented as a run", body.Attempts)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestTaskDetailRoutesRejectUnknownTasksAndStoreFailures keeps the three new
|
||||
// reads on the existing task-route conventions: an unknown task is 404 plain
|
||||
// text (never 200 with an empty body), a store failure is 500, and a
|
||||
// non-numeric id is 400.
|
||||
func TestTaskDetailRoutesRejectUnknownTasksAndStoreFailures(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
if _, err := base.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
existing, err := base.Store.TaskByIssue(t.Context(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
eventsBroken := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, taskEventsErr: fmt.Errorf("db locked")},
|
||||
Log: base.Log,
|
||||
}
|
||||
lookupBroken := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, taskByIDErr: fmt.Errorf("db locked")},
|
||||
Log: base.Log,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
srv *Server
|
||||
id int64
|
||||
suffix string
|
||||
wantStatus int
|
||||
}{
|
||||
{"attempts unknown task", base, 999, "/attempts", http.StatusNotFound},
|
||||
{"changes unknown task", base, 999, "/changes", http.StatusNotFound},
|
||||
{"debug unknown task", base, 999, "/debug", http.StatusNotFound},
|
||||
{"attempts events failure", eventsBroken, existing.ID, "/attempts", http.StatusInternalServerError},
|
||||
{"changes events failure", eventsBroken, existing.ID, "/changes", http.StatusInternalServerError},
|
||||
{"debug events failure", eventsBroken, existing.ID, "/debug", http.StatusInternalServerError},
|
||||
{"attempts lookup failure", lookupBroken, existing.ID, "/attempts", http.StatusInternalServerError},
|
||||
{"changes lookup failure", lookupBroken, existing.ID, "/changes", http.StatusInternalServerError},
|
||||
{"debug lookup failure", lookupBroken, existing.ID, "/debug", http.StatusInternalServerError},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
w := getTaskAPI(t, tt.srv, taskRoute(tt.id, tt.suffix))
|
||||
if w.Code != tt.wantStatus {
|
||||
t.Errorf("GET %s = %d (%s), want %d", tt.suffix, w.Code, w.Body, tt.wantStatus)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for _, suffix := range []string{"/attempts", "/changes", "/debug"} {
|
||||
t.Run("non-numeric id "+suffix, func(t *testing.T) {
|
||||
w := getTaskAPI(t, base, "/api/tasks/not-a-number"+suffix)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("GET %s = %d (%s), want 400", suffix, w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The attempt parameter belongs to the per-attempt reads: /attempts returns
|
||||
// every attempt of the task, so it does not consume the parameter at all,
|
||||
// while /changes and /debug resolve it and must refuse a value that is not
|
||||
// an attempt number rather than silently read the current one.
|
||||
t.Run("non-numeric attempt on /attempts is not a parameter of that read", func(t *testing.T) {
|
||||
w := getTaskAPI(t, base, taskRoute(existing.ID, "/attempts?attempt=later"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("GET /attempts?attempt=later = %d (%s), want 200", w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
for _, suffix := range []string{"/changes", "/debug"} {
|
||||
t.Run("non-numeric attempt "+suffix, func(t *testing.T) {
|
||||
w := getTaskAPI(t, base, taskRoute(existing.ID, suffix+"?attempt=later"))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("GET %s?attempt=later = %d (%s), want 400", suffix, w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// taskChangesView is GET /api/tasks/{id}/changes: the change captures recorded
|
||||
// for one attempt. Found reports that a capture was recorded at all -- an empty
|
||||
// captures list without it would tell an operator that nothing changed, which is
|
||||
// not a claim this system can make about a run whose diffstat was never read.
|
||||
type taskChangesView struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Found bool `json:"found"`
|
||||
Captures []changeCaptureView `json:"captures"`
|
||||
}
|
||||
|
||||
// changeCaptureView is one capture: the diffstat measured at the moment the run
|
||||
// was committed or pushed, plus the repository and pull-request links the page
|
||||
// renders beside it. The URLs are filled from the same forge projection the task
|
||||
// list uses, so a capture links exactly where its task does.
|
||||
type changeCaptureView struct {
|
||||
CapturedAt time.Time `json:"captured_at"`
|
||||
CapturedAfter string `json:"captured_after"`
|
||||
Stage string `json:"stage"`
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Base string `json:"base"`
|
||||
Branch string `json:"branch"`
|
||||
HeadSHA string `json:"head_sha"`
|
||||
BaseSHA string `json:"base_sha"`
|
||||
PRNumber int `json:"pr_number"`
|
||||
RepoURL string `json:"repo_url,omitempty"`
|
||||
PRURL string `json:"pr_url,omitempty"`
|
||||
Totals task.ChangeTotals `json:"totals"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Files []task.FileChange `json:"files"`
|
||||
}
|
||||
|
||||
// capturePayload is one changes_captured event's data as the producer persists
|
||||
// it. The measured change itself reuses the shared task.ChangeStats identity the
|
||||
// producer writes with, so the two sides cannot drift into two spellings of one
|
||||
// diffstat.
|
||||
type capturePayload struct {
|
||||
Schema string `json:"schema"`
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Base string `json:"base"`
|
||||
Branch string `json:"branch"`
|
||||
PRNumber int `json:"pr_number"`
|
||||
CapturedAfter string `json:"captured_after"`
|
||||
Truncated bool `json:"truncated"`
|
||||
task.ChangeStats
|
||||
}
|
||||
|
||||
// capturePayloadKeys is the exact key set one capture carries, derived from
|
||||
// capturePayload's own json tags rather than restated beside them: the reader
|
||||
// and the key set cannot disagree. A payload that renamed, dropped or added a
|
||||
// key is refused, because reading it leniently is how a lost truncation marker
|
||||
// becomes "not truncated" and a dropped file list becomes "nothing changed".
|
||||
var capturePayloadKeys = structKeys(reflect.TypeFor[capturePayload]())
|
||||
|
||||
// structKeys collects the JSON key names a struct declares, recursing into the
|
||||
// embedded value structs a decoder flattens.
|
||||
func structKeys(t reflect.Type) map[string]struct{} {
|
||||
keys := make(map[string]struct{}, t.NumField())
|
||||
for field := range t.Fields() {
|
||||
if field.Anonymous {
|
||||
for key := range structKeys(field.Type) {
|
||||
keys[key] = struct{}{}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if name, _, _ := strings.Cut(field.Tag.Get("json"), ","); name != "" && name != "-" {
|
||||
keys[name] = struct{}{}
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// handleTaskChanges serves the changed files one attempt produced.
|
||||
func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
evs, err := s.Store.TaskEvents(r.Context(), t.ID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
captures, recorded := capturedChanges(evs, attempt)
|
||||
|
||||
// The links come from the task's own forge resolution, reused rather than
|
||||
// re-derived: the capture's own owner/repo/pr decide the URL, so a capture
|
||||
// taken before the PR existed has no pull-request link instead of one
|
||||
// pointing at a later attempt's PR.
|
||||
forge := s.resolveForge(r.Context())
|
||||
for i := range captures {
|
||||
target := task.Task{
|
||||
Owner: captures[i].Owner, Repo: captures[i].Repo,
|
||||
PRNumber: captures[i].PRNumber, Identity: t.Identity,
|
||||
}
|
||||
captures[i].RepoURL, _, captures[i].PRURL = taskURLs(target, forge(target))
|
||||
}
|
||||
|
||||
writeJSON(w, taskChangesView{TaskID: t.ID, Attempt: attempt, Found: recorded, Captures: captures})
|
||||
}
|
||||
|
||||
// capturedChanges folds a task's events into the captures recorded for one
|
||||
// attempt, oldest first (events are read in insert order, which is capture
|
||||
// order).
|
||||
//
|
||||
// recorded reports that the attempt has at least one capture event even when its
|
||||
// payload could not be read: a capture that happened is provenance whether or not
|
||||
// this read can decode it, and answering "no capture was recorded" would be a
|
||||
// false statement about it. A payload that is absent, in a schema this build does
|
||||
// not read, or otherwise malformed is skipped rather than failing the read.
|
||||
func capturedChanges(evs []events.Event, attempt int) (captures []changeCaptureView, recorded bool) {
|
||||
captures = []changeCaptureView{}
|
||||
for _, e := range evs {
|
||||
if e.Kind != events.KindChangesCaptured || e.Attempt != attempt {
|
||||
continue
|
||||
}
|
||||
recorded = true
|
||||
capture, ok := decodeCapture(e)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
captures = append(captures, capture)
|
||||
}
|
||||
return captures, recorded
|
||||
}
|
||||
|
||||
// decodeCapture reads one capture event. It reports false when the event carries
|
||||
// no data, when its payload is not in the schema this build reads, when its key
|
||||
// set is not exactly the one this reader declares, or when the payload is
|
||||
// malformed. The totals are passed through as recorded and never recomputed from
|
||||
// the file entries, because the producer's totals cover the full change set even
|
||||
// when the entries were capped.
|
||||
func decodeCapture(e events.Event) (changeCaptureView, bool) {
|
||||
if len(e.Data) == 0 {
|
||||
return changeCaptureView{}, false
|
||||
}
|
||||
raw, err := json.Marshal(e.Data)
|
||||
if err != nil {
|
||||
return changeCaptureView{}, false
|
||||
}
|
||||
var keys map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &keys); err != nil {
|
||||
return changeCaptureView{}, false
|
||||
}
|
||||
if len(keys) != len(capturePayloadKeys) {
|
||||
return changeCaptureView{}, false
|
||||
}
|
||||
for key := range capturePayloadKeys {
|
||||
if _, ok := keys[key]; !ok {
|
||||
return changeCaptureView{}, false
|
||||
}
|
||||
}
|
||||
var payload capturePayload
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return changeCaptureView{}, false
|
||||
}
|
||||
if payload.Schema != events.ChangesCapturedSchema {
|
||||
return changeCaptureView{}, false
|
||||
}
|
||||
files := payload.Files
|
||||
if len(files) > task.MaxCapturedFiles {
|
||||
// The producer bounds the list at task.MaxCapturedFiles and reports the
|
||||
// drop with truncated. More entries than the shared cap means the cap
|
||||
// was lost, and rendering them would present the loss as a complete
|
||||
// capture.
|
||||
return changeCaptureView{}, false
|
||||
}
|
||||
if files == nil {
|
||||
files = []task.FileChange{}
|
||||
}
|
||||
return changeCaptureView{
|
||||
CapturedAt: e.At,
|
||||
CapturedAfter: payload.CapturedAfter,
|
||||
Stage: e.Stage,
|
||||
Owner: payload.Owner,
|
||||
Repo: payload.Repo,
|
||||
Base: payload.Base,
|
||||
Branch: payload.Branch,
|
||||
HeadSHA: payload.HeadSHA,
|
||||
BaseSHA: payload.BaseSHA,
|
||||
PRNumber: payload.PRNumber,
|
||||
Totals: payload.Totals,
|
||||
Truncated: payload.Truncated,
|
||||
Files: files,
|
||||
}, true
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// captureData is the shape the producer persists for one capture: the diffstat
|
||||
// measured at the moment a run was committed or pushed. The reader's fixtures
|
||||
// are built here; nothing in this file re-derives a capture.
|
||||
func captureData(files []any, totals map[string]any) map[string]any {
|
||||
return map[string]any{
|
||||
"schema": events.ChangesCapturedSchema,
|
||||
"owner": "acme", "repo": "widget", "base": "main", "branch": "feat/2-x",
|
||||
"head_sha": "head-sha", "base_sha": "base-sha", "pr_number": 0,
|
||||
"captured_after": "commit-push",
|
||||
"files": files, "totals": totals, "truncated": false,
|
||||
}
|
||||
}
|
||||
|
||||
func modifiedFile(path string, additions, deletions int) map[string]any {
|
||||
return map[string]any{
|
||||
"path": path, "old_path": "", "status": "modified",
|
||||
"additions": additions, "deletions": deletions, "binary": false,
|
||||
}
|
||||
}
|
||||
|
||||
func insertCapture(t *testing.T, srv *Server, taskID int64, attempt int, stage string, data map[string]any) {
|
||||
t.Helper()
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindChangesCaptured, TaskID: taskID, Attempt: attempt, Stage: stage,
|
||||
At: railBase.Add(time.Duration(attempt) * time.Minute), Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// changesResponse is the endpoint's body as the page consumes it, decoded by
|
||||
// field name so the contract is asserted rather than substring-matched.
|
||||
type changesResponse struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Found bool `json:"found"`
|
||||
Captures []captureViewJSON `json:"captures"`
|
||||
}
|
||||
|
||||
type captureViewJSON struct {
|
||||
CapturedAt time.Time `json:"captured_at"`
|
||||
CapturedAfter string `json:"captured_after"`
|
||||
Stage string `json:"stage"`
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Base string `json:"base"`
|
||||
Branch string `json:"branch"`
|
||||
HeadSHA string `json:"head_sha"`
|
||||
BaseSHA string `json:"base_sha"`
|
||||
PRNumber int `json:"pr_number"`
|
||||
RepoURL string `json:"repo_url"`
|
||||
PRURL string `json:"pr_url"`
|
||||
Totals changeTotalsJSON `json:"totals"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Files []fileChangeJSON `json:"files"`
|
||||
}
|
||||
|
||||
type changeTotalsJSON struct {
|
||||
Files int `json:"files"`
|
||||
Additions int `json:"additions"`
|
||||
Deletions int `json:"deletions"`
|
||||
}
|
||||
|
||||
type fileChangeJSON struct {
|
||||
Path string `json:"path"`
|
||||
OldPath string `json:"old_path"`
|
||||
Status string `json:"status"`
|
||||
Additions int `json:"additions"`
|
||||
Deletions int `json:"deletions"`
|
||||
Binary bool `json:"binary"`
|
||||
}
|
||||
|
||||
func decodeChanges(t *testing.T, body []byte) changesResponse {
|
||||
t.Helper()
|
||||
var decoded changesResponse
|
||||
if err := json.Unmarshal(body, &decoded); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, body)
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesKeepsFoundFalseApartFromAnEmptyFileList pins the
|
||||
// distinction the changed-files view depends on: "no capture was recorded for
|
||||
// this attempt" is not "no files changed".
|
||||
func TestHandleTaskChangesKeepsFoundFalseApartFromAnEmptyFileList(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
insertCapture(t, srv, current.ID, 2, "commit",
|
||||
captureData([]any{}, map[string]any{"files": 0, "additions": 0, "deletions": 0}))
|
||||
|
||||
recorded := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if recorded.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", recorded.Code, recorded.Body)
|
||||
}
|
||||
if raw := recorded.Body.String(); !strings.Contains(raw, `"files":[]`) {
|
||||
t.Errorf("body = %s, want an empty files array rather than null", raw)
|
||||
}
|
||||
body := decodeChanges(t, recorded.Body.Bytes())
|
||||
if !body.Found || body.Attempt != 2 {
|
||||
t.Fatalf("found = %v, attempt = %d; want true, 2", body.Found, body.Attempt)
|
||||
}
|
||||
if len(body.Captures) != 1 {
|
||||
t.Fatalf("captures = %d, want 1 (%s)", len(body.Captures), recorded.Body)
|
||||
}
|
||||
if len(body.Captures[0].Files) != 0 {
|
||||
t.Errorf("files = %+v, want none: a capture with an empty diff is still a capture", body.Captures[0].Files)
|
||||
}
|
||||
if body.Captures[0].Totals.Files != 0 {
|
||||
t.Errorf("totals.files = %d, want 0", body.Captures[0].Totals.Files)
|
||||
}
|
||||
|
||||
unrecorded := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=1"))
|
||||
if unrecorded.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", unrecorded.Code, unrecorded.Body)
|
||||
}
|
||||
if raw := unrecorded.Body.String(); !strings.Contains(raw, `"captures":[]`) {
|
||||
t.Errorf("body = %s, want an empty captures array rather than null", raw)
|
||||
}
|
||||
if got := decodeChanges(t, unrecorded.Body.Bytes()); got.Found || len(got.Captures) != 0 || got.Attempt != 1 {
|
||||
t.Errorf("attempt 1 = found %v with %d captures at attempt %d, want found false, none, attempt 1",
|
||||
got.Found, len(got.Captures), got.Attempt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesResolvesTheCurrentAttemptAndCarriesTheRecordedFields
|
||||
// pins the wire shape field by field, and that an absent attempt parameter
|
||||
// selects the task's current attempt.
|
||||
func TestHandleTaskChangesResolvesTheCurrentAttemptAndCarriesTheRecordedFields(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 12, 3)},
|
||||
map[string]any{"files": 1, "additions": 12, "deletions": 3})
|
||||
data["pr_number"] = 7
|
||||
insertCapture(t, srv, current.ID, 2, "commit-push", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if body.TaskID != current.ID || body.Attempt != 2 || !body.Found {
|
||||
t.Fatalf("envelope = task %d attempt %d found %v; want %d, 2, true",
|
||||
body.TaskID, body.Attempt, body.Found, current.ID)
|
||||
}
|
||||
if len(body.Captures) != 1 {
|
||||
t.Fatalf("captures = %d, want 1 (%s)", len(body.Captures), w.Body)
|
||||
}
|
||||
capture := body.Captures[0]
|
||||
if !capture.CapturedAt.Equal(railBase.Add(2 * time.Minute)) {
|
||||
t.Errorf("captured_at = %v, want the capture event's own time", capture.CapturedAt)
|
||||
}
|
||||
if capture.CapturedAfter != "commit-push" || capture.Stage != "commit-push" {
|
||||
t.Errorf("captured_after = %q, stage = %q; want commit-push, commit-push", capture.CapturedAfter, capture.Stage)
|
||||
}
|
||||
if capture.Owner != "acme" || capture.Repo != "widget" || capture.Base != "main" || capture.Branch != "feat/2-x" {
|
||||
t.Errorf("repository fields = %q/%q base %q branch %q", capture.Owner, capture.Repo, capture.Base, capture.Branch)
|
||||
}
|
||||
if capture.HeadSHA != "head-sha" || capture.BaseSHA != "base-sha" || capture.PRNumber != 7 {
|
||||
t.Errorf("shas = %q/%q pr %d, want head-sha/base-sha/7", capture.HeadSHA, capture.BaseSHA, capture.PRNumber)
|
||||
}
|
||||
if capture.Totals.Files != 1 || capture.Totals.Additions != 12 || capture.Totals.Deletions != 3 {
|
||||
t.Errorf("totals = %+v, want 1/12/3", capture.Totals)
|
||||
}
|
||||
if capture.Truncated {
|
||||
t.Error("truncated = true for a capture that was not truncated")
|
||||
}
|
||||
if len(capture.Files) != 1 {
|
||||
t.Fatalf("files = %+v, want one", capture.Files)
|
||||
}
|
||||
file := capture.Files[0]
|
||||
if file.Path != "internal/x.go" || file.Status != "modified" || file.Additions != 12 || file.Deletions != 3 || file.Binary {
|
||||
t.Errorf("file = %+v, want internal/x.go modified +12 -3, not binary", file)
|
||||
}
|
||||
if file.OldPath != "" {
|
||||
t.Errorf("old_path = %q, want empty for a modify", file.OldPath)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesKeepsTheFullTotalsOfATruncatedCapture pins that totals
|
||||
// are the producer's measurement of the whole change set, not a re-count of the
|
||||
// file entries this read happens to carry.
|
||||
func TestHandleTaskChangesKeepsTheFullTotalsOfATruncatedCapture(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 1, 1)},
|
||||
map[string]any{"files": 250, "additions": 900, "deletions": 10})
|
||||
data["truncated"] = true
|
||||
insertCapture(t, srv, current.ID, 2, "commit", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
captures := decodeChanges(t, w.Body.Bytes()).Captures
|
||||
if len(captures) != 1 {
|
||||
t.Fatalf("captures = %d, want 1 (%s)", len(captures), w.Body)
|
||||
}
|
||||
capture := captures[0]
|
||||
if !capture.Truncated {
|
||||
t.Error("truncated = false for a capture that dropped file entries")
|
||||
}
|
||||
if len(capture.Files) != 1 {
|
||||
t.Fatalf("files = %d, want the single entry the producer capped the list to", len(capture.Files))
|
||||
}
|
||||
if capture.Totals.Files != 250 || capture.Totals.Additions != 900 || capture.Totals.Deletions != 10 {
|
||||
t.Errorf("totals = %+v, want the full 250/900/10 rather than a count of the 1 file carried", capture.Totals)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesRefusesACaptureItCannotNameSchema pins the schema
|
||||
// marker's job: a payload whose shape this build does not know is not a
|
||||
// capture it may render. Rendering it would show a diffstat nobody read, so
|
||||
// the attempt reports that a capture was recorded and none was readable --
|
||||
// the panel's read-failure state -- rather than a capture of zeroes.
|
||||
func TestHandleTaskChangesRefusesACaptureItCannotNameSchema(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(map[string]any)
|
||||
}{
|
||||
{
|
||||
name: "no schema at all",
|
||||
mutate: func(data map[string]any) { delete(data, "schema") },
|
||||
},
|
||||
{
|
||||
name: "a schema this build does not know",
|
||||
mutate: func(data map[string]any) { data["schema"] = "archie/task-changes@2" },
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 12, 3)},
|
||||
map[string]any{"files": 1, "additions": 12, "deletions": 3})
|
||||
tt.mutate(data)
|
||||
insertCapture(t, srv, current.ID, 2, "commit", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if !body.Found {
|
||||
t.Error("found = false although a capture event was recorded for the attempt")
|
||||
}
|
||||
if len(body.Captures) != 0 {
|
||||
t.Errorf("captures = %+v, want none: a payload this build cannot name must not be rendered as a capture",
|
||||
body.Captures)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesRefusesAPayloadWhoseKeySetDrifted pins the other half
|
||||
// of the schema guard: the schema names the shape, the exact key set proves
|
||||
// the shape arrived. A key renamed, dropped or added means the payload is not
|
||||
// the one this reader knows, and reading it leniently is how a lost
|
||||
// truncation marker becomes "not truncated" and a moved cap becomes "every
|
||||
// file, none dropped".
|
||||
func TestHandleTaskChangesRefusesAPayloadWhoseKeySetDrifted(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(map[string]any)
|
||||
}{
|
||||
{
|
||||
name: "the truncation marker renamed",
|
||||
mutate: func(data map[string]any) {
|
||||
delete(data, "truncated")
|
||||
data["truncated_files"] = true
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "the file list dropped",
|
||||
mutate: func(data map[string]any) { delete(data, "files") },
|
||||
},
|
||||
{
|
||||
name: "a key this reader does not know",
|
||||
mutate: func(data map[string]any) { data["schema_version"] = 1 },
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 1, 0)},
|
||||
map[string]any{"files": task.MaxCapturedFiles + 1, "additions": 1, "deletions": 0})
|
||||
tt.mutate(data)
|
||||
insertCapture(t, srv, current.ID, 2, "commit", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if !body.Found {
|
||||
t.Error("found = false although a capture event was recorded for the attempt")
|
||||
}
|
||||
if len(body.Captures) != 0 {
|
||||
t.Errorf("captures = %+v, want none: a payload whose keys drifted must not be read as zero values",
|
||||
body.Captures)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesLinksThePullRequestOfTheFinalCapture is the reader half
|
||||
// of the requirement the commit-time captures cannot meet: their pr_number is
|
||||
// necessarily 0, and the capture OpenPR takes once the number exists is what
|
||||
// gives the panel a pull-request link.
|
||||
func TestHandleTaskChangesLinksThePullRequestOfTheFinalCapture(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.ConfigSource = func(_ context.Context) (ConfigView, bool, error) {
|
||||
return multiIdentityView(), true, nil
|
||||
}
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
beforePR := captureData([]any{modifiedFile("internal/x.go", 1, 0)},
|
||||
map[string]any{"files": 1, "additions": 1, "deletions": 0})
|
||||
beforePR["captured_after"] = "commit-push"
|
||||
insertCapture(t, srv, current.ID, 2, "commit-push", beforePR)
|
||||
|
||||
withPR := captureData([]any{modifiedFile("internal/x.go", 1, 0)},
|
||||
map[string]any{"files": 1, "additions": 1, "deletions": 0})
|
||||
withPR["captured_after"] = "open-pr"
|
||||
withPR["pr_number"] = 7
|
||||
insertCapture(t, srv, current.ID, 2, "open-pr", withPR)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
captures := decodeChanges(t, w.Body.Bytes()).Captures
|
||||
if len(captures) != 2 {
|
||||
t.Fatalf("captures = %d, want both the push and the open-pr capture (%s)", len(captures), w.Body)
|
||||
}
|
||||
if captures[0].PRNumber != 0 || captures[0].PRURL != "" {
|
||||
t.Errorf("the push capture = pr %d url %q, want no PR: it was taken before one existed",
|
||||
captures[0].PRNumber, captures[0].PRURL)
|
||||
}
|
||||
if captures[1].CapturedAfter != "open-pr" || captures[1].PRNumber != 7 {
|
||||
t.Fatalf("the final capture = %q pr %d, want open-pr, 7", captures[1].CapturedAfter, captures[1].PRNumber)
|
||||
}
|
||||
if captures[1].PRURL != "https://gitea.example/acme/widget/pulls/7" {
|
||||
t.Errorf("pr_url = %q, want the pull request the capture names", captures[1].PRURL)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesRefusesACaptureThatLostItsFileCap pins the cap from the
|
||||
// reading side: `files` is bounded at task.MaxCapturedFiles by the producer,
|
||||
// and a payload carrying more than that is one whose cap was lost. Rendering
|
||||
// it would advertise the loss as a complete capture of every file.
|
||||
func TestHandleTaskChangesRefusesACaptureThatLostItsFileCap(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
files := make([]any, 0, task.MaxCapturedFiles+1)
|
||||
for i := range task.MaxCapturedFiles + 1 {
|
||||
files = append(files, modifiedFile(fmt.Sprintf("file-%03d.go", i), 1, 0))
|
||||
}
|
||||
insertCapture(t, srv, current.ID, 2, "commit",
|
||||
captureData(files, map[string]any{"files": len(files), "additions": len(files), "deletions": 0}))
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if !body.Found {
|
||||
t.Error("found = false although a capture event was recorded for the attempt")
|
||||
}
|
||||
if len(body.Captures) != 0 {
|
||||
t.Errorf("captures = %d entries, want none: a payload over the cap is one whose cap was lost",
|
||||
len(body.Captures))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesSkipsCapturesWithNoReadablePayload pins the degrade
|
||||
// rule: a capture whose data is absent or malformed is skipped rather than
|
||||
// failing the read, and the attempt still reports that a capture was recorded.
|
||||
func TestHandleTaskChangesSkipsCapturesWithNoReadablePayload(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindChangesCaptured, TaskID: current.ID, Attempt: 2, Stage: "commit",
|
||||
At: railBase, Data: map[string]any{"files": "not-an-array"},
|
||||
})
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindChangesCaptured, TaskID: current.ID, Attempt: 2, Stage: "commit",
|
||||
At: railBase.Add(time.Second),
|
||||
})
|
||||
insertCapture(t, srv, current.ID, 2, "commit",
|
||||
captureData([]any{modifiedFile("internal/kept.go", 1, 0)},
|
||||
map[string]any{"files": 1, "additions": 1, "deletions": 0}))
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if !body.Found {
|
||||
t.Error("found = false although a capture event was recorded for the attempt")
|
||||
}
|
||||
if len(body.Captures) != 1 {
|
||||
t.Fatalf("captures = %+v, want only the readable one", body.Captures)
|
||||
}
|
||||
if got := body.Captures[0].Files[0].Path; got != "internal/kept.go" {
|
||||
t.Errorf("kept file = %q, want internal/kept.go", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesLinksTheCaptureRepositoryAndPullRequest reuses the task
|
||||
// list's own forge projection: the page needs a repository link and, once a PR
|
||||
// exists, a pull-request link, and it must get them from the same source the
|
||||
// task list uses rather than a second one.
|
||||
func TestHandleTaskChangesLinksTheCaptureRepositoryAndPullRequest(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.ConfigSource = func(_ context.Context) (ConfigView, bool, error) {
|
||||
return multiIdentityView(), true, nil
|
||||
}
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
for _, prNumber := range []int{0, 7} {
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 1, 0)},
|
||||
map[string]any{"files": 1, "additions": 1, "deletions": 0})
|
||||
data["pr_number"] = prNumber
|
||||
insertCapture(t, srv, current.ID, 2, "commit", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("pr %d: status = %d, body %s", prNumber, w.Code, w.Body)
|
||||
}
|
||||
captures := decodeChanges(t, w.Body.Bytes()).Captures
|
||||
capture := captures[len(captures)-1]
|
||||
if capture.RepoURL != "https://gitea.example/acme/widget" {
|
||||
t.Errorf("pr %d: repo_url = %q, want the task's gitea repository", prNumber, capture.RepoURL)
|
||||
}
|
||||
wantPR := ""
|
||||
if prNumber > 0 {
|
||||
wantPR = "https://gitea.example/acme/widget/pulls/7"
|
||||
}
|
||||
if capture.PRURL != wantPR {
|
||||
t.Errorf("pr %d: pr_url = %q, want %q", prNumber, capture.PRURL, wantPR)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// taskDebugView is GET /api/tasks/{id}/debug: the stored task record as it is,
|
||||
// and every event recorded for the task. It is deliberately not a generic
|
||||
// store-dump route -- the task list is capped at 100 rows, so a page that wanted
|
||||
// to show an older task's raw provenance had no row to join against. Nothing
|
||||
// here is projected, filtered or re-spelled: reading it is the point.
|
||||
//
|
||||
// Events are UNFILTERED. A debug view that silently hid the events of other
|
||||
// attempts would be worse than useless; each event carries its own attempt, so
|
||||
// the operator sees everything and can attribute it. Attempt reports only which
|
||||
// attempt the page had selected. No log payload is included: the log tab already
|
||||
// serves it, and embedding it would duplicate a large body for no new
|
||||
// information.
|
||||
type taskDebugView struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Task task.Task `json:"task"`
|
||||
Events []events.Event `json:"events"`
|
||||
}
|
||||
|
||||
// handleTaskDebug serves the task's raw record together with its whole event
|
||||
// list, for whichever attempt the request names.
|
||||
func (s *Server) handleTaskDebug(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
evs, err := s.Store.TaskEvents(r.Context(), t.ID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if evs == nil {
|
||||
evs = []events.Event{}
|
||||
}
|
||||
writeJSON(w, taskDebugView{TaskID: t.ID, Attempt: attempt, Task: *t, Events: evs})
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// TestHandleTaskDebugReturnsTheWholeRecordAndEveryEvent pins R7's read: the
|
||||
// stored task record verbatim, and EVERY event of the task rather than only the
|
||||
// selected attempt's -- each event carries its own attempt, so a filtered list
|
||||
// would hide the very provenance the view exists to show.
|
||||
func TestHandleTaskDebugReturnsTheWholeRecordAndEveryEvent(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindStageStart, TaskID: current.ID, Attempt: 1, Stage: "prepare", At: railBase,
|
||||
})
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindAgentFinish, TaskID: current.ID, Attempt: 0, At: railBase.Add(time.Second),
|
||||
Data: map[string]any{"status": "ok"},
|
||||
})
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindStageStart, TaskID: current.ID, Attempt: 2, Stage: "implement",
|
||||
At: railBase.Add(2 * time.Second),
|
||||
})
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/debug?attempt=1"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
raw := w.Body.String()
|
||||
if strings.Contains(raw, `"entries"`) {
|
||||
t.Errorf("body carries a log payload: %s", raw)
|
||||
}
|
||||
|
||||
var body struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Task workflow.Task `json:"task"`
|
||||
Events []struct {
|
||||
Kind string `json:"kind"`
|
||||
Attempt int `json:"attempt"`
|
||||
} `json:"events"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.TaskID != current.ID || body.Attempt != 1 {
|
||||
t.Errorf("envelope = task %d attempt %d, want task %d attempt 1 (the selected attempt)",
|
||||
body.TaskID, body.Attempt, current.ID)
|
||||
}
|
||||
if body.Task.ID != current.ID || body.Task.Status != workflow.StatusRunning || body.Task.Attempt != 2 {
|
||||
t.Errorf("task record = id %d status %q attempt %d, want the stored record (%d, running, 2)",
|
||||
body.Task.ID, body.Task.Status, body.Task.Attempt, current.ID)
|
||||
}
|
||||
if len(body.Events) != 3 {
|
||||
t.Fatalf("events = %d, want all 3 including the one recorded against a different attempt (%s)",
|
||||
len(body.Events), w.Body)
|
||||
}
|
||||
wantAttempts := []int{1, 0, 2}
|
||||
for i, want := range wantAttempts {
|
||||
if body.Events[i].Attempt != want {
|
||||
t.Errorf("event %d attempt = %d, want %d (order and attribution preserved)", i, body.Events[i].Attempt, want)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(raw, `"attempt":0`) {
|
||||
t.Errorf("body = %s, want attempt carried on every event so an unattributed one stays distinguishable", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskDebugResolvesTheCurrentAttemptWithoutAParameter pins that the
|
||||
// envelope reports the attempt the page selected, defaulting to the task's
|
||||
// current attempt exactly as the log read does.
|
||||
func TestHandleTaskDebugResolvesTheCurrentAttemptWithoutAParameter(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/debug"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Attempt int `json:"attempt"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.Attempt != current.Attempt {
|
||||
t.Errorf("attempt = %d, want the task's current attempt %d", body.Attempt, current.Attempt)
|
||||
}
|
||||
}
|
||||
@@ -48,8 +48,12 @@ func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) {
|
||||
page, err := reader.TaskLog(r.Context(), id, attempt, logging.Query{
|
||||
Levels: splitCSV(q.Get("level")),
|
||||
Component: strings.TrimSpace(q.Get("component")),
|
||||
Contains: strings.TrimSpace(q.Get("q")),
|
||||
Limit: limit,
|
||||
// Stage is a narrowing filter, not a scoping one: only entries a stage
|
||||
// tagged carry the field, so the UI states that a stage filter matches
|
||||
// the lines that record a stage and nothing else.
|
||||
Stage: strings.TrimSpace(q.Get("stage")),
|
||||
Contains: strings.TrimSpace(q.Get("q")),
|
||||
Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
// A reader that exists but cannot read here is still a statement about
|
||||
@@ -134,32 +138,16 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
// the attempt to read: the "attempt" query parameter when the request names
|
||||
// one, otherwise the task's current Attempt. It answers the request itself and
|
||||
// reports false when either step fails.
|
||||
//
|
||||
// The resolution itself is taskAttemptTarget's, shared with the attempt rail,
|
||||
// the changed-files read and the debug view, so every per-attempt read of one
|
||||
// task selects the same attempt for the same request.
|
||||
func (s *Server) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return 0, 0, false
|
||||
}
|
||||
task, err := s.Store.TaskByID(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return 0, 0, false
|
||||
}
|
||||
if task == nil {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
attempt = task.Attempt
|
||||
if raw := strings.TrimSpace(r.URL.Query().Get("attempt")); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
http.Error(w, "bad attempt", http.StatusBadRequest)
|
||||
return 0, 0, false
|
||||
}
|
||||
attempt = parsed
|
||||
}
|
||||
return id, attempt, true
|
||||
return t.ID, attempt, true
|
||||
}
|
||||
|
||||
// taskLogLimit bounds a page the way handleLogs bounds the daemon-wide read:
|
||||
|
||||
@@ -96,6 +96,103 @@ func TestHandleTaskLogsHonoursExplicitAttempt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsFiltersByStageAndKeepsTheAttempt pins R5's read half: the
|
||||
// stage parameter reaches the reader's query, narrows the attempt's entries to
|
||||
// the lines that record that stage, and leaves both the attempt it resolved and
|
||||
// the file's existence (found) untouched -- a filter that matches nothing is
|
||||
// "nothing matching this filter", never "this deployment cannot read logs".
|
||||
func TestHandleTaskLogsFiltersByStageAndKeepsTheAttempt(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
baseDir := t.TempDir()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Written to attempt 1's file: an earlier attempt the task's current
|
||||
// Attempt field does not point at, so the attempt must be requested.
|
||||
sink, err := logging.NewTaskSink(baseDir, task.ID, 1, logging.TaskSinkOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sink.Logger().Warn("committing the worktree", "stage", "commit")
|
||||
sink.Logger().Warn("agent produced a diff", "component", "agent")
|
||||
if err := sink.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
query map[string]string
|
||||
wantCount int
|
||||
wantFound bool
|
||||
}{
|
||||
{
|
||||
name: "no stage filter",
|
||||
query: map[string]string{"attempt": "1"},
|
||||
wantCount: 2,
|
||||
wantFound: true,
|
||||
},
|
||||
{
|
||||
name: "the stage this attempt recorded",
|
||||
query: map[string]string{"attempt": "1", "stage": "commit"},
|
||||
wantCount: 1,
|
||||
wantFound: true,
|
||||
},
|
||||
{
|
||||
name: "a stage no entry records",
|
||||
query: map[string]string{"attempt": "1", "stage": "implement"},
|
||||
wantCount: 0,
|
||||
wantFound: true,
|
||||
},
|
||||
{
|
||||
name: "a stage filter on an attempt with no log at all",
|
||||
query: map[string]string{"attempt": "2", "stage": "commit"},
|
||||
wantCount: 0,
|
||||
wantFound: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
w := getTaskLogs(t, srv, task.ID, tt.query)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Entries []logging.Entry `json:"entries"`
|
||||
Attempt int `json:"attempt"`
|
||||
Found bool `json:"found"`
|
||||
Disabled bool `json:"disabled"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
wantAttempt := 1
|
||||
if tt.query["attempt"] == "2" {
|
||||
wantAttempt = 2
|
||||
}
|
||||
if body.Attempt != wantAttempt {
|
||||
t.Errorf("attempt = %d, want the requested attempt %d", body.Attempt, wantAttempt)
|
||||
}
|
||||
if len(body.Entries) != tt.wantCount {
|
||||
t.Errorf("entries = %d, want %d (%s)", len(body.Entries), tt.wantCount, w.Body)
|
||||
}
|
||||
if body.Found != tt.wantFound {
|
||||
t.Errorf("found = %v, want %v: a filter that matches nothing is not a missing log", body.Found, tt.wantFound)
|
||||
}
|
||||
if body.Disabled {
|
||||
t.Error("disabled = true for a process that has a task-log reader")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskLogsBadID(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/not-a-number/logs", nil)
|
||||
|
||||
@@ -243,6 +243,9 @@ func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/task-meta", s.handleTaskMeta)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction)
|
||||
mux.HandleFunc("GET /api/tasks/{id}", s.handleTask)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/attempts", s.handleTaskAttempts)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/changes", s.handleTaskChanges)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/debug", s.handleTaskDebug)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs/download", s.handleTaskLogDownload)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user