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
@@ -981,6 +981,14 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
|
||||
d.Log.Warn("PR state check failed", "pr", t.PRNumber, "err", err)
|
||||
continue
|
||||
}
|
||||
// OpenPRs returns a deliberately narrow projection of a pr_open task
|
||||
// (id/owner/repo/issue/pr/status/source/identity) that does not carry
|
||||
// the attempt, so the outcome event below reads it from the task's own
|
||||
// row. A failed lookup costs attribution and never the merge handling:
|
||||
// the status transition and the worktree cleanup still run. OpenPRs
|
||||
// carries attempt, so these events are attributed without a second
|
||||
// read per open PR on every reconcile tick.
|
||||
attempt := t.Attempt
|
||||
switch state {
|
||||
case "merged":
|
||||
_ = d.Store.Transition(ctx, t.ID, workflow.StatusPROpen, workflow.StatusMerged, "")
|
||||
@@ -997,7 +1005,7 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
|
||||
))
|
||||
d.Log.Info("PR merged", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindPRMerged, TaskID: t.ID,
|
||||
Kind: events.KindPRMerged, TaskID: t.ID, Attempt: attempt,
|
||||
Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber,
|
||||
Data: map[string]any{"pr": t.PRNumber},
|
||||
})
|
||||
@@ -1006,7 +1014,7 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
|
||||
_ = trees.Cleanup(t.Owner, t.Repo, t.IssueNumber)
|
||||
d.Log.Info("PR rejected", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindPRRejected, TaskID: t.ID,
|
||||
Kind: events.KindPRRejected, TaskID: t.ID, Attempt: attempt,
|
||||
Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber,
|
||||
Data: map[string]any{"pr": t.PRNumber},
|
||||
})
|
||||
@@ -1040,7 +1048,7 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
|
||||
}
|
||||
d.recordPark(ctx, task.ID, reason)
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindParked, TaskID: task.ID,
|
||||
Kind: events.KindParked, TaskID: task.ID, Attempt: task.Attempt,
|
||||
Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason,
|
||||
})
|
||||
return
|
||||
@@ -1054,7 +1062,7 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
|
||||
}
|
||||
d.recordPark(ctx, task.ID, reason)
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindParked, TaskID: task.ID,
|
||||
Kind: events.KindParked, TaskID: task.ID, Attempt: task.Attempt,
|
||||
Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason,
|
||||
})
|
||||
return
|
||||
@@ -1318,12 +1326,15 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
|
||||
return
|
||||
}
|
||||
defer revoke()
|
||||
cfg := d.configFor(task)
|
||||
taskCfg := cfg.ForTask()
|
||||
d.captureAttemptConfig(ctx, task, taskCfg)
|
||||
req := taskrun.Request{
|
||||
Task: task,
|
||||
Repo: repo,
|
||||
Cfg: d.configFor(task).ForTask(),
|
||||
Providers: agentexec.ProvidersFromConfig(d.configFor(task).Providers),
|
||||
MCPServers: d.configFor(task).Tools.MCPServers,
|
||||
Cfg: taskCfg,
|
||||
Providers: agentexec.ProvidersFromConfig(cfg.Providers),
|
||||
MCPServers: cfg.Tools.MCPServers,
|
||||
WorktreeGrant: grant,
|
||||
KindWorkflows: d.KindWorkflows,
|
||||
LabelWorkflows: d.LabelWorkflows,
|
||||
@@ -1486,6 +1497,52 @@ func (d *Daemon) configFor(task *workflow.Task) config.Config {
|
||||
return d.Cfg.Get()
|
||||
}
|
||||
|
||||
// captureAttemptConfig persists the effective task configuration this attempt
|
||||
// runs under, as a durable event on the attempt's own key.
|
||||
//
|
||||
// It is written where the configuration is materialised for the dispatch, so
|
||||
// the document is exactly what the run received. The published configuration
|
||||
// snapshot cannot answer this: it is the CURRENT configuration, replaced on
|
||||
// every publish, so a run that finished last week has no record anywhere else.
|
||||
//
|
||||
// Fail-open by construction: a configuration that could not be recorded is
|
||||
// worth a log line and nothing more. Parking a task over a reporting failure
|
||||
// would trade the run for the receipt.
|
||||
func (d *Daemon) captureAttemptConfig(ctx context.Context, task *workflow.Task, cfg config.TaskConfig) {
|
||||
if d.Store == nil {
|
||||
return
|
||||
}
|
||||
document, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
d.Log.Warn("attempt configuration not captured", "task", task.ID, "attempt", task.Attempt, "err", err)
|
||||
return
|
||||
}
|
||||
event := events.Event{
|
||||
At: time.Now().UTC(),
|
||||
Kind: events.KindConfigCaptured,
|
||||
TaskID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo,
|
||||
Issue: task.IssueNumber,
|
||||
Workflow: task.Workflow,
|
||||
Attempt: task.Attempt,
|
||||
Data: map[string]any{
|
||||
"schema": events.ConfigCapturedSchema,
|
||||
// Raw so the document is embedded once, as it was encoded, rather
|
||||
// than as a string a reader would have to decode again.
|
||||
"document": json.RawMessage(document),
|
||||
},
|
||||
}
|
||||
id, err := d.Store.InsertEvent(ctx, event)
|
||||
if err != nil {
|
||||
d.Log.Warn("attempt configuration not captured", "task", task.ID, "attempt", task.Attempt, "err", err)
|
||||
return
|
||||
}
|
||||
// The assigned ID tells the event sink to broadcast without inserting a
|
||||
// duplicate row.
|
||||
event.ID = id
|
||||
d.emit(event)
|
||||
}
|
||||
|
||||
func configForIdentity(root config.Config, identity config.IdentityConfig) config.Config {
|
||||
root.BotUser = identity.BotUser
|
||||
root.BotEmail = identity.BotEmail
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -1610,3 +1611,333 @@ func TestReconcilePRsSkipsChatTasks(t *testing.T) {
|
||||
t.Errorf("CloseIssue called for a chat task: issue number is synthetic")
|
||||
}
|
||||
}
|
||||
|
||||
// daemonCanarySecrets are recognisable secret references and values that must
|
||||
// never appear in a captured configuration document. The event this capture
|
||||
// writes is readable by anyone who can read the task's timeline, so the
|
||||
// document is a disclosure boundary, not just a convenience.
|
||||
const (
|
||||
canaryForgeToken = "ghp_DAEMONCANARYFORGETOKEN01"
|
||||
canaryWebhookSecret = "CANARY-WEBHOOK-SECRET-02"
|
||||
canaryIdentityToken = "ghp_DAEMONCANARYIDENTITY03"
|
||||
canaryProviderKey = "sk-DAEMONCANARYPROVIDERKEY04"
|
||||
canaryBWSKeyName = "DAEMON-CANARY-BWS-KEY-NAME-05"
|
||||
canaryTelegramToken = "tg-DAEMONCANARYTELEGRAMTOKEN06"
|
||||
canaryNATSTokenEnv = "DAEMON_CANARY_NATS_TOKEN_ENV_07"
|
||||
canaryStateStoreToken = "DAEMON-CANARY-STATE-STORE-TOKEN-08"
|
||||
)
|
||||
|
||||
// configWithCanarySecrets is a fully populated configuration carrying
|
||||
// recognisable secrets in every place a deployment keeps one: the root forge,
|
||||
// an identity's forge, the model providers, the chat channel, the state store
|
||||
// and the NATS credential. A capture that serialized the wrong object -- the
|
||||
// whole config, or a projection that forgot to drop a secret -- would carry
|
||||
// one of them.
|
||||
func configWithCanarySecrets() config.Config {
|
||||
return config.Config{
|
||||
WorkDir: "/work/archie",
|
||||
DBPath: "/work/archie/archie.db",
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie@example.com",
|
||||
Label: "archie",
|
||||
Forge: config.Forge{
|
||||
Type: "gitea", Host: "gitea.example.com", TokenEnv: "GITEA_TOKEN",
|
||||
Token: secret.SecretRef{Engine: "bws", Key: canaryForgeToken},
|
||||
WebhookSecret: secret.SecretRef{Engine: "bws", Key: canaryWebhookSecret},
|
||||
Intake: "webhook",
|
||||
},
|
||||
Models: map[string]string{"builder": "openai/gpt-4", "planner": "openai/gpt-4"},
|
||||
Providers: map[string]config.Provider{
|
||||
"openai": {
|
||||
Class: "openai", APIKeyEnv: "OPENAI_API_KEY", BaseURL: "https://api.openai.com/v1",
|
||||
APIKey: secret.SecretRef{Engine: "bws", Key: canaryBWSKeyName},
|
||||
},
|
||||
"custom": {
|
||||
Class: "custom", APIKey: secret.SecretRef{Engine: "literal", Key: canaryProviderKey},
|
||||
},
|
||||
},
|
||||
Budgets: config.Budgets{MaxSteps: 40, GateMaxFailures: 2},
|
||||
DiffCapLines: 800,
|
||||
Dispatch: config.Dispatch{
|
||||
Trigger: "either", AckReaction: "eyes",
|
||||
Labels: map[string]string{"queued": "archie:queued"},
|
||||
},
|
||||
Notify: config.Notify{Webhook: "https://hooks.example.com/notify"},
|
||||
Tools: config.ToolsConfig{Policy: config.ToolPolicy{MaxResultChars: 12000, SpillDir: "/tmp/spill"}},
|
||||
NATS: config.NATSConfig{Mode: "external", URL: "nats://127.0.0.1:4222", TokenEnv: canaryNATSTokenEnv},
|
||||
Chat: config.ChatConfig{Operator: "sam", Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN", Token: secret.SecretRef{Engine: "bws", Key: canaryTelegramToken}}},
|
||||
Services: config.Services{State: config.ServiceConnection{Target: "127.0.0.1:50051", TargetToken: canaryStateStoreToken}},
|
||||
ModelLimits: map[string]config.ModelLimits{
|
||||
"openai/gpt-4": {ContextWindow: 128000, MaxOutputTokens: 4096},
|
||||
},
|
||||
Identities: []config.IdentityConfig{
|
||||
{
|
||||
Name: "gitea-bot", BotUser: "gitea-bot", BotEmail: "gitea-bot@example.com",
|
||||
Forge: config.Forge{Type: "gitea", Host: "gitea.example.com", Token: secret.SecretRef{Engine: "bws", Key: canaryIdentityToken}},
|
||||
Models: map[string]string{"builder": "openai/gpt-4"},
|
||||
Budgets: config.Budgets{MaxSteps: 40},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatchCapturesTheAttemptsEffectiveConfig is R4's producer half: the
|
||||
// configuration an attempt ran under is retrievable for that attempt.
|
||||
//
|
||||
// It asserts three separate claims rather than one: the event is durable and
|
||||
// attributed to the attempt, the document is the dispatch's own TaskConfig,
|
||||
// and no secret value anywhere in the configuration reaches it.
|
||||
func TestDispatchCapturesTheAttemptsEffectiveConfig(t *testing.T) {
|
||||
d, s, busClient := daemonWithNATS(t)
|
||||
d.Cfg.Set(configWithCanarySecrets())
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 5, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim: (%v, %v)", task, err)
|
||||
}
|
||||
if task.Attempt == 0 {
|
||||
t.Fatal("claimed task has attempt 0; the event below could not be attributed to a run")
|
||||
}
|
||||
|
||||
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
data, _ := json.Marshal(taskrun.Response{Status: workflow.StatusPROpen})
|
||||
_ = msg.Respond(data)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("subscribe: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
d.runViaAgent(ctx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
|
||||
|
||||
timeline, err := s.TaskEvents(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var captures []events.Event
|
||||
for _, e := range timeline {
|
||||
if e.Kind == events.KindConfigCaptured {
|
||||
captures = append(captures, e)
|
||||
}
|
||||
}
|
||||
if len(captures) != 1 {
|
||||
t.Fatalf("config_captured events = %d, want exactly 1 for the attempt", len(captures))
|
||||
}
|
||||
captured := captures[0]
|
||||
if captured.Attempt != task.Attempt {
|
||||
t.Errorf("capture attempt = %d, want the dispatched attempt %d", captured.Attempt, task.Attempt)
|
||||
}
|
||||
|
||||
encoded, err := json.Marshal(captured)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
document := string(encoded)
|
||||
for _, leak := range []string{
|
||||
canaryForgeToken, canaryWebhookSecret, canaryIdentityToken, canaryProviderKey,
|
||||
canaryBWSKeyName, canaryTelegramToken, canaryNATSTokenEnv, canaryStateStoreToken,
|
||||
} {
|
||||
if strings.Contains(document, leak) {
|
||||
t.Errorf("captured configuration document leaked %q:\n%s", leak, document)
|
||||
}
|
||||
}
|
||||
|
||||
var data struct {
|
||||
Schema string `json:"schema"`
|
||||
Document json.RawMessage `json:"document"`
|
||||
}
|
||||
if err := json.Unmarshal(encoded, &data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The event wrapper carries kind/stage/attempt; the document itself is
|
||||
// what the Config tab renders.
|
||||
var wrapper struct {
|
||||
Data struct {
|
||||
Schema string `json:"schema"`
|
||||
Document json.RawMessage `json:"document"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(encoded, &wrapper); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if wrapper.Data.Schema != events.ConfigCapturedSchema {
|
||||
t.Errorf("schema = %q, want %q", wrapper.Data.Schema, events.ConfigCapturedSchema)
|
||||
}
|
||||
var doc map[string]any
|
||||
if err := json.Unmarshal(wrapper.Data.Document, &doc); err != nil {
|
||||
t.Fatalf("document is not a JSON object: %v", err)
|
||||
}
|
||||
|
||||
// The document is exactly TaskConfig's field set, not the larger dashboard
|
||||
// projection: a reader must be able to trust that it carries no providers,
|
||||
// repositories, identities or lock state.
|
||||
wantKeys := []string{
|
||||
"bot_email", "bot_user", "budgets", "diff_cap_lines", "dispatch",
|
||||
"forge", "model_limits", "models", "notify", "tool_policy",
|
||||
}
|
||||
gotKeys := make([]string, 0, len(doc))
|
||||
for key := range doc {
|
||||
gotKeys = append(gotKeys, key)
|
||||
}
|
||||
sort.Strings(gotKeys)
|
||||
if !slices.Equal(gotKeys, wantKeys) {
|
||||
t.Errorf("document keys = %v, want exactly %v", gotKeys, wantKeys)
|
||||
}
|
||||
if doc["forge"] == nil || !strings.Contains(document, "gitea.example.com") {
|
||||
t.Error("document is missing the non-secret forge host the Config tab renders")
|
||||
}
|
||||
|
||||
// The size decides whether a per-attempt document belongs in an event at
|
||||
// all; recorded so the number is reviewable, not assumed.
|
||||
t.Logf("serialized config document: %d bytes for a fully populated deployment", len(wrapper.Data.Document))
|
||||
if len(wrapper.Data.Document) == 0 {
|
||||
t.Error("document is empty; the Config tab would render nothing")
|
||||
}
|
||||
|
||||
// Models and ModelLimits are the only two fields whose size is set by the
|
||||
// deployment rather than by the struct, so the growth factor gets measured
|
||||
// too instead of assumed.
|
||||
scaled := configWithCanarySecrets()
|
||||
scaled.Models = map[string]string{}
|
||||
scaled.ModelLimits = map[string]config.ModelLimits{}
|
||||
for i := range 20 {
|
||||
ref := fmt.Sprintf("openai/model-%d", i)
|
||||
scaled.Models[fmt.Sprintf("role-%d", i)] = ref
|
||||
scaled.ModelLimits[ref] = config.ModelLimits{ContextWindow: 128000, MaxOutputTokens: 4096}
|
||||
}
|
||||
scaledDoc, err := json.Marshal(scaled.ForTask())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("serialized config document with 20 named models: %d bytes", len(scaledDoc))
|
||||
}
|
||||
|
||||
// failingEventStore is the daemon's store surface with an event insert that
|
||||
// always fails, so the fail-open policy of the capture can be observed without
|
||||
// breaking everything else the dispatch needs.
|
||||
type failingEventStore struct {
|
||||
*store.Store
|
||||
}
|
||||
|
||||
func (f failingEventStore) InsertEvent(context.Context, events.Event) (int64, error) {
|
||||
return 0, fmt.Errorf("events table unavailable")
|
||||
}
|
||||
|
||||
// TestCaptureAttemptConfigFailureDoesNotStopTheDispatch: a provenance record
|
||||
// that could not be written must not cost the run. The taskrun request has to
|
||||
// go out anyway, and nothing may park.
|
||||
func TestCaptureAttemptConfigFailureDoesNotStopTheDispatch(t *testing.T) {
|
||||
d, s, busClient := daemonWithNATS(t)
|
||||
d.Store = failingEventStore{Store: s}
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 6, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
dispatched := make(chan struct{}, 1)
|
||||
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
dispatched <- struct{}{}
|
||||
data, _ := json.Marshal(taskrun.Response{Status: workflow.StatusPROpen})
|
||||
_ = msg.Respond(data)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("subscribe: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
d.runViaAgent(ctx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
|
||||
|
||||
select {
|
||||
case <-dispatched:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("the taskrun request was never published; a failed config capture stopped the dispatch")
|
||||
}
|
||||
|
||||
got, err := s.TaskByIssue(ctx, "acme", "widget", 6)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByIssue: (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status == workflow.StatusParked {
|
||||
t.Errorf("task parked with reason %q; a failed config capture must not park a run", got.ParkReason)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskAgnosticDaemonEventsCarryNoAttempt pins the other half of the
|
||||
// attribution rule: an event produced before any task row exists has no
|
||||
// attempt to name, and inventing one -- the deployment's "current" attempt, a
|
||||
// zero-that-means-first -- would be a fabricated claim. It stays 0, which the
|
||||
// reader reports as unattributed.
|
||||
func TestTaskAgnosticDaemonEventsCarryNoAttempt(t *testing.T) {
|
||||
d := &Daemon{Bus: events.NewBus(), Log: slog.New(slog.DiscardHandler)}
|
||||
sub := d.Bus.Subscribe(4)
|
||||
t.Cleanup(sub.Close)
|
||||
|
||||
d.acknowledge(context.Background(), &recordingForge{}, config.Config{},
|
||||
config.Repo{Owner: "acme", Name: "widget"}, forge.Issue{Number: 3, Title: "a task"})
|
||||
|
||||
select {
|
||||
case e := <-sub.C:
|
||||
if e.Kind != events.KindTaskQueued {
|
||||
t.Fatalf("kind = %q, want %q", e.Kind, events.KindTaskQueued)
|
||||
}
|
||||
if e.Attempt != 0 {
|
||||
t.Errorf("queued event attempt = %d, want 0 (no task exists yet to attribute it to)", e.Attempt)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("no queued event was published")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcilePRsAttributesTheOutcomeToTheTasksAttempt: a PR is merged or
|
||||
// rejected against the attempt whose task recorded that PR number, so the
|
||||
// timeline can attribute the outcome to the run that produced it instead of
|
||||
// leaving it unattributed.
|
||||
func TestReconcilePRsAttributesTheOutcomeToTheTasksAttempt(t *testing.T) {
|
||||
d, s, fg := testDaemon(t, 3, 0)
|
||||
ctx := context.Background()
|
||||
d.Bus = events.NewBus()
|
||||
sub := d.Bus.Subscribe(8)
|
||||
t.Cleanup(sub.Close)
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 42, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
if task.Attempt == 0 {
|
||||
t.Fatal("claimed task has attempt 0; this test could not tell a stamp from a coincidence")
|
||||
}
|
||||
task.PRNumber = 7
|
||||
if err := s.Update(ctx, task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusPROpen, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fg.prStates = map[int]string{7: "merged"}
|
||||
|
||||
d.reconcilePRs(ctx)
|
||||
|
||||
select {
|
||||
case e := <-sub.C:
|
||||
if e.Kind != events.KindPRMerged {
|
||||
t.Fatalf("kind = %q, want %q", e.Kind, events.KindPRMerged)
|
||||
}
|
||||
if e.Attempt != task.Attempt {
|
||||
t.Errorf("pr_merged attempt = %d, want the task's attempt %d", e.Attempt, task.Attempt)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("reconcilePRs published no merge event")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user