oficina / equipo Public

Mac slice F task 4: primary base, packs, publication diffs, outcomes

The primary's side of the base exchange for Engineering on a Mac worker:

- prepare_base is recorded durably and answered once per attempt with
  the default branch's tip (fetch, defaultTip); asked again it re-reports
  the same SHA. Unborn, not a hub repository, a failed fetch or a rebase
  round whose commits are missing: base_unavailable.
- packCommits packs exactly TransferHeader.Commits() (rev-list --objects
  --no-walk), refusing invalid headers before git runs and commits the
  clone lacks before the pack is built.
- publishWorker, only after a successful push at protocol 37, measures
  the worker's candidate (change files, diffs with the primary's known
  secrets left out) and queues the diffs bound to the publication with
  the published report in one transaction; it echoes the outcome phase.
  Failing to measure is a diagnostic, never a push failure.
- Instance: diffs naming a publication are accepted only from the
  person's primary for that pending or published publication of the
  worker's attempt; a worker's own diffs are refused. The worker's done
  never sets or clears files or diffs. Its committed report records the
  outcome, publish carries it, and published (or a later done) gives
  step_timeout or shell_unavailable; Pushed comes only from published.
- The runner's unfinishedReport never sets Pushed on a worker.
- A declared oversize Engineering pack ends workspace_too_large with
  Needs you (new StepReasons entry, pending copy).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 5fb353cd7e86b716f6b3a7d9c2f95158564f881e parent 8bcec34
18 files changed, +1,352 −82
  • .rastrillo/budgets.txt +5 −5
  • docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json +5 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +1 −0
  • internal/equipo/chat/change_diffs.go +44 −10
  • internal/equipo/chat/change_diffs_test.go +5 −5
  • internal/equipo/chat/runners.go +9 −0
  • internal/equipo/chat/tasks.go +18 −5
  • internal/equipo/chat/transfers.go +83 −6
  • internal/equipo/copy.go +1 −0
  • internal/runner/thin/change_diffs.go +60 −18
  • internal/runner/thin/engineer_time_test.go +1 −1
  • internal/runner/thin/link.go +11 −2
  • internal/runner/thin/relay.go +141 −23
  • internal/runner/thin/relay_engineering_test.go +508 −0
  • internal/runner/thin/relay_test.go +13 −3
  • internal/runner/thin/step.go +11 −2
  • internal/thintest/mac_publication_contract_test.go +432 −0
  • internal/wire/tasks.go +4 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 51d1f67e..92b23800 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 23988 - Preview grants, retry/timeline, no-access merges, kept work, check-db copy, notification actions, places page and its superseded card, GitHub owner routes, Mac waits; measured 23988.
-size internal/wire 8590 - Protocol 31 facts, 32 unfinished work, task evidence, CI units, notification inputs, 33 Assistant files, 34 places, 35 diffs, Mac waits, 37 Mac Engineering; measured 8590.
+size internal/equipo 23989 - Preview grants, retry/timeline, no-access merges, kept work, check-db copy, notification actions, places page and its superseded card, GitHub owner routes, Mac waits; measured 23989.
+size internal/wire 8592 - Protocol 31 facts, 32 unfinished work, task evidence, CI units, notification inputs, 33 Assistant files, 34 places, 35 diffs, Mac waits, 37 Mac Engineering; measured 8592.
size internal/equipotest - 12683 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures and Rastrillo asset contract; measured 0/12683 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 30399 25546 Protocol 31 facts, 35 diffs, merge credential, publication guards, kept work, CI units, places publish, token scans, Mac slice F pin and paths; measured 30399/25546.
+size internal/runner/thin 30577 26064 Protocol 31 facts, 35 diffs, merge credential, publication guards, kept work, CI units, places publish, token scans, Mac pin, paths, bases; measured 30577/26064.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 38671 12096 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places, waiting cards, Mac waits, Mac Engineering; measured 38671/12096.
+size internal/equipo/chat 38804 12096 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places, waiting cards, Mac waits, Mac Engineering; measured 38804/12096.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 11977 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files end to end; the restart wait; the live site waits for a place; a card answer settles at the bottom; measured 11977 test lines.
-size internal/thintest - 38383 Protocol 31 contracts, 35 diffs, stuck tasks, no-access merges, held retries, unfinished work, free rounds, previews, Assistant files, places, Mac waits, Mac Engineering; measured 38383.
+size internal/thintest - 38815 Protocol 31 contracts, 35 diffs, stuck tasks, no-access merges, held retries, unfinished work, free rounds, previews, Assistant files, places, Mac waits, Mac Engineering; measured 38815.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
diff --git a/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json b/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json
index 7e591c32..d1065327 100644
--- a/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json
+++ b/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json
@@ -68,5 +68,10 @@
"key": "chat.merge.not.mac_made",
"where": "Merge card, why Equipo did not merge on its own: the candidate was made on a Mac runner",
"draft": "it was made on a Mac runner, so it merges only when you choose"
+ },
+ {
+ "key": "work.reason.workspace_too_large",
+ "where": "Step stop reason: a Mac Engineering attempt's commits were too large to relay to the Mac (Needs you: Try again)",
+ "draft": "the project is too large to send to the Mac"
}
]
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index be492776..35707585 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -7019,6 +7019,7 @@ records remain unchanged.
| `work.decide.mac_wait_ask` | It starts by itself once %s is ready. You can also cancel it. | Copy specialist | COPY REVIEW PENDING |
| `work.reason.base_unavailable` | the main runner couldn’t get the version of the project to start from | Copy specialist | COPY REVIEW PENDING |
| `chat.merge.not.mac_made` | it was made on a Mac runner, so it merges only when you choose | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.workspace_too_large` | the project is too large to send to the Mac | Copy specialist | COPY REVIEW PENDING |
## Task 21
diff --git a/internal/equipo/chat/change_diffs.go b/internal/equipo/chat/change_diffs.go
index b45337f9..a45657a3 100644
--- a/internal/equipo/chat/change_diffs.go
+++ b/internal/equipo/chat/change_diffs.go
@@ -56,21 +56,31 @@ func (t *txn) changeDiff(l Lease, v *wire.ChangeDiffUpload) error {
}
return err
}
- if step.Specialist != wire.SpecialistEngineering || step.Person != l.Runner.Person || step.RunnerID != l.Runner.RunnerID || step.Attempt != v.Attempt || step.State != wire.StepRunning || step.Retired || step.BaseSHA != v.Base || step.CandidateSHA != v.Candidate || !validSHA(v.Candidate) {
+ if step.Specialist != wire.SpecialistEngineering || step.Person != l.Runner.Person || step.Attempt != v.Attempt || step.Retired || step.BaseSHA != v.Base || step.CandidateSHA != v.Candidate || !validSHA(v.Candidate) {
return refuse()
}
- k, err := t.loadTask(step.TaskID)
- if err != nil {
- return err
- }
- if wire.FinalStage(k.Stage) || k.CancelRequested || k.MoveProject != "" {
+ if v.Publication == "" {
+ // The primary's own candidate, from the runner it runs on, while it
+ // runs. A worker's diffs are never kept: the primary measures a
+ // worker's candidate when it publishes it.
+ role, err := t.s.authority.RunnerRole(t.db, l.Runner.RunnerID)
+ if err != nil {
+ return err
+ }
+ if role != wire.RolePrimary || step.RunnerID != l.Runner.RunnerID || step.State != wire.StepRunning {
+ return refuse()
+ }
+ } else if ok, err := t.publicationUploader(l, step, v.Publication); err != nil || !ok {
+ if err != nil {
+ return err
+ }
return refuse()
}
- role, err := t.s.authority.RunnerRole(t.db, l.Runner.RunnerID)
+ k, err := t.loadTask(step.TaskID)
if err != nil {
return err
}
- if role != wire.RolePrimary && role != wire.RoleWorker {
+ if wire.FinalStage(k.Stage) || k.CancelRequested || k.MoveProject != "" {
return refuse()
}
data, err := base64.StdEncoding.DecodeString(v.Data)
@@ -120,9 +130,33 @@ func (t *txn) changeDiff(l Lease, v *wire.ChangeDiffUpload) error {
return t.db.Create(&record).Error
}
+// publicationUploader: l may upload diffs bound to publication for step,
+// a worker's Engineering attempt (protocol 37). Only the person's primary
+// now, for the step's own publication while it is pending or published,
+// whether or not the worker's final report has come; never another
+// runner, an earlier publication or a failed one.
+func (t *txn) publicationUploader(l Lease, step stepRecord, publication string) (bool, error) {
+ if l.Protocol < wire.ProtocolMacEngineering {
+ return false, nil
+ }
+ primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person)
+ if err != nil {
+ return false, err
+ }
+ if primary == "" || primary != l.Runner.RunnerID || step.RunnerID == primary {
+ return false, nil
+ }
+ if step.PublicationID != publication || step.Publication != wire.PublicationPending && step.Publication != wire.PublicationPublished {
+ return false, nil
+ }
+ return step.State == wire.StepRunning || step.State == wire.StepDone, nil
+}
+
// A collection becomes readable only with its matching accepted final report.
// Missing, conflicting and incomplete collections never affect Engineering.
-func (t *txn) acceptChangeDiffs(l Lease, step stepRecord, collection string) error {
+// uploader is the runner whose uploads count: the step's own runner for the
+// primary's candidate, the publication's primary for a worker's.
+func (t *txn) acceptChangeDiffs(l Lease, step stepRecord, collection, uploader string) error {
if l.Protocol < wire.ProtocolChangeDiffs || step.Specialist != wire.SpecialistEngineering || !wire.ValidSHA256(collection) {
return nil
}
@@ -143,7 +177,7 @@ func (t *txn) acceptChangeDiffs(l Lease, step stepRecord, collection string) err
}
files := make([]wire.FileDiff, 0, len(rows))
for i, r := range rows {
- if r.Total != len(rows) || r.Idx != i || r.TaskID != step.TaskID || r.RunnerID != step.RunnerID || r.Base != step.BaseSHA || r.Candidate != step.CandidateSHA || !paths[r.Path] {
+ if r.Total != len(rows) || r.Idx != i || r.TaskID != step.TaskID || r.RunnerID != uploader || r.Base != step.BaseSHA || r.Candidate != step.CandidateSHA || !paths[r.Path] {
return nil
}
delete(paths, r.Path)
diff --git a/internal/equipo/chat/change_diffs_test.go b/internal/equipo/chat/change_diffs_test.go
index 0af8426d..11cb599c 100644
--- a/internal/equipo/chat/change_diffs_test.go
+++ b/internal/equipo/chat/change_diffs_test.go
@@ -81,7 +81,7 @@ func TestChangeDiffPublicationAndRead(t *testing.T) {
err = r.s.tx(ctx, func(tx *txn) error {
var st stepRecord
tx.db.First(&st, "id = ?", "s1")
- return tx.acceptChangeDiffs(l, st, v.Collection)
+ return tx.acceptChangeDiffs(l, st, v.Collection, st.RunnerID)
})
if err != nil {
t.Fatal(err)
@@ -177,7 +177,7 @@ func TestChangeDiffStateAndPublicationGuards(t *testing.T) {
if err := r.s.tx(ctx, func(tx *txn) error {
var st stepRecord
tx.db.First(&st, "id = ?", "s1")
- return tx.acceptChangeDiffs(l, st, v.Collection)
+ return tx.acceptChangeDiffs(l, st, v.Collection, st.RunnerID)
}); err != nil {
t.Fatal(err)
}
@@ -241,7 +241,7 @@ func TestChangeDiffEncodedResponseCap(t *testing.T) {
if err := r.s.tx(ctx, func(tx *txn) error {
var st stepRecord
tx.db.First(&st, "id = ?", "s1")
- return tx.acceptChangeDiffs(l, st, v.Collection)
+ return tx.acceptChangeDiffs(l, st, v.Collection, st.RunnerID)
}); err != nil {
t.Fatal(err)
}
@@ -263,7 +263,7 @@ func TestChangeDiffRechecksBeforeReturningBytes(t *testing.T) {
if err := r.s.tx(ctx, func(tx *txn) error {
var st stepRecord
tx.db.First(&st, "id = ?", "s1")
- return tx.acceptChangeDiffs(l, st, v.Collection)
+ return tx.acceptChangeDiffs(l, st, v.Collection, st.RunnerID)
}); err != nil {
t.Fatal(err)
}
@@ -327,7 +327,7 @@ func TestChangeDiffHiddenCharactersAndRetiredRead(t *testing.T) {
if err := r.s.tx(ctx, func(tx *txn) error {
var st stepRecord
tx.db.First(&st, "id = ?", "s1")
- return tx.acceptChangeDiffs(l, st, v.Collection)
+ return tx.acceptChangeDiffs(l, st, v.Collection, st.RunnerID)
}); err != nil {
t.Fatal(err)
}
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
index 2d82c910..7460c2c7 100644
--- a/internal/equipo/chat/runners.go
+++ b/internal/equipo/chat/runners.go
@@ -89,6 +89,15 @@ func (t *txn) withdrawnSettle(k *taskRecord, s *stepRecord) error {
}
return t.saveStep(s, k)
}
+ if s.Specialist == wire.SpecialistEngineering && s.Reason == wire.ReasonWorkspaceTooLarge {
+ // Its pack could not be relayed: it ends with Needs you, never on
+ // another runner.
+ endFailed(t, s, s.Reason)
+ if err := t.saveStep(s, k); err != nil {
+ return err
+ }
+ return t.advance(k)
+ }
if s.Reason != "" {
s.Terminated = true
return t.resolveNotRun(k, s, s.Reason)
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index fdba7770..e7ee0644 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -809,7 +809,7 @@ func (t *txn) writeStep(s *stepRecord) error {
}
s.Revision++
s.UpdatedAt = t.now()
- if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("base_checks", "base_checks_sha", "copy_owner", "copy_revision", "copy_result", "failure_signature", "state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_files", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold", "housekeeping_attempt", "coordinator_attempt", "held_at", "publish", "model", "xcode_access").Updates(s).Error; err != nil {
+ if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("base_checks", "base_checks_sha", "copy_owner", "copy_revision", "copy_result", "failure_signature", "state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_files", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold", "housekeeping_attempt", "coordinator_attempt", "held_at", "publish", "model", "xcode_access", "outcome_phase").Updates(s).Error; err != nil {
return err
}
if s.Retired {
@@ -1566,6 +1566,11 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
}
if s.CandidateSHA == "" && v.CandidateSHA != "" {
s.CandidateSHA, changed = v.CandidateSHA, true
+ if role != wire.RolePrimary && s.Specialist == wire.SpecialistEngineering && !s.Republish {
+ // A worker's commit: what it is (unfinished, no shell) is kept
+ // for its publication, which alone ends the step that way.
+ s.OutcomePhase = workerOutcome(v.OutcomePhase)
+ }
}
if v.Family != "" && s.Family != v.Family || v.Account != "" && s.Account != v.Account {
s.Family, s.Account, changed = firstSet(v.Family, s.Family), firstSet(v.Account, s.Account), true
@@ -1644,9 +1649,17 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
}
s.Pushed = true
}
- s.ChangeFiles = acceptChangeFiles(l, role, s, v.ChangeFiles)
- if err := t.acceptChangeDiffs(l, s, v.ChangeDiffs); err != nil {
- return err
+ if role == wire.RolePrimary {
+ s.ChangeFiles = acceptChangeFiles(l, role, s, v.ChangeFiles)
+ if err := t.acceptChangeDiffs(l, s, v.ChangeDiffs, l.Runner.RunnerID); err != nil {
+ return err
+ }
+ } else {
+ // A worker's commit is measured by the primary when it
+ // publishes (published): this report never sets or clears
+ // its files or diffs, and its outcome's reason waits for
+ // that publication too.
+ takeOutcome(&s)
}
s.Apple = v.Apple
s.Askable = v.Askable
@@ -2231,7 +2244,7 @@ func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool)
st.Activity = ""
if st.Specialist == wire.SpecialistEngineering && !republish {
// Engineering runs again from the step's base: a new candidate.
- st.CandidateSHA = ""
+ st.CandidateSHA, st.OutcomePhase = "", ""
}
if !republish {
st.FromAttempt = 0
diff --git a/internal/equipo/chat/transfers.go b/internal/equipo/chat/transfers.go
index 7f2a89de..26f3ca70 100644
--- a/internal/equipo/chat/transfers.go
+++ b/internal/equipo/chat/transfers.go
@@ -115,7 +115,8 @@ func (t *txn) blob(l Lease, v *wire.Blob) error {
return errTransferRefused("attempt not current")
}
if v.Total > wire.MaxTransferChunks {
- // Declared too large to relay: the checks cannot run on that runner.
+ // Declared too large to relay: the checks cannot run on that runner,
+ // nor Engineering on that Mac.
return t.tooLarge(&k, &s, tr)
}
data, err := base64.StdEncoding.DecodeString(v.Data)
@@ -145,7 +146,8 @@ func (t *txn) blob(l Lease, v *wire.Blob) error {
}
// tooLarge closes a transfer past the bound; inbound, its checks end as
-// not run (checks_unavailable).
+// not run (checks_unavailable), and Engineering on a Mac ends
+// workspace_too_large with Needs you (it never runs on Linux instead).
func (t *txn) tooLarge(k *taskRecord, s *stepRecord, tr transferRecord) error {
if err := t.dropChunks(tr); err != nil {
return err
@@ -153,10 +155,40 @@ func (t *txn) tooLarge(k *taskRecord, s *stepRecord, tr transferRecord) error {
if err := t.db.Model(&transferRecord{}).Where("id = ?", tr.ID).Update("state", transferClosed).Error; err != nil {
return err
}
- if tr.Direction == wire.TransferInbound && !wire.StepTerminal(s.State) {
- return t.withdrawResolving(k, s, "checks_unavailable")
+ if tr.Direction != wire.TransferInbound || wire.StepTerminal(s.State) {
+ return nil
}
- return nil
+ if tr.Kind == wire.TransferKindEngineering {
+ return t.withdrawFailing(k, s, wire.ReasonWorkspaceTooLarge)
+ }
+ return t.withdrawResolving(k, s, "checks_unavailable")
+}
+
+// withdrawFailing withdraws an Engineering attempt that will end failed
+// for reason: at once when it never started, else once its termination
+// is reported (withdrawnSettle).
+func (t *txn) withdrawFailing(k *taskRecord, s *stepRecord, reason string) error {
+ if s.StartedAt == nil {
+ if err := t.voidAttempt(*s); err != nil {
+ return err
+ }
+ endFailed(t, s, reason)
+ if err := t.saveStep(s, k); err != nil {
+ return err
+ }
+ return t.advance(k)
+ }
+ s.Withdrawn, s.Reason = true, reason
+ if err := t.saveStep(s, k); err != nil {
+ return err
+ }
+ return t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt})
+}
+
+// endFailed ends an attempt failed for reason, its end proven.
+func endFailed(t *txn, s *stepRecord, reason string) {
+ now := t.now()
+ s.State, s.Reason, s.Terminated, s.FinishedAt, s.Withdrawn, s.Placement = wire.StepFailed, reason, true, &now, false, ""
}
// blobAcked closes a transfer once its receiver acked the last chunk.
@@ -222,7 +254,38 @@ func (t *txn) publish(k *taskRecord, s *stepRecord, tr transferRecord) error {
if err := t.saveStep(s, k); err != nil {
return err
}
- return t.commandTo(primary, s.Person, wire.FramePublish, wire.PublishCommand{Publication: s.PublicationID, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, Repo: tr.Repo, Branch: k.Branch, Person: s.Person, BaseSHA: tr.BaseSHA, CandidateSHA: tr.CandidateSHA, Transfer: tr.ID})
+ // Diffs an earlier publication of this attempt left unaccepted are
+ // stale: only this publication's primary uploads count now.
+ if err := t.db.Where("step_id = ? AND attempt = ? AND accepted = ?", s.ID, s.Attempt, false).Delete(&changeDiffRecord{}).Error; err != nil {
+ return err
+ }
+ return t.commandTo(primary, s.Person, wire.FramePublish, wire.PublishCommand{Publication: s.PublicationID, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, Repo: tr.Repo, Branch: k.Branch, Person: s.Person, BaseSHA: tr.BaseSHA, CandidateSHA: tr.CandidateSHA, Transfer: tr.ID, OutcomePhase: s.OutcomePhase})
+}
+
+// workerOutcome is the outcome a worker's committed report names, if it
+// is one ("" is an ordinary commit).
+func workerOutcome(phase string) string {
+ switch phase {
+ case wire.OutcomeCommitted, wire.OutcomeUnfinished, wire.OutcomeNoShell:
+ return phase
+ }
+ return ""
+}
+
+// takeOutcome: once a worker's commit is published, the step ends as its
+// outcome says: step_timeout for unfinished work, shell_unavailable for
+// a fix round without a shell (each over proposal_failed, as on the
+// primary).
+func takeOutcome(s *stepRecord) {
+ if !s.Pushed || s.Publication != wire.PublicationPublished {
+ return
+ }
+ switch s.OutcomePhase {
+ case wire.OutcomeUnfinished:
+ s.Reason = reasonUnfinished
+ case wire.OutcomeNoShell:
+ s.Reason = wire.ReasonShellUnavailable
+ }
}
// published applies the primary's answer: only the primary, only for the
@@ -262,6 +325,15 @@ func (t *txn) published(l Lease, v *wire.PublishedReport) error {
if v.Reason == "proposal_failed" {
s.Reason = v.Reason
}
+ if s.State == wire.StepDone {
+ takeOutcome(&s)
+ }
+ // The primary's measurement of the candidate it pushed (protocol
+ // 37): its files here, its diffs from the uploads naming this
+ // publication.
+ if l.Protocol >= wire.ProtocolMacEngineering {
+ s.ChangeFiles = acceptChangeFiles(l, wire.RolePrimary, s, v.ChangeFiles)
+ }
} else {
s.Publication = wire.PublicationFailed
switch v.Reason {
@@ -274,6 +346,11 @@ func (t *txn) published(l Lease, v *wire.PublishedReport) error {
if err := t.saveStep(&s, &k); err != nil {
return err
}
+ if v.Pushed && !s.Retired && l.Protocol >= wire.ProtocolMacEngineering {
+ if err := t.acceptChangeDiffs(l, s, v.DiffCollection, l.Runner.RunnerID); err != nil {
+ return err
+ }
+ }
if s.Retired {
return t.finishAbandon(&k)
}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 57c31d4d..128cf316 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -2523,6 +2523,7 @@ var pageCopy = map[string]string{
"work.decide.mac_update_why": "This change needs a Mac. %s needs an update before the change can be made there.", // COPY REVIEW PENDING
"work.decide.mac_wait_ask": "It starts by itself once %s is ready. You can also cancel it.", // COPY REVIEW PENDING
"work.reason.base_unavailable": "the main runner couldn’t get the version of the project to start from", // COPY REVIEW PENDING
+ "work.reason.workspace_too_large": "the project is too large to send to the Mac", // COPY REVIEW PENDING
"chat.merge.not.mac_made": "it was made on a Mac runner, so it merges only when you choose", // COPY REVIEW PENDING
}
diff --git a/internal/runner/thin/change_diffs.go b/internal/runner/thin/change_diffs.go
index 6ea69fa0..4db48f3c 100644
--- a/internal/runner/thin/change_diffs.go
+++ b/internal/runner/thin/change_diffs.go
@@ -5,6 +5,7 @@ import (
"database/sql"
"encoding/base64"
"encoding/json"
+ "errors"
"os/exec"
"slices"
"strconv"
@@ -162,36 +163,77 @@ func (e *Engineer) queueChangeDiffs(ctx context.Context, r stepRow, git, dir str
return ""
}
defer e.diffCollect.Unlock()
+ ups, collection := e.changeDiffUploads(ctx, r.Repo, wire.ChangeDiffUpload{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt}, git, dir, f)
+ if len(ups) == 0 {
+ return ""
+ }
+ err := e.O.State.tx(ctx, func(tx *sql.Tx) error {
+ for _, v := range ups {
+ if err := e.O.State.enqueue(tx, wire.FrameChangeDiff, "", v); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return ""
+ }
+ return collection
+}
+
+// changeDiffUploads is the display collection of f as uploads naming
+// at's task, step, attempt and (for a worker's candidate) publication,
+// with this runner's known secrets left out: its diff secrets (the
+// runner's bearer token) and the forge credential it already uses for
+// repo. Nothing when the credential cannot be read or a frame would be
+// too large.
+func (e *Engineer) changeDiffUploads(ctx context.Context, repo string, at wire.ChangeDiffUpload, git, dir string, f *wire.ChangeFiles) ([]wire.ChangeDiffUpload, string) {
known := slices.Clone(e.DiffSecrets)
// Read only the credential file already used for this runner's forge work;
// never resolve a remote credential or access the network for display.
if e.O.Runner.AmadanCredentialPath != "" {
- credential, err := (forge.FileCredentials{Path: e.O.Runner.AmadanCredentialPath}).Credential(ctx, r.Repo)
+ credential, err := (forge.FileCredentials{Path: e.O.Runner.AmadanCredentialPath}).Credential(ctx, repo)
if err != nil {
- return ""
+ return nil, ""
}
known = append(known, credential.Bearer, credential.GitPassword)
}
files := collectChangeDiffs(ctx, git, dir, f, known)
if len(files) == 0 {
- return ""
+ return nil, ""
}
collection := wire.DiffCollection(files)
- err := e.O.State.tx(ctx, func(tx *sql.Tx) error {
- for i, file := range files {
- v := wire.ChangeDiffUpload{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, Base: f.Base, Candidate: f.SHA, Collection: collection, Index: i, Total: len(files), Path: file.Path, Size: len(file.Patch), SHA256: wire.DiffDigest([]byte(file.Patch)), Data: base64.StdEncoding.EncodeToString([]byte(file.Patch)), Reason: file.Reason, Truncated: file.Truncated}
- raw, _ := json.Marshal(v)
- if len(raw) > wire.MaxFrameBytes-1024 {
- return wire.ErrProtocol
- }
- if err := e.O.State.enqueue(tx, wire.FrameChangeDiff, "", v); err != nil {
- return err
- }
+ ups := make([]wire.ChangeDiffUpload, 0, len(files))
+ for i, file := range files {
+ v := wire.ChangeDiffUpload{TaskID: at.TaskID, StepID: at.StepID, Attempt: at.Attempt, Publication: at.Publication, Base: f.Base, Candidate: f.SHA, Collection: collection, Index: i, Total: len(files), Path: file.Path, Size: len(file.Patch), SHA256: wire.DiffDigest([]byte(file.Patch)), Data: base64.StdEncoding.EncodeToString([]byte(file.Patch)), Reason: file.Reason, Truncated: file.Truncated}
+ raw, _ := json.Marshal(v)
+ if len(raw) > wire.MaxFrameBytes-1024 {
+ return nil, ""
}
- return nil
- })
- if err != nil {
- return ""
+ ups = append(ups, v)
}
- return collection
+ return ups, collection
+}
+
+// publicationDiffs measures a worker's pushed candidate on its base in
+// the publication's private repository: the change files, and the diffs
+// bound to the publication (protocol 37; an older instance has no words
+// for either). Any failure is a diagnostic: the push stands, with fewer
+// facts.
+func (e *Engineer) publicationDiffs(ctx context.Context, p pubRow, dir string) (*wire.ChangeFiles, string, []wire.ChangeDiffUpload) {
+ if e.O.Protocol == nil || e.O.Protocol() < wire.ProtocolMacEngineering {
+ return nil, "", nil
+ }
+ files := changeFiles(ctx, e.O.Runner.GitPath, dir, p.BaseSHA, p.CandidateSHA)
+ if files == nil {
+ e.log("publication change files", errors.New("the candidate could not be measured on its base"))
+ return nil, "", nil
+ }
+ e.diffCollect.Lock()
+ defer e.diffCollect.Unlock()
+ ups, collection := e.changeDiffUploads(ctx, p.Repo, wire.ChangeDiffUpload{TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, Publication: p.Publication}, e.O.Runner.GitPath, dir, files)
+ if len(ups) == 0 {
+ e.log("publication change diffs", errors.New("no diffs for the candidate"))
+ }
+ return files, collection, ups
}
diff --git a/internal/runner/thin/engineer_time_test.go b/internal/runner/thin/engineer_time_test.go
index 1fc9355f..8b72a57b 100644
--- a/internal/runner/thin/engineer_time_test.go
+++ b/internal/runner/thin/engineer_time_test.go
@@ -235,7 +235,7 @@ func TestUnfinishedReportQueuedSafely(t *testing.T) {
if read(f).StepID != c.step {
continue
}
- sent, err := s.unfinishedReport(ctx, f, c.protocol)
+ sent, err := s.unfinishedReport(ctx, f, c.protocol, false)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index 5a2aab7b..de22abe5 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -477,7 +477,7 @@ func (l *Link) Run(ctx context.Context) error {
// a frame that protocol does not have is not sent.
func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error {
l.mu.Lock()
- proto := l.proto
+ proto, role := l.proto, l.role
l.mu.Unlock()
if f.Type == wire.FrameToolCall {
body, err := f.Decode()
@@ -501,7 +501,7 @@ func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error
}
}
}
- f, err := l.State.unfinishedReport(ctx, f, proto)
+ f, err := l.State.unfinishedReport(ctx, f, proto, role == wire.RoleWorker)
if err != nil {
return err
}
@@ -909,6 +909,15 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro
if l.Relay != nil {
l.Relay.Wake()
}
+ case *wire.PrepareBaseCommand:
+ // Mac Engineering on a worker (protocol 37): the primary resolves
+ // the attempt's base, durably, and reports it once per attempt.
+ if err = l.State.AcceptPrepareBase(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
+ if l.Relay != nil {
+ l.Relay.Wake()
+ }
case *wire.Ack:
if l.resolve(v.ID, "") {
continue
diff --git a/internal/runner/thin/relay.go b/internal/runner/thin/relay.go
index 6ee8e5b1..c2e81098 100644
--- a/internal/runner/thin/relay.go
+++ b/internal/runner/thin/relay.go
@@ -35,6 +35,7 @@ CREATE TABLE IF NOT EXISTS chunks (transfer TEXT NOT NULL, idx INTEGER NOT NULL,
CREATE INDEX IF NOT EXISTS chunks_step ON chunks(step_id, attempt);
CREATE TABLE IF NOT EXISTS uploads (transfer TEXT PRIMARY KEY, body TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS publications (id TEXT PRIMARY KEY, body TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL);
+CREATE TABLE IF NOT EXISTS bases (step_id TEXT NOT NULL, attempt INTEGER NOT NULL, body TEXT NOT NULL, base_sha TEXT NOT NULL DEFAULT '', reason TEXT NOT NULL DEFAULT '', state TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (step_id, attempt));
`
// Upload and publication states.
@@ -91,6 +92,53 @@ func (s *State) AcceptPublish(ctx context.Context, frameID string, c wire.Publis
})
}
+// AcceptPrepareBase records a prepare_base command exactly once. An
+// attempt is resolved once: asked again (a new frame for the same
+// attempt), it is answered with the base it was given, even if the
+// default branch has moved since.
+func (s *State) AcceptPrepareBase(ctx context.Context, frameID string, c wire.PrepareBaseCommand) error {
+ raw, _ := json.Marshal(c)
+ return s.tx(ctx, func(t *sql.Tx) error {
+ fresh, err := seen(t, frameID)
+ if err != nil || !fresh {
+ return err
+ }
+ var body, state, base, reason string
+ err = t.QueryRow("SELECT body, state, base_sha, reason FROM bases WHERE step_id=? AND attempt=?", c.StepID, c.Attempt).Scan(&body, &state, &base, &reason)
+ if errors.Is(err, sql.ErrNoRows) {
+ _, err = t.Exec("INSERT INTO bases(step_id, attempt, body, state, created_at) VALUES(?,?,?,?,?)", c.StepID, c.Attempt, string(raw), relayPending, now())
+ return err
+ }
+ if err != nil || state != relayReported {
+ return err
+ }
+ var was wire.PrepareBaseCommand
+ if json.Unmarshal([]byte(body), &was) != nil || was.TaskID != c.TaskID {
+ return nil
+ }
+ return s.enqueue(t, wire.FrameBase, "", wire.BaseReport{TaskID: was.TaskID, StepID: was.StepID, Attempt: was.Attempt, BaseSHA: base, Reason: reason})
+ })
+}
+
+func (s *State) pendingBases(ctx context.Context) ([]wire.PrepareBaseCommand, error) {
+ return relayRows[wire.PrepareBaseCommand](ctx, s, "SELECT body FROM bases WHERE state=? ORDER BY created_at", relayPending)
+}
+
+// reportBase records an attempt's base and queues its report, in one
+// transaction: the attempt is never resolved twice.
+func (s *State) reportBase(ctx context.Context, rep wire.BaseReport) error {
+ return s.tx(ctx, func(t *sql.Tx) error {
+ res, err := t.Exec("UPDATE bases SET state=?, base_sha=?, reason=? WHERE step_id=? AND attempt=? AND state=?", relayReported, rep.BaseSHA, rep.Reason, rep.StepID, rep.Attempt, relayPending)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n != 1 {
+ return nil
+ }
+ return s.enqueue(t, wire.FrameBase, "", rep)
+ })
+}
+
// ErrPackIncomplete means not every chunk of a transfer has arrived.
var ErrPackIncomplete = errors.New("pack incomplete")
@@ -257,9 +305,10 @@ func (s *State) setPublication(ctx context.Context, id, state string) error {
return err
}
-// reportPublished queues the published report and marks the publication
-// reported, in one transaction.
-func (s *State) reportPublished(ctx context.Context, rep wire.PublishedReport) error {
+// reportPublished queues the publication's change diffs, then its
+// published report, and marks the publication reported, in one
+// transaction.
+func (s *State) reportPublished(ctx context.Context, rep wire.PublishedReport, diffs []wire.ChangeDiffUpload) error {
return s.tx(ctx, func(t *sql.Tx) error {
next := relayReported
if !rep.Pushed {
@@ -272,6 +321,11 @@ func (s *State) reportPublished(ctx context.Context, rep wire.PublishedReport) e
if n, _ := res.RowsAffected(); n != 1 {
return nil
}
+ for _, d := range diffs {
+ if err := s.enqueue(t, wire.FrameChangeDiff, "", d); err != nil {
+ return err
+ }
+ }
return s.enqueue(t, wire.FramePublished, "", rep)
})
}
@@ -322,10 +376,20 @@ func (x *Relay) Loop(ctx context.Context) {
// Once does what is pending now.
func (x *Relay) Once(ctx context.Context) {
+ bases, err := x.State.pendingBases(ctx)
+ x.log("relay bases", err)
+ for _, c := range bases {
+ rep, done := x.Engine.prepareBase(ctx, c)
+ if !done {
+ continue
+ }
+ x.log("relay base", x.State.reportBase(context.WithoutCancel(ctx), rep))
+ x.notify()
+ }
ups, err := x.State.pendingUploads(ctx)
x.log("relay uploads", err)
for _, u := range ups {
- pack, err := x.Engine.packCandidate(ctx, u.Transfer)
+ pack, err := x.Engine.packCommits(ctx, u.Transfer)
if err != nil {
x.log("relay pack", err)
continue
@@ -336,11 +400,11 @@ func (x *Relay) Once(ctx context.Context) {
pubs, err := x.State.openPublications(ctx)
x.log("relay publications", err)
for _, p := range pubs {
- rep, done := x.Engine.publishWorker(ctx, p)
+ rep, diffs, done := x.Engine.publishWorker(ctx, p)
if !done {
continue
}
- x.log("relay published", x.State.reportPublished(context.WithoutCancel(ctx), rep))
+ x.log("relay published", x.State.reportPublished(context.WithoutCancel(ctx), rep, diffs))
x.notify()
}
}
@@ -357,20 +421,69 @@ func (x *Relay) log(msg string, err error) {
}
}
-// packCandidate is the pack of exactly one commit (the commit, its tree
-// and blobs, no history) from the project clone.
-func (e *Engineer) packCandidate(ctx context.Context, h wire.TransferHeader) ([]byte, error) {
- if !forgekey.ValidHub(h.Repo) || !shaPattern.MatchString(h.CandidateSHA) {
+// prepareBase resolves a worker attempt's base as Engineer.Exec does on
+// the primary: fetch, then the default branch's tip. A repository with no
+// commits (never Mac work), one that is not a hub repository, a clone
+// that cannot be fetched, or a rebase round whose commits the clone does
+// not have, is base_unavailable. done is false only when ctx ended.
+func (e *Engineer) prepareBase(ctx context.Context, c wire.PrepareBaseCommand) (wire.BaseReport, bool) {
+ rep := wire.BaseReport{TaskID: c.TaskID, StepID: c.StepID, Attempt: c.Attempt, Reason: wire.ReasonBaseUnavailable}
+ if !c.Valid() || !forgekey.ValidHub(c.Repo) {
+ return rep, true
+ }
+ fctx, cancel := context.WithTimeout(ctx, prepTimeout)
+ defer cancel()
+ if err := e.fetch(fctx, c.Repo); err != nil {
+ if ctx.Err() != nil {
+ return rep, false
+ }
+ e.log("prepare base fetch", err)
+ return rep, true
+ }
+ tip, err := e.defaultTip(fctx, c.Repo)
+ if err != nil {
+ // ErrEmptyRepo included: a worker refuses an empty base.
+ e.log("prepare base tip", err)
+ return rep, true
+ }
+ if c.Rebase && (!e.hasCommit(fctx, c.Repo, c.FromBase) || !e.hasCommit(fctx, c.Repo, c.CandidateSHA)) {
+ e.log("prepare base rebase", errors.New("the rebase round's commits are not in the clone"))
+ return rep, true
+ }
+ rep.BaseSHA, rep.Reason = tip, ""
+ return rep, true
+}
+
+// packCommits is the pack of exactly the commits the header names
+// (TransferHeader.Commits), each with its tree and blobs, and no history:
+// for a checks transfer the candidate alone, for an Engineering transfer
+// the base and, for a rebase round, the old base and the candidate. A
+// header that is not valid, a repository that is not a hub repository,
+// or a name that is not a full SHA is refused before git runs; a commit
+// the fresh clone does not have is refused before the pack is built.
+func (e *Engineer) packCommits(ctx context.Context, h wire.TransferHeader) ([]byte, error) {
+ commits := h.Commits()
+ if !forgekey.ValidHub(h.Repo) || !h.Valid() || len(commits) == 0 {
return nil, errPackRefused
}
+ for _, c := range commits {
+ if !shaPattern.MatchString(c) {
+ return nil, errPackRefused
+ }
+ }
ctx, cancel := context.WithTimeout(ctx, prepTimeout)
defer cancel()
if err := e.fetch(ctx, h.Repo); err != nil {
return nil, err
}
+ for _, c := range commits {
+ if !e.hasCommit(ctx, h.Repo, c) {
+ return nil, errPackRefused
+ }
+ }
env := workspace.GitEnvironment()
env["HOME"] = "/nonexistent"
- list := groupCommand(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(h.Repo), "rev-list", "--objects", "--no-walk", h.CandidateSHA)
+ list := groupCommand(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + e.Clones.Path(h.Repo), "rev-list", "--objects", "--no-walk", "--end-of-options"}, commits...)...)
pack := groupCommand(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(h.Repo), "pack-objects", "--stdout", "-q")
for k, v := range env {
list.Env = append(list.Env, k+"="+v)
@@ -426,13 +539,16 @@ var relayFault func(point string) bool
// as its parent and a complete tree, the instance confirms the
// publication right before the push, and forge pushes it with every check
// it makes for the primary's own work (record, then reconcile, so a
-// repeat after a crash pushes nothing twice). done is false while it must
-// be tried again (chunks still arriving, no lease now).
-func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedReport, bool) {
- rep := wire.PublishedReport{Publication: p.Publication, TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, CandidateSHA: p.CandidateSHA}
- fail := func(reason string) (wire.PublishedReport, bool) {
+// repeat after a crash pushes nothing twice). Once pushed, and only
+// then, the candidate's change files and diffs on the base are measured
+// here, bound to the publication (publicationDiffs). The report echoes
+// the outcome the publish command named. done is false while it must be
+// tried again (chunks still arriving, no lease now).
+func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedReport, []wire.ChangeDiffUpload, bool) {
+ rep := wire.PublishedReport{Publication: p.Publication, TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, CandidateSHA: p.CandidateSHA, OutcomePhase: p.OutcomePhase}
+ fail := func(reason string) (wire.PublishedReport, []wire.ChangeDiffUpload, bool) {
rep.Pushed, rep.Reason = false, reason
- return rep, true
+ return rep, nil, true
}
if !slices.Contains(e.Owners, p.Person) || !forgekey.ValidHub(p.Repo) || !wire.ValidTaskBranch(p.Branch) || !shaPattern.MatchString(p.CandidateSHA) || !shaPattern.MatchString(p.BaseSHA) {
return fail("policy_rejected")
@@ -443,7 +559,7 @@ func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedR
switch {
case errors.Is(err, ErrPackIncomplete):
if _, statErr := os.Stat(dir); statErr != nil {
- return rep, false
+ return rep, nil, false
}
// Indexed before (a republish): the chunks are gone.
case err != nil:
@@ -456,12 +572,12 @@ func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedR
}
}
if err := e.O.State.setPublication(ctx, p.Publication, relayIndexed); err != nil {
- return rep, false
+ return rep, nil, false
}
e.log("publication chunks", e.O.State.dropChunks(ctx, p.Transfer))
}
if relayFault != nil && relayFault("indexed") {
- return rep, false
+ return rep, nil, false
}
if err := e.verifyWorkerCommit(ctx, p, dir); err != nil {
e.log("publication verify", err)
@@ -486,7 +602,7 @@ func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedR
Remote: func(ctx context.Context) (workspace.Remote, error) { return e.Forge.Remote(ctx, p.Repo, Push) },
Confirm: confirm})
if relayFault != nil && relayFault("pushed") {
- return rep, false
+ return rep, nil, false
}
switch {
case err == nil:
@@ -494,12 +610,14 @@ func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedR
if _, proposalErr := e.Forge.Propose(ctx, Proposal{Repo: p.Repo, Branch: p.Branch}); proposalErr != nil {
rep.Reason = "proposal_failed"
}
- return rep, true
+ var diffs []wire.ChangeDiffUpload
+ rep.ChangeFiles, rep.DiffCollection, diffs = e.publicationDiffs(ctx, p, dir)
+ return rep, diffs, true
case errors.Is(refused, ErrWithdrawn):
return fail("cancelled")
case refused != nil:
// No lease now (disconnected): try again later.
- return rep, false
+ return rep, nil, false
case errors.Is(err, forge.ErrPushConflict):
return fail("push_conflict")
default:
diff --git a/internal/runner/thin/relay_engineering_test.go b/internal/runner/thin/relay_engineering_test.go
new file mode 100644
index 00000000..a7765e71
--- /dev/null
+++ b/internal/runner/thin/relay_engineering_test.go
@@ -0,0 +1,508 @@
+package thin
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Mac runners slice F, plan task 4: the primary's side of the base
+// exchange. It resolves a worker attempt's base (prepare_base, then a
+// durable base report), packs exactly the commits an Engineering header
+// names, and, once it has pushed a worker's candidate, sends the change
+// files and diffs bound to that publication.
+
+const sampleRepo = "amadan.net/oficina/sample"
+
+// bases are the base reports in the outbox, in order.
+func (r *relayRig) bases(t *testing.T) []wire.BaseReport {
+ t.Helper()
+ frames, _, err := r.e.O.State.Unacked(context.Background(), 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []wire.BaseReport
+ for _, f := range frames {
+ if f.Type == wire.FrameBase {
+ var b wire.BaseReport
+ if err := json.Unmarshal(f.Data, &b); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, b)
+ }
+ }
+ return out
+}
+
+func (r *relayRig) prepare(t *testing.T, frame string, attempt int64) {
+ t.Helper()
+ if err := r.e.O.State.AcceptPrepareBase(context.Background(), frame, wire.PrepareBaseCommand{TaskID: "tk1", StepID: "s1", Attempt: attempt, Repo: sampleRepo}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// reopen is a restart: the same state directory opened again, a new
+// relay over it.
+func (r *relayRig) reopen(t *testing.T) {
+ t.Helper()
+ r.e.O.State.Close()
+ s, err := OpenState(context.Background(), filepath.Join(r.root, "state"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { s.Close() })
+ r.e.O.State = s
+ r.relay = &Relay{State: s, Engine: r.e}
+}
+
+// The primary fetches and reports the default branch's tip for the
+// attempt, once. The same attempt asked again (a restart, a resent
+// command) is answered with the same SHA even after the branch moved; a
+// new attempt gets the tip as it is now.
+func TestPrepareBaseResolvesAndIsIdempotent(t *testing.T) {
+ r := newRelayRig(t)
+ ctx := context.Background()
+ r.prepare(t, "pb-1", 1)
+ r.relay.Once(ctx)
+ got := r.bases(t)
+ if len(got) != 1 || got[0] != (wire.BaseReport{TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: r.base}) || !got[0].Valid() {
+ t.Fatalf("base reports %+v, want %s", got, r.base)
+ }
+ // The default branch moves on.
+ gitOut(t, r.seed, "push", "-q", r.remote, "main")
+ r.reopen(t)
+ r.relay.Once(ctx)
+ if got := r.bases(t); len(got) != 1 {
+ t.Fatalf("reported again after a restart: %+v", got)
+ }
+ // The same frame again does nothing; the same attempt asked again is
+ // answered with the SHA it was given.
+ r.prepare(t, "pb-1", 1)
+ r.prepare(t, "pb-2", 1)
+ r.relay.Once(ctx)
+ got = r.bases(t)
+ if len(got) != 2 || got[1].BaseSHA != r.base || got[1].Attempt != 1 {
+ t.Fatalf("same attempt asked again: %+v", got)
+ }
+ r.prepare(t, "pb-3", 2)
+ r.relay.Once(ctx)
+ got = r.bases(t)
+ if len(got) != 3 || got[2].Attempt != 2 || got[2].BaseSHA != r.commit {
+ t.Fatalf("a new attempt: %+v, want %s", got, r.commit)
+ }
+}
+
+// A repository with no commits has no base for a worker (it is never Mac
+// work): base_unavailable. So does a repository the primary does not
+// publish to (before git runs) and a rebase round whose commits the clone
+// does not have.
+func TestPrepareBaseRefusesUnborn(t *testing.T) {
+ ctx := context.Background()
+ t.Run("unborn", func(t *testing.T) {
+ r := newRelayRig(t)
+ empty := filepath.Join(r.root, "empty.git")
+ gitOut(t, r.root, "init", "-q", "--bare", "-b", "main", empty)
+ r.f.dir = empty
+ r.prepare(t, "pb-1", 1)
+ r.relay.Once(ctx)
+ if got := r.bases(t); len(got) != 1 || got[0].Reason != wire.ReasonBaseUnavailable || got[0].BaseSHA != "" || !got[0].Valid() {
+ t.Fatalf("unborn: %+v", got)
+ }
+ })
+ t.Run("not a hub repository", func(t *testing.T) {
+ r := newRelayRig(t)
+ r.e.O.Runner.GitPath, r.e.Clones.Git = "/nonexistent/git", "/nonexistent/git"
+ if err := r.e.O.State.AcceptPrepareBase(ctx, "pb-1", wire.PrepareBaseCommand{TaskID: "tk1", StepID: "s1", Attempt: 1, Repo: "github.com/someone/else"}); err != nil {
+ t.Fatal(err)
+ }
+ r.relay.Once(ctx)
+ if got := r.bases(t); len(got) != 1 || got[0].Reason != wire.ReasonBaseUnavailable {
+ t.Fatalf("not a hub repository: %+v", got)
+ }
+ })
+ t.Run("rebase commits missing", func(t *testing.T) {
+ r := newRelayRig(t)
+ if err := r.e.O.State.AcceptPrepareBase(ctx, "pb-1", wire.PrepareBaseCommand{TaskID: "tk1", StepID: "s1", Attempt: 1, Repo: sampleRepo, Rebase: true, FromBase: r.base, CandidateSHA: strings.Repeat("e", 40)}); err != nil {
+ t.Fatal(err)
+ }
+ r.relay.Once(ctx)
+ if got := r.bases(t); len(got) != 1 || got[0].Reason != wire.ReasonBaseUnavailable {
+ t.Fatalf("rebase without its candidate: %+v", got)
+ }
+ })
+}
+
+// packRig is a remote with history: main at c1 on c0, and a task branch
+// whose tip c2 sits on c0 (the old base of a rebase round onto c1).
+func packRig(t *testing.T) (r *relayRig, c0, c1, c2 string) {
+ t.Helper()
+ r = newRelayRig(t)
+ work := filepath.Join(r.root, "history")
+ gitOut(t, r.root, "init", "-q", "-b", "main", work)
+ write := func(name, text string) {
+ os.MkdirAll(filepath.Dir(filepath.Join(work, name)), 0755)
+ os.WriteFile(filepath.Join(work, name), []byte(text), 0644)
+ }
+ write("README.md", "zero\n")
+ write("Sources/App.swift", "let a = 0\n")
+ gitOut(t, work, "add", "-A")
+ gitOut(t, work, "commit", "-q", "-m", "c0")
+ c0 = gitOut(t, work, "rev-parse", "HEAD")
+ write("Sources/App.swift", "let a = 1\n")
+ write("Sources/More.swift", "let m = 1\n")
+ gitOut(t, work, "add", "-A")
+ gitOut(t, work, "commit", "-q", "-m", "c1")
+ c1 = gitOut(t, work, "rev-parse", "HEAD")
+ gitOut(t, work, "checkout", "-q", "-b", relayBranch, c0)
+ write("Sources/Task.swift", "let t = 2\n")
+ gitOut(t, work, "add", "-A")
+ gitOut(t, work, "commit", "-q", "-m", "c2")
+ c2 = gitOut(t, work, "rev-parse", "HEAD")
+ remote := filepath.Join(r.root, "history.git")
+ gitOut(t, r.root, "clone", "-q", "--bare", "--no-single-branch", work, remote)
+ r.f.dir = remote
+ return r, c0, c1, c2
+}
+
+// packInventory indexes pack into an empty repository and lists the
+// objects in the pack itself (verify-pack), by type.
+func packInventory(t *testing.T, pack []byte) map[string][]string {
+ t.Helper()
+ dir := filepath.Join(t.TempDir(), "empty.git")
+ if out, err := exec.Command("git", "init", "-q", "--bare", dir).CombinedOutput(); err != nil {
+ t.Fatalf("%v: %s", err, out)
+ }
+ index := exec.Command("git", "--git-dir="+dir, "index-pack", "--stdin")
+ index.Stdin = bytes.NewReader(pack)
+ if out, err := index.CombinedOutput(); err != nil {
+ t.Fatalf("index-pack: %v: %s", err, out)
+ }
+ idx, _ := filepath.Glob(filepath.Join(dir, "objects", "pack", "*.idx"))
+ if len(idx) != 1 {
+ t.Fatalf("pack indexes %v", idx)
+ }
+ out, err := exec.Command("git", "verify-pack", "-v", idx[0]).Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ inv := map[string][]string{}
+ for _, line := range strings.Split(string(out), "\n") {
+ f := strings.Fields(line)
+ if len(f) >= 3 && shaPattern.MatchString(f[0]) {
+ inv[f[1]] = append(inv[f[1]], f[0])
+ }
+ }
+ for _, v := range inv {
+ sort.Strings(v)
+ }
+ return inv
+}
+
+// objectsOf is every object of the commits and their trees, no history,
+// from the source repository.
+func objectsOf(t *testing.T, gitDir string, commits ...string) []string {
+ t.Helper()
+ out, err := exec.Command("git", append([]string{"--git-dir=" + gitDir, "rev-list", "--objects", "--no-walk"}, commits...)...).Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var all []string
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ all = append(all, strings.Fields(line)[0])
+ }
+ sort.Strings(all)
+ return all
+}
+
+// An Engineering pack holds exactly the commits its header names, each
+// with its complete tree, and no other commit (their parents stay out);
+// a checks pack is still exactly the candidate.
+func TestPackCommitsInventory(t *testing.T) {
+ r, c0, c1, c2 := packRig(t)
+ ctx := context.Background()
+ for _, c := range []struct {
+ name string
+ h wire.TransferHeader
+ want []string
+ }{
+ {"first step", wire.TransferHeader{ID: "tr_e1", Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: c1}, []string{c1}},
+ {"rebase round", wire.TransferHeader{ID: "tr_e2", Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: sampleRepo, TaskID: "tk1", StepID: "s2", Attempt: 1, BaseSHA: c1, OldBaseSHA: c0, CandidateSHA: c2}, []string{c1, c0, c2}},
+ {"checks", wire.TransferHeader{ID: "tr_c", Direction: wire.TransferInbound, Repo: sampleRepo, TaskID: "tk1", StepID: "s3", Attempt: 1, BaseSHA: c0, CandidateSHA: c2}, []string{c2}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ pack, err := r.e.packCommits(ctx, c.h)
+ if err != nil {
+ t.Fatal(err)
+ }
+ inv := packInventory(t, pack)
+ want := slices.Clone(c.want)
+ sort.Strings(want)
+ if !slices.Equal(inv["commit"], want) {
+ t.Fatalf("commits in the pack %v, want exactly %v", inv["commit"], want)
+ }
+ var got []string
+ for _, kind := range []string{"commit", "tree", "blob", "tag"} {
+ got = append(got, inv[kind]...)
+ }
+ sort.Strings(got)
+ if all := objectsOf(t, r.e.Clones.Path(sampleRepo), c.want...); !slices.Equal(got, all) {
+ t.Fatalf("objects in the pack %v, want the commits' trees exactly %v", got, all)
+ }
+ })
+ }
+}
+
+// Before git runs, a header naming something other than full SHAs, a
+// repository that is not a hub repository or an invalid kind is refused;
+// after the fetch, a commit the clone does not have is refused.
+func TestPackCommitsRefuses(t *testing.T) {
+ r, c0, c1, c2 := packRig(t)
+ ctx := context.Background()
+ eng := wire.TransferHeader{ID: "tr_e", Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: c1}
+ before := map[string]wire.TransferHeader{}
+ h := eng
+ h.Repo = "github.com/someone/else"
+ before["not a hub repository"] = h
+ h = eng
+ h.BaseSHA = "main"
+ before["a ref, not a SHA"] = h
+ h = eng
+ h.BaseSHA = strings.ToUpper(c1)
+ before["not lowercase"] = h
+ h = eng
+ h.OldBaseSHA = c0
+ before["old base without candidate"] = h
+ h = eng
+ h.Direction = wire.TransferOutbound
+ before["outbound engineering"] = h
+ h = eng
+ h.Kind = "everything"
+ before["unknown kind"] = h
+ h = wire.TransferHeader{ID: "tr_c", Direction: wire.TransferInbound, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, CandidateSHA: "HEAD"}
+ before["checks candidate not a SHA"] = h
+ git := r.e.O.Runner.GitPath
+ r.e.O.Runner.GitPath, r.e.Clones.Git = "/nonexistent/git", "/nonexistent/git"
+ for name, h := range before {
+ if _, err := r.e.packCommits(ctx, h); !errors.Is(err, errPackRefused) {
+ t.Errorf("%s: %v, want refused before git runs", name, err)
+ }
+ }
+ r.e.O.Runner.GitPath, r.e.Clones.Git = git, git
+ missing := eng
+ missing.OldBaseSHA, missing.CandidateSHA = c0, strings.Repeat("e", 40)
+ if _, err := r.e.packCommits(ctx, missing); !errors.Is(err, errPackRefused) {
+ t.Fatalf("a commit the clone does not have: %v", err)
+ }
+ ok := eng
+ ok.OldBaseSHA, ok.CandidateSHA = c0, c2
+ if _, err := r.e.packCommits(ctx, ok); err != nil {
+ t.Fatalf("the rebase round's pack: %v", err)
+ }
+}
+
+// changeDiffs are the change_diff uploads in the outbox, in order.
+func (r *relayRig) changeDiffs(t *testing.T) (ups []wire.ChangeDiffUpload, raw []string) {
+ t.Helper()
+ frames, _, err := r.e.O.State.Unacked(context.Background(), 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range frames {
+ if f.Type == wire.FrameChangeDiff {
+ var v wire.ChangeDiffUpload
+ if err := json.Unmarshal(f.Data, &v); err != nil {
+ t.Fatal(err)
+ }
+ ups = append(ups, v)
+ raw = append(raw, string(f.Data))
+ }
+ }
+ return ups, raw
+}
+
+// After the push, the primary measures the worker's candidate on the
+// base and queues its diffs, each naming the publication and the
+// worker's task, step and attempt, before the published report that
+// carries the files, the collection and the outcome the publish command
+// named. The runner's bearer token never reaches a diff.
+func TestPublishWorkerChangeFilesAndDiffs(t *testing.T) {
+ const token = "eqr_t0p_s3cret_bearer_token_for_this_runner_1234"
+ ctx := context.Background()
+ publish := func(r *relayRig, id string) {
+ t.Helper()
+ h := r.header()
+ if err := r.e.O.State.AcceptPublish(ctx, "pub-"+id, wire.PublishCommand{Publication: id, TaskID: h.TaskID, StepID: h.StepID, Attempt: h.Attempt, Repo: h.Repo, Branch: relayBranch, Person: "p@x", BaseSHA: r.base, CandidateSHA: r.commit, Transfer: h.ID, OutcomePhase: wire.OutcomeUnfinished}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ rig := func(t *testing.T) *relayRig {
+ r := newRelayRigWith(t, map[string]string{"Config.txt": "server = example.com\nbearer = " + token + "\n", "Notes.md": "plain words\n"})
+ r.e.DiffSecrets = []string{token}
+ r.e.O.Protocol = func() int { return wire.ProtocolMacEngineering }
+ r.receive(t, r.pack, r.header())
+ return r
+ }
+
+ t.Run("pushed", func(t *testing.T) {
+ r := rig(t)
+ publish(r, "pb_1")
+ r.relay.Once(ctx)
+ reps := r.reports(t)
+ if len(reps) != 1 || !reps[0].Pushed || reps[0].OutcomePhase != wire.OutcomeUnfinished {
+ t.Fatalf("published %+v", reps)
+ }
+ f := reps[0].ChangeFiles
+ if f == nil || f.Base != r.base || f.SHA != r.commit || f.Files != 3 || !wire.ValidChangeFiles(f) {
+ t.Fatalf("change files %+v", f)
+ }
+ ups, raw := r.changeDiffs(t)
+ if len(ups) != 3 {
+ t.Fatalf("%d diffs", len(ups))
+ }
+ files := make([]wire.FileDiff, len(ups))
+ for i, u := range ups {
+ if u.Publication != "pb_1" || u.TaskID != "tk1" || u.StepID != "s1" || u.Attempt != 1 || u.Base != r.base || u.Candidate != r.commit || u.Index != i || u.Total != 3 {
+ t.Fatalf("diff %d not bound to the publication: %+v", i, u)
+ }
+ patch, _ := base64.StdEncoding.DecodeString(u.Data)
+ files[i] = wire.FileDiff{Path: u.Path, Patch: string(patch), Reason: u.Reason, Truncated: u.Truncated}
+ if strings.Contains(string(patch), token) || strings.Contains(raw[i], token) || strings.Contains(raw[i], base64.StdEncoding.EncodeToString([]byte(token))) {
+ t.Fatalf("the bearer token in diff %d: %s", i, raw[i])
+ }
+ switch u.Path {
+ case "Config.txt":
+ if u.Reason == "" || u.Size != 0 {
+ t.Fatalf("the secret-bearing file was shown: %+v", u)
+ }
+ case "Swipe.swift":
+ if !strings.Contains(string(patch), "+let back = true") {
+ t.Fatalf("swipe diff %q", patch)
+ }
+ }
+ }
+ if reps[0].DiffCollection == "" || reps[0].DiffCollection != wire.DiffCollection(files) {
+ t.Fatalf("collection %q", reps[0].DiffCollection)
+ }
+ // The diffs go before the report that names them.
+ frames, _, _ := r.e.O.State.Unacked(ctx, 0)
+ if last := frames[len(frames)-1]; last.Type != wire.FramePublished {
+ t.Fatalf("last frame %s", last.Type)
+ }
+ for _, fr := range frames {
+ if strings.Contains(string(fr.Data), token) {
+ t.Fatalf("the bearer token in %s", fr.Type)
+ }
+ }
+ })
+
+ t.Run("push failed", func(t *testing.T) {
+ r := rig(t)
+ publish(r, "pb_1")
+ if err := r.e.Clones.Ensure(ctx, sampleRepo); err != nil {
+ t.Fatal(err)
+ }
+ r.f.fail = 10
+ r.relay.Once(ctx)
+ reps := r.reports(t)
+ if len(reps) != 1 || reps[0].Pushed || reps[0].ChangeFiles != nil || reps[0].DiffCollection != "" || reps[0].OutcomePhase != wire.OutcomeUnfinished {
+ t.Fatalf("failed push %+v", reps)
+ }
+ if ups, _ := r.changeDiffs(t); len(ups) != 0 {
+ t.Fatalf("%d diffs queued without a push", len(ups))
+ }
+ // Retry's publication pushes and then sends them.
+ r.f.fail = 0
+ publish(r, "pb_2")
+ r.relay.Once(ctx)
+ ups, _ := r.changeDiffs(t)
+ if reps = r.reports(t); len(reps) != 2 || !reps[1].Pushed || len(ups) != 3 || ups[0].Publication != "pb_2" || reps[1].DiffCollection == "" {
+ t.Fatalf("republished %+v, %d diffs", reps, len(ups))
+ }
+ })
+
+ t.Run("diffs unavailable", func(t *testing.T) {
+ // The forge credential cannot be read, so its secrets cannot be
+ // left out: no diffs, and still a push.
+ r := rig(t)
+ r.e.O.Runner.AmadanCredentialPath = filepath.Join(r.root, "missing-credential")
+ publish(r, "pb_1")
+ r.relay.Once(ctx)
+ reps := r.reports(t)
+ if ups, _ := r.changeDiffs(t); len(reps) != 1 || !reps[0].Pushed || reps[0].DiffCollection != "" || len(ups) != 0 || r.pushCount() != 1 {
+ t.Fatalf("diagnostic, not a push failure: %+v, %d diffs", reps, len(ups))
+ }
+ })
+
+ t.Run("older instance", func(t *testing.T) {
+ r := rig(t)
+ r.e.O.Protocol = func() int { return wire.ProtocolChangeDiffs }
+ publish(r, "pb_1")
+ r.relay.Once(ctx)
+ reps := r.reports(t)
+ if ups, _ := r.changeDiffs(t); len(reps) != 1 || !reps[0].Pushed || reps[0].ChangeFiles != nil || len(ups) != 0 {
+ t.Fatalf("below 37: %+v, %d diffs", reps, len(ups))
+ }
+ })
+}
+
+// On a worker, unfinished work sent at protocol 37 is the work done, never
+// pushed (only the primary's published report says that), with its
+// outcome; the primary's own report is unchanged.
+func TestWorkerUnfinishedReportNeverPushed(t *testing.T) {
+ e, _, r, _ := hubRig(t)
+ ctx := context.Background()
+ s := e.O.State
+ cand := strings.Repeat("2", 40)
+ r.Specialist, r.StepID = wire.SpecialistEngineering, "s9"
+ if err := s.AcceptDispatch(ctx, "d-s9", r.DispatchCommand); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.setStepPhase(ctx, r, phaseCommittedUnfinished, "", cand); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: r.TaskID, StepID: "s9", Attempt: 1, State: wire.StepDone, Reason: "step_timeout", CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}}); err != nil {
+ t.Fatal(err)
+ }
+ frames, _, err := s.Unacked(ctx, 0)
+ if err != nil || len(frames) != 1 {
+ t.Fatalf("queued %d: %v", len(frames), err)
+ }
+ read := func(f wire.Frame) *wire.StepReport {
+ body, err := f.Decode()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return body.(*wire.StepReport)
+ }
+ sent, err := s.unfinishedReport(ctx, frames[0], wire.ProtocolMacEngineering, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if v := read(sent); v.Pushed || v.State != wire.StepDone || v.CandidateSHA != cand || v.Reason != "step_timeout" || v.OutcomePhase != wire.OutcomeUnfinished {
+ t.Fatalf("a worker's unfinished work sent as %+v", v)
+ }
+ if v := read(must(s.unfinishedReport(ctx, frames[0], wire.ProtocolMacEngineering, false))); !v.Pushed || v.State != wire.StepDone || v.OutcomePhase != "" {
+ t.Fatalf("the primary's unfinished work sent as %+v", v)
+ }
+ if v := read(must(s.unfinishedReport(ctx, frames[0], wire.ProtocolChangeDiffs, true))); v.Pushed || v.State != wire.StepFailed {
+ t.Fatalf("a worker's unfinished work below 37 sent as %+v", v)
+ }
+}
+
+func must[T any](v T, err error) T {
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
diff --git a/internal/runner/thin/relay_test.go b/internal/runner/thin/relay_test.go
index a9a5d213..f2fb151c 100644
--- a/internal/runner/thin/relay_test.go
+++ b/internal/runner/thin/relay_test.go
@@ -43,11 +43,17 @@ type relayRig struct {
pack []byte
pushes string
confirm error
+ // seed is the work tree the remote was cloned from; remote the bare
+ // remote; root the rig's directory.
+ seed, remote, root string
}
const relayBranch = "equipo/tk1-swipe-back"
-func newRelayRig(t *testing.T) *relayRig {
+func newRelayRig(t *testing.T) *relayRig { return newRelayRigWith(t, nil) }
+
+// newRelayRigWith is newRelayRig whose worker commit also writes extra.
+func newRelayRigWith(t *testing.T, extra map[string]string) *relayRig {
t.Helper()
root := t.TempDir()
seed := filepath.Join(root, "seed")
@@ -63,7 +69,11 @@ func newRelayRig(t *testing.T) *relayRig {
os.WriteFile(hook, []byte("#!/bin/sh\ncat >> "+pushes+"\n"), 0755)
// The worker's commit, made elsewhere on the base.
os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = true\n"), 0644)
- gitOut(t, seed, "commit", "-q", "-am", "swipe back")
+ for name, text := range extra {
+ os.WriteFile(filepath.Join(seed, name), []byte(text), 0644)
+ }
+ gitOut(t, seed, "add", "-A")
+ gitOut(t, seed, "commit", "-q", "-m", "swipe back")
commit := gitOut(t, seed, "rev-parse", "HEAD")
list := exec.Command("git", "-C", seed, "rev-list", "--objects", "--no-walk", commit)
objects, _ := list.Output()
@@ -81,7 +91,7 @@ func newRelayRig(t *testing.T) *relayRig {
}
t.Cleanup(func() { s.Close() })
f := &pushForge{dir: remote}
- r := &relayRig{f: f, base: base, commit: commit, pack: pack, pushes: pushes}
+ r := &relayRig{f: f, base: base, commit: commit, pack: pack, pushes: pushes, seed: seed, remote: remote, root: root}
e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test"}
e.O.Runner.GitPath, e.O.Runner.WorkspaceRoot, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", filepath.Join(root, "work"), filepath.Join(root, "state"), s
e.ConfirmPublication = func(context.Context, string, int64, string) error { return r.confirm }
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go
index 99ceff3a..f3afada7 100644
--- a/internal/runner/thin/step.go
+++ b/internal/runner/thin/step.go
@@ -249,8 +249,14 @@ func (s *State) ReportStep(ctx context.Context, r stepRow, rep wire.StepReport)
// step_timeout whose attempt pushed its unfinished work (its row: done,
// step_timeout, phase committed_unfinished, the candidate) is that work,
// done with the reason step_timeout. Any other frame is unchanged.
-func (s *State) unfinishedReport(ctx context.Context, f wire.Frame, protocol int) (wire.Frame, error) {
- if f.Type != wire.FrameStep || protocol < wire.ProtocolUnfinishedWork {
+//
+// On a worker (Mac runners slice F) that work is never pushed here: only
+// the primary publishes a worker's commit, and only its published report
+// says pushed. From protocol 37 a worker sends it done, not pushed, with
+// its outcome (wire.OutcomeUnfinished), which the instance keeps for the
+// publication; below 37 it is sent as queued.
+func (s *State) unfinishedReport(ctx context.Context, f wire.Frame, protocol int, worker bool) (wire.Frame, error) {
+ if f.Type != wire.FrameStep || protocol < wire.ProtocolUnfinishedWork || worker && protocol < wire.ProtocolMacEngineering {
return f, nil
}
body, err := f.Decode()
@@ -270,6 +276,9 @@ func (s *State) unfinishedReport(ctx context.Context, f wire.Frame, protocol int
return f, err
}
rep.State, rep.Pushed, rep.CandidateSHA = wire.StepDone, true, candidate
+ if worker {
+ rep.Pushed, rep.OutcomePhase = false, wire.OutcomeUnfinished
+ }
return wire.NewFrame(f.ID, f.Type, rep)
}
diff --git a/internal/thintest/mac_publication_contract_test.go b/internal/thintest/mac_publication_contract_test.go
new file mode 100644
index 00000000..4f6ff330
--- /dev/null
+++ b/internal/thintest/mac_publication_contract_test.go
@@ -0,0 +1,432 @@
+package thintest
+
+import (
+ "encoding/base64"
+ "net/url"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Mac runners slice F, plan task 4: a worker's candidate is measured by
+// the primary when it publishes. Its change files ride in the published
+// report and its diffs are uploaded bound to that publication; the
+// instance accepts them only from that publication's primary, for the
+// worker's task, step and attempt. The worker's outcome (unfinished,
+// no-shell) is kept from its committed report through the publication,
+// and Pushed is only ever the primary's word.
+
+// swipeDiff is one file's display diff of a worker's candidate.
+var swipeDiff = wire.FileDiff{Path: "Sources/Swipe.swift", Patch: "@@ -1 +1 @@\n-let back = false\n+let back = true\n"}
+
+// committedAs runs w's Engineering attempt d to a commit whose outcome is
+// outcome, as workerCommitted does; with done, the worker's final report
+// (done, not pushed, its reason for that outcome) comes before the pack.
+func (r *runnersRig) committedAs(w *peer, d *wire.DispatchCommand, cand, outcome string, done bool) *wire.PublishCommand {
+ r.t.Helper()
+ if !w.lease(d.StepID, d.Attempt) {
+ r.t.Fatal("start refused")
+ }
+ w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, Findings: []wire.Finding{}})
+ w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, OutcomePhase: outcome, Findings: []wire.Finding{}})
+ _, body := w.expect(wire.FrameSendPack)
+ h := body.(*wire.SendPackCommand).Transfer
+ if h.Direction != wire.TransferOutbound || h.CandidateSHA != cand {
+ r.t.Fatalf("outbound header %+v", h)
+ }
+ if done {
+ w.send(wire.FrameStep, workerDone(d, cand, outcome))
+ }
+ w.send(wire.FrameBlob, chunk(h, []byte("PACK commit")))
+ r.fromPrimary(wire.FrameBlob)
+ pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
+ if pub.CandidateSHA != cand || pub.Transfer != h.ID || pub.StepID != d.StepID || pub.Attempt != d.Attempt || pub.OutcomePhase != outcome {
+ r.t.Fatalf("publish %+v, want outcome %q", pub, outcome)
+ }
+ return pub
+}
+
+// workerDone is a worker's final report for its commit: done, never
+// pushed, with the reason its outcome has on the worker.
+func workerDone(d *wire.DispatchCommand, cand, outcome string) wire.StepReport {
+ reason := ""
+ switch outcome {
+ case wire.OutcomeUnfinished:
+ reason = "step_timeout"
+ case wire.OutcomeNoShell:
+ reason = wire.ReasonShellUnavailable
+ }
+ return wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, Reason: reason, CandidateSHA: cand, Termination: true, TerminationKind: wire.TerminationProcessGroup, OutcomePhase: outcome, Findings: []wire.Finding{}}
+}
+
+// publicationDiff is the primary's upload of one display diff bound to
+// pub.
+func publicationDiff(pub *wire.PublishCommand, base string, file wire.FileDiff) wire.ChangeDiffUpload {
+ return wire.ChangeDiffUpload{TaskID: pub.TaskID, StepID: pub.StepID, Attempt: pub.Attempt, Publication: pub.Publication, Base: base, Candidate: pub.CandidateSHA, Collection: wire.DiffCollection([]wire.FileDiff{file}), Total: 1, Path: file.Path, Size: len(file.Patch), SHA256: wire.DiffDigest([]byte(file.Patch)), Data: base64.StdEncoding.EncodeToString([]byte(file.Patch))}
+}
+
+func diffFacts(base, cand string, file wire.FileDiff) *wire.ChangeFiles {
+ return &wire.ChangeFiles{Base: base, SHA: cand, Files: 1, Additions: 1, Deletions: 1, Entries: []wire.ChangedFile{{Path: file.Path, Status: wire.ChangeFileModified, Additions: 1, Deletions: 1}}}
+}
+
+// publishedWith is the primary's published report for pub with its
+// measurements of the candidate.
+func publishedWith(pub *wire.PublishCommand, base string, file wire.FileDiff) wire.PublishedReport {
+ return wire.PublishedReport{Publication: pub.Publication, TaskID: pub.TaskID, StepID: pub.StepID, Attempt: pub.Attempt, CandidateSHA: pub.CandidateSHA, Pushed: true, ChangeFiles: diffFacts(base, pub.CandidateSHA, file), DiffCollection: wire.DiffCollection([]wire.FileDiff{file}), OutcomePhase: pub.OutcomePhase}
+}
+
+// diffRows counts the stored diff rows of a step, accepted or not.
+func (r *runnersRig) diffRows(step string) int {
+ r.t.Helper()
+ var n int
+ if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_change_diffs WHERE step_id = ?", step).Scan(&n); err != nil {
+ r.t.Fatal(err)
+ }
+ return n
+}
+
+// diffOf reads a file's diff of the task's candidate as the person's
+// device does.
+func (r *runnersRig) diffOf(task, cand, path string) wire.ChangeDiff {
+ r.t.Helper()
+ var out wire.ChangeDiff
+ if err := r.client.do(r.ctx, "GET", "/api/v1/tasks/"+task+"/changes/diff?candidate_sha="+cand+"&path="+url.QueryEscape(path), nil, &out); err != nil {
+ r.t.Fatal(err)
+ }
+ return out
+}
+
+// shown: the task shows the primary's measurement of the worker's
+// candidate, and the file's diff reads as uploaded.
+func (r *runnersRig) shown(task, base, cand string, file wire.FileDiff) {
+ r.t.Helper()
+ k := r.task(task)
+ f := k.Steps[0].ChangeFiles
+ if f == nil || f.Base != base || f.SHA != cand || len(f.Entries) != 1 || f.Entries[0].Path != file.Path || !k.Steps[0].Pushed {
+ r.t.Fatalf("change files on the task %+v (step %+v)", f, k.Steps[0])
+ }
+ if out := r.diffOf(task, cand, file.Path); out.Patch != file.Patch || out.StepID != k.Steps[0].ID || out.Reason != "" {
+ r.t.Fatalf("diff %+v", out)
+ }
+}
+
+// restartMac restarts the instance (a deploy) and reconnects the primary
+// and w, returning w's new connection.
+func (r *runnersRig) restartMac(w *peer) *peer {
+ r.t.Helper()
+ pgen, wgen := r.primary.fr.Welcome.Generation, w.fr.Welcome.Generation
+ c := r.creds[w.fr]
+ r.primary.fr.Close()
+ w.fr.Close()
+ r.inst.Restart(r.t)
+ h := primaryHello(pgen)
+ h.Protocol = wire.ProtocolMacEngineering
+ h.Catalog[0].NeedsMacOS = true
+ p, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, h)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ r.t.Cleanup(p.Close)
+ r.runner, r.primary, r.held = p, &peer{t: r.t, r: r.toolRig, fr: p}, nil
+ r.primary.r = r.toolRig
+ wh := macEngineerHello(c[1], wire.EngineeringReady, wire.ProtocolMacEngineering, false)
+ wh.Generation = wgen
+ fr, err := DialRunnerHello(r.ctx, r.inst.URL, c[0], wh)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ r.t.Cleanup(fr.Close)
+ r.creds[fr] = c
+ return &peer{t: r.t, r: r.toolRig, fr: fr}
+}
+
+// The primary's diffs of a worker's candidate are accepted for its
+// publication whether the worker's final report comes before them or
+// after, and across an instance restart; they are shown once the
+// published report names their collection.
+func TestContractPublicationDiffs(t *testing.T) {
+ for _, order := range []string{"uploads before done", "done before uploads", "restart between"} {
+ t.Run(order, func(t *testing.T) {
+ r := newMacRig(t)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xd1)
+ task, d := r.macDispatch(w, "iOS diffs", base)
+ pub := r.committedAs(w, d, cand, wire.OutcomeCommitted, order == "done before uploads")
+ r.primary.send(wire.FrameChangeDiff, publicationDiff(pub, base, swipeDiff))
+ if n := r.diffRows(d.StepID); n != 1 {
+ t.Fatalf("%d diff rows from the publication's primary", n)
+ }
+ if order == "restart between" {
+ w = r.restartMac(w)
+ }
+ r.primary.send(wire.FramePublished, publishedWith(pub, base, swipeDiff))
+ if order != "done before uploads" {
+ w.send(wire.FrameStep, workerDone(d, cand, wire.OutcomeCommitted))
+ }
+ r.shown(task, base, cand, swipeDiff)
+ })
+ }
+}
+
+// Diffs that name a publication are refused from anyone but the person's
+// primary (the worker, a primary that was replaced), for another attempt,
+// for a publication that is not the step's own or that failed; a worker's
+// own diffs are never kept.
+func TestContractPublicationDiffsRefused(t *testing.T) {
+ r := newMacRig(t)
+ // Work the first primary started, so its removal waits for that proof
+ // and it stays connected, removing.
+ plain := primaryHello(0)
+ plain.Protocol = wire.ProtocolMacEngineering
+ r.primary.heartbeat(plain)
+ started := r.macTask("Linux change")
+ d0 := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand)
+ if d0.TaskID != started || !r.primary.lease(d0.StepID, d0.Attempt) {
+ t.Fatalf("plain engineering %+v", d0)
+ }
+ mac := primaryHello(0)
+ mac.Protocol = wire.ProtocolMacEngineering
+ mac.Catalog[0].NeedsMacOS = true
+ r.primary.heartbeat(mac)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xd2)
+ task, d := r.macDispatch(w, "iOS refused diffs", base)
+ pub := r.committedAs(w, d, cand, wire.OutcomeCommitted, false)
+ up := publicationDiff(pub, base, swipeDiff)
+ none := func(why string) {
+ t.Helper()
+ if n := r.diffRows(d.StepID); n != 0 {
+ t.Fatalf("%s: %d diff rows kept", why, n)
+ }
+ }
+ // The worker, naming the publication, and on its own.
+ w.send(wire.FrameChangeDiff, up)
+ none("from the worker")
+ own := up
+ own.Publication = ""
+ w.send(wire.FrameChangeDiff, own)
+ none("the worker's own diffs")
+ // The primary, for another attempt or another publication.
+ wrong := up
+ wrong.Attempt = d.Attempt + 1
+ r.primary.send(wire.FrameChangeDiff, wrong)
+ none("another attempt")
+ stale := up
+ stale.Publication = "pb_not_this_one"
+ r.primary.send(wire.FrameChangeDiff, stale)
+ none("another publication")
+ // A failed publication's, then Retry's new publication: the old one is
+ // stale, the new one is accepted.
+ w.send(wire.FrameStep, workerDone(d, cand, wire.OutcomeCommitted))
+ if !r.primary.leasePublication(d.StepID, d.Attempt, pub.Publication) {
+ t.Fatal("publication refused")
+ }
+ r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Reason: "push_failed"})
+ r.primary.send(wire.FrameChangeDiff, up)
+ none("a failed publication")
+ if _, err := r.client.RetryTask(r.ctx, task); err != nil {
+ t.Fatal(err)
+ }
+ again := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
+ r.primary.send(wire.FrameChangeDiff, up)
+ none("a stale publication")
+ // The first primary removed while it is still connected: a replacement
+ // is the person's primary now, and the old one's upload is refused.
+ old := r.primary
+ r.remove(old.fr.Welcome.RunnerID, false)
+ token := r.inst.EnrolRunner(t).Token
+ h := primaryHello(0)
+ h.Protocol, h.Label = wire.ProtocolMacEngineering, "docs-t2"
+ h.Catalog[0].NeedsMacOS = true
+ np, err := DialRunnerHello(r.ctx, r.inst.URL, token, h)
+ if err != nil || np.Welcome.Role != wire.RolePrimary {
+ t.Fatalf("replacement %+v %v", np, err)
+ }
+ t.Cleanup(np.Close)
+ old.send(wire.FrameChangeDiff, publicationDiff(again, base, swipeDiff))
+ none("a replaced primary")
+ replacement := &peer{t: t, r: r.toolRig, fr: np}
+ replacement.send(wire.FrameChangeDiff, publicationDiff(again, base, swipeDiff))
+ if n := r.diffRows(d.StepID); n != 1 {
+ t.Fatalf("the current primary's upload for the current publication: %d rows", n)
+ }
+}
+
+// The files and diffs the primary published are kept whichever of the
+// worker's done and the published report comes first, and after a
+// restart; the worker's own measurement never replaces or clears them.
+func TestContractPublishedFilesSurviveDone(t *testing.T) {
+ for _, order := range []string{"done first", "published first"} {
+ t.Run(order, func(t *testing.T) {
+ r := newMacRig(t)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xd3)
+ task, d := r.macDispatch(w, "iOS files", base)
+ pub := r.committedAs(w, d, cand, wire.OutcomeCommitted, false)
+ // The worker's own final report names other files and its own
+ // collection: neither counts.
+ done := workerDone(d, cand, wire.OutcomeCommitted)
+ bogus := wire.FileDiff{Path: "Elsewhere.swift", Patch: "@@ -1 +1 @@\n-a\n+b\n"}
+ done.ChangeFiles, done.ChangeDiffs = diffFacts(base, cand, bogus), wire.DiffCollection([]wire.FileDiff{bogus})
+ if order == "done first" {
+ w.send(wire.FrameStep, done)
+ if k := r.task(task); k.Steps[0].ChangeFiles != nil {
+ t.Fatalf("the worker's measurement was kept: %+v", k.Steps[0].ChangeFiles)
+ }
+ }
+ r.primary.send(wire.FrameChangeDiff, publicationDiff(pub, base, swipeDiff))
+ r.primary.send(wire.FramePublished, publishedWith(pub, base, swipeDiff))
+ if order == "published first" {
+ w.send(wire.FrameStep, done)
+ }
+ r.shown(task, base, cand, swipeDiff)
+ w = r.restartMac(w)
+ r.shown(task, base, cand, swipeDiff)
+ })
+ }
+}
+
+// The worker's outcome survives its publication: unfinished work is
+// step_timeout and a fix round with no shell is shell_unavailable, but
+// only once the primary has published it, and Pushed only ever comes
+// from the primary's published report, through a failed publication and
+// Retry's republish too.
+func TestContractWorkerUnfinishedThroughPublication(t *testing.T) {
+ t.Run("timeout", func(t *testing.T) {
+ r := newMacRig(t)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xe1)
+ task, d := r.macDispatch(w, "iOS timeout", base)
+ pub := r.committedAs(w, d, cand, wire.OutcomeUnfinished, false)
+ // The worker saying it pushed its unfinished work is refused.
+ pushed := workerDone(d, cand, wire.OutcomeUnfinished)
+ pushed.Pushed = true
+ w.send(wire.FrameStep, pushed)
+ w.send(wire.FrameStep, workerDone(d, cand, wire.OutcomeUnfinished))
+ if s := r.task(task).Steps[0]; s.Pushed || s.Reason == "step_timeout" || s.State != wire.StepDone {
+ t.Fatalf("before publication %+v", s)
+ }
+ r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Pushed: true, OutcomePhase: wire.OutcomeUnfinished})
+ if s := r.task(task).Steps[0]; !s.Pushed || s.Reason != "step_timeout" || s.Publication != wire.PublicationPublished {
+ t.Fatalf("after publication %+v", s)
+ }
+ })
+ t.Run("published before done", func(t *testing.T) {
+ r := newMacRig(t)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xe2)
+ task, d := r.macDispatch(w, "iOS timeout early", base)
+ pub := r.committedAs(w, d, cand, wire.OutcomeUnfinished, false)
+ r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Pushed: true, OutcomePhase: wire.OutcomeUnfinished})
+ w.send(wire.FrameStep, workerDone(d, cand, wire.OutcomeUnfinished))
+ if s := r.task(task).Steps[0]; !s.Pushed || s.Reason != "step_timeout" || s.State != wire.StepDone {
+ t.Fatalf("after both %+v", s)
+ }
+ })
+ t.Run("no shell fix round", func(t *testing.T) {
+ r := newMacRig(t)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ base, c1, c2 := sha(1), sha(0xe3), sha(0xe4)
+ task, _ := r.macCandidate(w, "iOS no shell", base, c1)
+ cw, c := r.macChecked(task, w)
+ cw.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepDone, CandidateSHA: c1, Checks: wire.ChecksFailed, Gate: "xcodebuild test", ExitCode: exit(65), Output: "FAILED", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}})
+ _, body := w.expect(wire.FrameDispatch)
+ fix := body.(*wire.DispatchCommand)
+ if fix.Specialist != wire.SpecialistEngineering || fix.Round != 1 {
+ t.Fatalf("fix round %+v", fix)
+ }
+ r.engineeringTransfer(w, fix)
+ pub := r.committedAs(w, fix, c2, wire.OutcomeNoShell, true)
+ step := func() wire.Step {
+ for _, s := range r.task(task).Steps {
+ if s.ID == fix.StepID {
+ return s
+ }
+ }
+ t.Fatal("no fix round")
+ return wire.Step{}
+ }
+ if s := step(); s.Pushed || s.Reason == wire.ReasonShellUnavailable {
+ t.Fatalf("before publication %+v", s)
+ }
+ r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: fix.StepID, Attempt: fix.Attempt, CandidateSHA: c2, Pushed: true, OutcomePhase: wire.OutcomeNoShell})
+ if s := step(); !s.Pushed || s.Reason != wire.ReasonShellUnavailable {
+ t.Fatalf("after publication %+v", s)
+ }
+ })
+ t.Run("failed publication then republish", func(t *testing.T) {
+ r := newMacRig(t)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xe5)
+ task, d := r.macDispatch(w, "iOS timeout again", base)
+ pub := r.committedAs(w, d, cand, wire.OutcomeUnfinished, true)
+ if !r.primary.leasePublication(d.StepID, d.Attempt, pub.Publication) {
+ t.Fatal("publication refused")
+ }
+ r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Reason: "push_failed", OutcomePhase: wire.OutcomeUnfinished})
+ if s := r.task(task).Steps[0]; s.Pushed || s.Reason != "push_failed" {
+ t.Fatalf("failed publication %+v", s)
+ }
+ if _, err := r.client.RetryTask(r.ctx, task); err != nil {
+ t.Fatal(err)
+ }
+ again := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
+ if again.Publication == pub.Publication || again.OutcomePhase != wire.OutcomeUnfinished {
+ t.Fatalf("republish %+v", again)
+ }
+ if s := r.task(task).Steps[0]; s.Pushed {
+ t.Fatalf("pushed before the republish %+v", s)
+ }
+ r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: again.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Pushed: true, OutcomePhase: wire.OutcomeUnfinished})
+ if s := r.task(task).Steps[0]; !s.Pushed || s.Reason != "step_timeout" {
+ t.Fatalf("republished %+v", s)
+ }
+ })
+}
+
+// A pack too large to relay (declared by its chunk count) ends a worker's
+// Engineering attempt workspace_too_large with Needs you, whether or not
+// the worker had started it; nothing reaches the worker and nothing runs
+// on Linux.
+func TestPackOversizeIsWorkspaceTooLarge(t *testing.T) {
+ for _, started := range []bool{false, true} {
+ name := "not started"
+ if started {
+ name = "started"
+ }
+ t.Run(name, func(t *testing.T) {
+ r := newMacRig(t)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ task := r.macTask("iOS huge")
+ r.based(r.prepared(task), sha(1))
+ _, body := w.expect(wire.FrameDispatch)
+ d := body.(*wire.DispatchCommand)
+ h := r.engineeringTransfer(w, d)
+ if started && !w.lease(d.StepID, d.Attempt) {
+ t.Fatal("start refused")
+ }
+ big := chunk(h, []byte("PACK huge"))
+ big.Total = wire.MaxTransferChunks + 1
+ r.primary.send(wire.FrameBlob, big)
+ if started {
+ _, body = w.expect(wire.FrameCancelStep)
+ if c := body.(*wire.CancelStepCommand); c.StepID != d.StepID || c.Attempt != d.Attempt {
+ t.Fatalf("cancel %+v", c)
+ }
+ w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepCancelled, Reason: "withdrawn", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}})
+ }
+ s := r.engineeringStep(task)
+ if s.State != wire.StepFailed || s.Reason != wire.ReasonWorkspaceTooLarge || !s.Terminated || r.needsYou(task) != wire.NeedsRetry {
+ t.Fatalf("oversize %+v needs %q", s, r.needsYou(task))
+ }
+ if n := r.relayed(w); n != 0 {
+ t.Fatalf("%d chunks reached the worker", n)
+ }
+ if n := r.mailboxHas(r.primary.fr.Welcome.RunnerID, `"specialist":"engineering"`); n != 0 {
+ t.Fatalf("%d engineering dispatches to the Linux primary", n)
+ }
+ w.none(wire.FrameDispatch, 50*time.Millisecond)
+ })
+ }
+}
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go
index c019be77..e592b335 100644
--- a/internal/wire/tasks.go
+++ b/internal/wire/tasks.go
@@ -1150,8 +1150,10 @@ var StepReasons = map[string]bool{
"transfer_refused": true,
"runner_offline": true,
// Mac Engineering (slice F): the primary could not resolve the base of
- // an attempt on a worker; nothing ran.
- ReasonBaseUnavailable: true,
+ // an attempt on a worker; nothing ran. Its commits were too large to
+ // relay to the Mac (workspace_too_large); it never runs on Linux.
+ ReasonBaseUnavailable: true,
+ ReasonWorkspaceTooLarge: true,
// machine_removed: the runner was removed while the step may have been
// running; nothing proves its end (only Recover settles it).
"machine_removed": true,