oficina / equipo Public

Mac slice F task 4 fix 1: publication's primary, file names, below 37

Astra round 1:

- A publication belongs to the primary it was given to
  (chat_steps.publication_runner, migration 0120 amended). Its diffs,
  confirmation and published report count only from that runner while
  it is the person's primary. A replacement primary's connect fails the
  old primary's pending publication so the person can Retry, and Retry
  asks the worker to send its commit again, to the new primary.
- The primary withholds the change files and diffs when a listed file
  name or a renamed file's old name holds a secret it knows; the push
  stands. The same screen covers the primary's own steps.
- A worker's outcome_phase counts only at protocol 37 or later, as the
  published report's files and a publication's diffs already did.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 7006e3def1862c9b6c824d4e918f411463d45ea4 parent d1c3e9b
16 files changed, +361 −60
  • .rastrillo/budgets.txt +3 −3
  • internal/equipo/chat/change_diffs.go +4 −3
  • internal/equipo/chat/placement_edges_test.go +1 −1
  • internal/equipo/chat/proposal_seam_test.go +1 −1
  • internal/equipo/chat/runner.go +3 −0
  • internal/equipo/chat/tasks.go +20 −3
  • internal/equipo/chat/transfers.go +37 −2
  • internal/equipo/migrations/0120_mac_engineering.sql +2 −0
  • internal/equipo/migrations/schema.sql +1 −0
  • internal/equipo/migrations_mac_engineering_test.go +1 −1
  • internal/runner/thin/change_diffs.go +47 −15
  • internal/runner/thin/change_diffs_test.go +5 −1
  • internal/runner/thin/engineer.go +3 −2
  • internal/runner/thin/relay_engineering_test.go +46 −0
  • internal/runner/thin/relay_test.go +12 −0
  • internal/thintest/mac_publication_contract_test.go +175 −28
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 4c98ca5d..741f808b 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -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 30669 26513 Protocol 31 facts, 35 diffs, merge credential, publication guards, kept work, CI units, places publish, token scans, Mac pin, paths, bases, endpoint; measured 30669/26513.
+size internal/runner/thin 30702 26575 Protocol 31 facts, 35 diffs, merge credential, publication guards, kept work, CI units, places publish, token scans, Mac pin, paths, bases, endpoint; measured 30702/26575.
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 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.
+size internal/equipo/chat 38860 12096 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places, waiting cards, Mac waits, Mac Engineering; measured 38860/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 - 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.
+size internal/thintest - 38962 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 38962.
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/internal/equipo/chat/change_diffs.go b/internal/equipo/chat/change_diffs.go
index a45657a3..e0ce1c9b 100644
--- a/internal/equipo/chat/change_diffs.go
+++ b/internal/equipo/chat/change_diffs.go
@@ -131,8 +131,9 @@ func (t *txn) changeDiff(l Lease, v *wire.ChangeDiffUpload) 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,
+// a worker's Engineering attempt (protocol 37). Only the primary the
+// publication was given to, while it is the person's primary, 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) {
@@ -143,7 +144,7 @@ func (t *txn) publicationUploader(l Lease, step stepRecord, publication string)
if err != nil {
return false, err
}
- if primary == "" || primary != l.Runner.RunnerID || step.RunnerID == primary {
+ if primary == "" || primary != l.Runner.RunnerID || step.PublicationRunner != primary || step.RunnerID == primary {
return false, nil
}
if step.PublicationID != publication || step.Publication != wire.PublicationPending && step.Publication != wire.PublicationPublished {
diff --git a/internal/equipo/chat/placement_edges_test.go b/internal/equipo/chat/placement_edges_test.go
index 27ed13e2..038e2adc 100644
--- a/internal/equipo/chat/placement_edges_test.go
+++ b/internal/equipo/chat/placement_edges_test.go
@@ -256,7 +256,7 @@ func TestPlacementAbandonPendingPublicationHistory(t *testing.T) {
st.Terminated = true
st.CandidateSHA = strings.Repeat("a", 40)
st.Publication = wire.PublicationPending
- st.PublicationID = "pub_edge"
+ st.PublicationID, st.PublicationRunner = "pub_edge", "RUNNER1"
r := abandonedPlacement(t, st)
if v := placementEdgeView(t, r); wire.FinalStage(v.Stage) {
t.Fatal("unsettled publication appeared final")
diff --git a/internal/equipo/chat/proposal_seam_test.go b/internal/equipo/chat/proposal_seam_test.go
index 80557520..3728b069 100644
--- a/internal/equipo/chat/proposal_seam_test.go
+++ b/internal/equipo/chat/proposal_seam_test.go
@@ -20,7 +20,7 @@ func TestProposalFailureKeepsSuccessfulPublication(t *testing.T) {
st.State = wire.StepDone
st.Terminated = true
st.Publication = wire.PublicationPending
- st.PublicationID = "pub_proposal"
+ st.PublicationID, st.PublicationRunner = "pub_proposal", "RUNNER1"
}
if err := r.s.db.G.Create(&st).Error; err != nil {
t.Fatal(err)
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index bf19bd48..c29090fc 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -88,6 +88,9 @@ func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string,
if err := t.reprepareBases(p.Person, p.RunnerID, lease.Protocol); err != nil {
return err
}
+ if err := t.reassignPublications(p.Person, p.RunnerID); err != nil {
+ return err
+ }
}
// The Assistant: nor its turns, below protocol 19.
if err := t.fenceLanes(lease); err != nil {
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index e7ee0644..7fe0e112 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -216,6 +216,9 @@ type stepRecord struct {
// Publication of a worker's Engineering candidate by the primary.
Publication string
PublicationID string
+ // PublicationRunner is the primary the publication was given to: only
+ // it may answer it (Mac runners slice F).
+ PublicationRunner string
// Apple: Engineering's change touched Apple files (its checks need
// macOS).
Apple bool
@@ -809,7 +812,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", "outcome_phase").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", "publication_runner").Updates(s).Error; err != nil {
return err
}
if s.Retired {
@@ -1566,7 +1569,7 @@ 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 {
+ if role != wire.RolePrimary && s.Specialist == wire.SpecialistEngineering && !s.Republish && l.Protocol >= wire.ProtocolMacEngineering {
// 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)
@@ -2183,7 +2186,21 @@ func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool)
return 0, ErrNotRetryable
}
st.Reason = ""
- if err := t.publish(k, &st, tr); err != nil {
+ primary, err := t.s.authority.PrimaryRunner(t.db, st.Person)
+ if err != nil {
+ return 0, err
+ }
+ if primary != "" && tr.ToRunner != primary {
+ // The commit went to a primary that has been replaced: the
+ // worker sends it again, to this one, which then publishes it.
+ st.Publication = ""
+ if err := t.saveStep(&st, k); err != nil {
+ return 0, err
+ }
+ if _, err := t.openTransfer(*k, st, st.RunnerID, primary, wire.TransferHeader{Direction: wire.TransferOutbound, BaseSHA: st.BaseSHA, CandidateSHA: st.CandidateSHA}); err != nil {
+ return 0, err
+ }
+ } else if err := t.publish(k, &st, tr); err != nil {
return 0, err
}
k.Stage = wire.StageInProgress
diff --git a/internal/equipo/chat/transfers.go b/internal/equipo/chat/transfers.go
index 26f3ca70..d90a6f33 100644
--- a/internal/equipo/chat/transfers.go
+++ b/internal/equipo/chat/transfers.go
@@ -250,7 +250,7 @@ func (t *txn) publish(k *taskRecord, s *stepRecord, tr transferRecord) error {
if err != nil || primary == "" {
return err
}
- s.Publication, s.PublicationID = wire.PublicationPending, newID("pb_")
+ s.Publication, s.PublicationID, s.PublicationRunner = wire.PublicationPending, newID("pb_"), primary
if err := t.saveStep(s, k); err != nil {
return err
}
@@ -308,6 +308,9 @@ func (t *txn) published(l Lease, v *wire.PublishedReport) error {
if s.Attempt != v.Attempt || s.PublicationID != v.Publication || s.Publication != wire.PublicationPending || s.CandidateSHA != v.CandidateSHA {
return nil
}
+ if s.PublicationRunner != l.Runner.RunnerID {
+ return fmt.Errorf("%w: published from a primary the publication was not given to", ErrRefused)
+ }
k, err := t.loadTask(s.TaskID)
if err != nil {
return err
@@ -386,7 +389,7 @@ func (t *txn) authorizePublication(l Lease, stepID string, attempt int64, public
if err != nil {
return "", err
}
- if primary != l.Runner.RunnerID || s.Attempt != attempt || s.PublicationID != publication || s.Publication != wire.PublicationPending || k.CancelRequested || wire.FinalStage(k.Stage) {
+ if primary != l.Runner.RunnerID || s.PublicationRunner != l.Runner.RunnerID || s.Attempt != attempt || s.PublicationID != publication || s.Publication != wire.PublicationPending || k.CancelRequested || wire.FinalStage(k.Stage) {
return "cancelled", nil
}
return "", nil
@@ -407,3 +410,35 @@ func (t *txn) candidateCommitted(k taskRecord, s stepRecord) error {
_, err = t.openTransfer(k, s, s.RunnerID, primary, wire.TransferHeader{Direction: wire.TransferOutbound, BaseSHA: s.BaseSHA, CandidateSHA: s.CandidateSHA})
return err
}
+
+// reassignPublications runs when the person's primary connects: a
+// pending publication given to another runner (a primary since replaced)
+// can no longer be answered by anyone, so it fails as an unpushed commit
+// and the person's Retry has the worker send its commit to this primary.
+func (t *txn) reassignPublications(person, primary string) error {
+ if current, err := t.s.authority.PrimaryRunner(t.db, person); err != nil || current != primary {
+ return err
+ }
+ var rows []stepRecord
+ if err := t.db.Where("person = ? AND publication = ? AND coalesce(publication_runner, '') <> ?", person, wire.PublicationPending, primary).Find(&rows).Error; err != nil {
+ return err
+ }
+ for i := range rows {
+ s := rows[i]
+ k, err := t.loadTask(s.TaskID)
+ if err != nil {
+ return err
+ }
+ if s.Retired || wire.FinalStage(k.Stage) || k.MoveProject != "" {
+ continue
+ }
+ s.Publication, s.Reason = wire.PublicationFailed, "push_failed"
+ if err := t.saveStep(&s, &k); err != nil {
+ return err
+ }
+ if err := t.advance(&k); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/migrations/0120_mac_engineering.sql b/internal/equipo/migrations/0120_mac_engineering.sql
index 7e851dc7..d09d75df 100644
--- a/internal/equipo/migrations/0120_mac_engineering.sql
+++ b/internal/equipo/migrations/0120_mac_engineering.sql
@@ -6,6 +6,8 @@ ALTER TABLE runner_transfers ADD COLUMN old_base_sha text;
ALTER TABLE chat_steps ADD COLUMN xcode_access text;
ALTER TABLE chat_steps ADD COLUMN outcome_phase text;
ALTER TABLE chat_steps ADD COLUMN session_id text;
+-- The primary a worker's publication was given to: only it may answer it.
+ALTER TABLE chat_steps ADD COLUMN publication_runner text;
ALTER TABLE chat_questions ADD COLUMN eng_attempt integer;
ALTER TABLE chat_questions ADD COLUMN eng_account text;
ALTER TABLE chat_questions ADD COLUMN eng_session text;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 46877f94..7fa79b50 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -847,6 +847,7 @@ ALTER TABLE runner_transfers ADD COLUMN old_base_sha text;
ALTER TABLE chat_steps ADD COLUMN xcode_access text;
ALTER TABLE chat_steps ADD COLUMN outcome_phase text;
ALTER TABLE chat_steps ADD COLUMN session_id text;
+ALTER TABLE chat_steps ADD COLUMN publication_runner text;
ALTER TABLE chat_questions ADD COLUMN eng_attempt integer;
ALTER TABLE chat_questions ADD COLUMN eng_account text;
ALTER TABLE chat_questions ADD COLUMN eng_session text;
diff --git a/internal/equipo/migrations_mac_engineering_test.go b/internal/equipo/migrations_mac_engineering_test.go
index 4daf3fff..70bbfd27 100644
--- a/internal/equipo/migrations_mac_engineering_test.go
+++ b/internal/equipo/migrations_mac_engineering_test.go
@@ -128,7 +128,7 @@ func TestMacEngineeringMigrationKeepsOpenTransfersAndQuestions(t *testing.T) {
}
added := map[string][]string{
"runner_transfers": {"kind", "old_base_sha"},
- "chat_steps": {"xcode_access", "outcome_phase", "session_id"},
+ "chat_steps": {"xcode_access", "outcome_phase", "session_id", "publication_runner"},
"chat_questions": {"eng_attempt", "eng_account", "eng_session", "runner_id", "base_sha", "candidate_sha"},
"chat_tasks": {"mac_needs"},
}
diff --git a/internal/runner/thin/change_diffs.go b/internal/runner/thin/change_diffs.go
index 4db48f3c..d62cc533 100644
--- a/internal/runner/thin/change_diffs.go
+++ b/internal/runner/thin/change_diffs.go
@@ -158,12 +158,14 @@ func clipDisplayPatch(s string) (string, bool) {
return s[:end], end < len(s)
}
-func (e *Engineer) queueChangeDiffs(ctx context.Context, r stepRow, git, dir string, f *wire.ChangeFiles) string {
- if e.O.State == nil || e.O.Protocol == nil || e.O.Protocol() < wire.ProtocolChangeDiffs || !e.diffCollect.TryLock() {
+// queueChangeDiffs queues the display diffs of f, already screened
+// (screenChangeFiles) against known.
+func (e *Engineer) queueChangeDiffs(ctx context.Context, r stepRow, git, dir string, f *wire.ChangeFiles, known []string) string {
+ if f == nil || e.O.State == nil || e.O.Protocol == nil || e.O.Protocol() < wire.ProtocolChangeDiffs || !e.diffCollect.TryLock() {
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)
+ ups, collection := changeDiffUploads(ctx, wire.ChangeDiffUpload{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt}, git, dir, f, known)
if len(ups) == 0 {
return ""
}
@@ -181,23 +183,53 @@ func (e *Engineer) queueChangeDiffs(ctx context.Context, r stepRow, git, dir str
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)
+// knownSecrets are the secrets this runner knows that must never reach a
+// display measurement: its diff secrets (the runner's bearer token) and
+// the forge credential it already uses for repo. ok is false when the
+// credential cannot be read.
+func (e *Engineer) knownSecrets(ctx context.Context, repo string) (known []string, ok bool) {
+ 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, repo)
if err != nil {
- return nil, ""
+ return nil, false
}
known = append(known, credential.Bearer, credential.GitPassword)
}
+ return known, true
+}
+
+// screenChangeFiles is f as it may leave this runner, with the known
+// secrets it was screened against: nil when they cannot be read, or when
+// a listed file name or a renamed file's old name holds one of them or
+// anything else a diff would withhold (a file name can be the secret,
+// and it travels in the change files and in every diff upload).
+func (e *Engineer) screenChangeFiles(ctx context.Context, repo string, f *wire.ChangeFiles) (*wire.ChangeFiles, []string) {
+ if f == nil {
+ return nil, nil
+ }
+ known, ok := e.knownSecrets(ctx, repo)
+ if !ok {
+ return nil, nil
+ }
+ for _, entry := range f.Entries {
+ for _, name := range []string{entry.Path, entry.OldPath} {
+ if name != "" && diffscan.Check(ctx, name, known) != "" {
+ e.log("change files", errors.New("a file name is withheld, so the measurement is"))
+ return nil, nil
+ }
+ }
+ }
+ return f, known
+}
+
+// changeDiffUploads is the display collection of f as uploads naming
+// at's task, step, attempt and (for a worker's candidate) publication,
+// with the known secrets left out. Nothing when a frame would be too
+// large.
+func changeDiffUploads(ctx context.Context, at wire.ChangeDiffUpload, git, dir string, f *wire.ChangeFiles, known []string) ([]wire.ChangeDiffUpload, string) {
files := collectChangeDiffs(ctx, git, dir, f, known)
if len(files) == 0 {
return nil, ""
@@ -224,14 +256,14 @@ func (e *Engineer) publicationDiffs(ctx context.Context, p pubRow, dir string) (
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)
+ files, known := e.screenChangeFiles(ctx, p.Repo, 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"))
+ e.log("publication change files", errors.New("the candidate could not be measured on its base, or not safely"))
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)
+ ups, collection := changeDiffUploads(ctx, wire.ChangeDiffUpload{TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, Publication: p.Publication}, e.O.Runner.GitPath, dir, files, known)
if len(ups) == 0 {
e.log("publication change diffs", errors.New("no diffs for the candidate"))
}
diff --git a/internal/runner/thin/change_diffs_test.go b/internal/runner/thin/change_diffs_test.go
index 62651e85..5a273461 100644
--- a/internal/runner/thin/change_diffs_test.go
+++ b/internal/runner/thin/change_diffs_test.go
@@ -206,7 +206,11 @@ func TestQueueDiffWithholdsOwnForgeCredentials(t *testing.T) {
}
engineer := Engineer{O: ClaudeOptions{State: state, Protocol: func() int { return wire.ProtocolCurrent }}}
engineer.O.Runner.AmadanCredentialPath = credential
- if engineer.queueChangeDiffs(context.Background(), stepRow{DispatchCommand: wire.DispatchCommand{TaskID: "tk", StepID: "s", Attempt: 1, Repo: "amadan.net/ns/repo"}}, "/usr/bin/git", filepath.Join(dir, ".git"), facts) == "" {
+ facts, known := engineer.screenChangeFiles(context.Background(), "amadan.net/ns/repo", facts)
+ if facts == nil {
+ t.Fatal("the measurement was withheld")
+ }
+ if engineer.queueChangeDiffs(context.Background(), stepRow{DispatchCommand: wire.DispatchCommand{TaskID: "tk", StepID: "s", Attempt: 1, Repo: "amadan.net/ns/repo"}}, "/usr/bin/git", filepath.Join(dir, ".git"), facts, known) == "" {
t.Fatal("no collection")
}
frames, _, err := state.Unacked(context.Background(), 0)
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go
index aa77f87b..1d34d6e8 100644
--- a/internal/runner/thin/engineer.go
+++ b/internal/runner/thin/engineer.go
@@ -487,8 +487,9 @@ func (e *Engineer) publish(ctx context.Context, r stepRow, rep wire.StepReport)
}
}
if r.Specialist == wire.SpecialistEngineering {
- rep.ChangeFiles = changeFiles(ctx, tree.Git, tree.GitDir, r.Base, r.Candidate)
- rep.ChangeDiffs = e.queueChangeDiffs(ctx, r, tree.Git, tree.GitDir, rep.ChangeFiles)
+ var known []string
+ rep.ChangeFiles, known = e.screenChangeFiles(ctx, r.Repo, changeFiles(ctx, tree.Git, tree.GitDir, r.Base, r.Candidate))
+ rep.ChangeDiffs = e.queueChangeDiffs(ctx, r, tree.Git, tree.GitDir, rep.ChangeFiles, known)
}
expectedHead := ""
if r.Specialist == wire.SpecialistCopy {
diff --git a/internal/runner/thin/relay_engineering_test.go b/internal/runner/thin/relay_engineering_test.go
index f55c38d0..356394d7 100644
--- a/internal/runner/thin/relay_engineering_test.go
+++ b/internal/runner/thin/relay_engineering_test.go
@@ -460,6 +460,52 @@ func TestPublishWorkerChangeFilesAndDiffs(t *testing.T) {
})
}
+// A file name, or a renamed file's old name, holding a secret this
+// primary knows (its bearer token) would reach the instance in the
+// change files and in every diff upload, whatever the worker scanned
+// (the worker does not know the primary's secrets). Such a measurement
+// is withheld: no files, no diffs, and the push stands.
+func TestPublishWorkerSecretInFileName(t *testing.T) {
+ const token = "correcthorsebatterystaplerunnerbearer"
+ ctx := context.Background()
+ for _, c := range []struct {
+ name string
+ before, extra map[string]string
+ moves [][2]string
+ }{
+ {name: "file name", extra: map[string]string{"keys-" + token + ".txt": "nothing secret inside\n"}},
+ {name: "renamed from", before: map[string]string{"notes-" + token + ".md": "the same words\nin both names\n"}, moves: [][2]string{{"notes-" + token + ".md", "notes.md"}}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := newRelayRigFiles(t, c.before, c.extra, c.moves)
+ r.e.DiffSecrets = []string{token}
+ r.e.O.Protocol = func() int { return wire.ProtocolMacEngineering }
+ r.receive(t, r.pack, r.header())
+ h := r.header()
+ if err := r.e.O.State.AcceptPublish(ctx, "pub-1", wire.PublishCommand{Publication: "pb_1", 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}); err != nil {
+ t.Fatal(err)
+ }
+ r.relay.Once(ctx)
+ reps := r.reports(t)
+ if len(reps) != 1 || !reps[0].Pushed || reps[0].ChangeFiles != nil || reps[0].DiffCollection != "" {
+ t.Fatalf("published %+v", reps)
+ }
+ if ups, _ := r.changeDiffs(t); len(ups) != 0 {
+ t.Fatalf("%d diffs sent", len(ups))
+ }
+ frames, _, err := r.e.O.State.Unacked(ctx, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range frames {
+ if strings.Contains(string(f.Data), token) || strings.Contains(string(f.Data), base64.StdEncoding.EncodeToString([]byte(token))) {
+ t.Fatalf("the bearer token in %s: %s", f.Type, f.Data)
+ }
+ }
+ })
+ }
+}
+
// 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.
diff --git a/internal/runner/thin/relay_test.go b/internal/runner/thin/relay_test.go
index f2fb151c..4cbaea8c 100644
--- a/internal/runner/thin/relay_test.go
+++ b/internal/runner/thin/relay_test.go
@@ -54,11 +54,20 @@ 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 {
+ return newRelayRigFiles(t, nil, extra, nil)
+}
+
+// newRelayRigFiles is newRelayRig whose base also has the files before,
+// and whose worker commit also writes extra and moves files (git mv).
+func newRelayRigFiles(t *testing.T, before, extra map[string]string, moves [][2]string) *relayRig {
t.Helper()
root := t.TempDir()
seed := filepath.Join(root, "seed")
gitOut(t, root, "init", "-q", "-b", "main", seed)
os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = false\n"), 0644)
+ for name, text := range before {
+ os.WriteFile(filepath.Join(seed, name), []byte(text), 0644)
+ }
gitOut(t, seed, "add", "-A")
gitOut(t, seed, "commit", "-q", "-m", "base")
base := gitOut(t, seed, "rev-parse", "HEAD")
@@ -72,6 +81,9 @@ func newRelayRigWith(t *testing.T, extra map[string]string) *relayRig {
for name, text := range extra {
os.WriteFile(filepath.Join(seed, name), []byte(text), 0644)
}
+ for _, m := range moves {
+ gitOut(t, seed, "mv", m[0], m[1])
+ }
gitOut(t, seed, "add", "-A")
gitOut(t, seed, "commit", "-q", "-m", "swipe back")
commit := gitOut(t, seed, "rev-parse", "HEAD")
diff --git a/internal/thintest/mac_publication_contract_test.go b/internal/thintest/mac_publication_contract_test.go
index 4f6ff330..b787a996 100644
--- a/internal/thintest/mac_publication_contract_test.go
+++ b/internal/thintest/mac_publication_contract_test.go
@@ -169,26 +169,12 @@ func TestContractPublicationDiffs(t *testing.T) {
}
}
-// 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.
+// Diffs that name a publication are refused from anyone but that
+// publication's primary (here the worker), for another attempt, for a
+// publication that is not the step's own or that failed; a worker's own
+// diffs are never kept. Retry's new publication is accepted.
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)
@@ -231,10 +217,54 @@ func TestContractPublicationDiffsRefused(t *testing.T) {
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)
+ r.primary.send(wire.FrameChangeDiff, publicationDiff(again, base, swipeDiff))
+ if n := r.diffRows(d.StepID); n != 1 {
+ t.Fatalf("the publication's primary, for the current publication: %d rows", n)
+ }
+}
+
+// diffRowsBy counts a step's stored diff rows uploaded by runner.
+func (r *runnersRig) diffRowsBy(step, runner string) int {
+ r.t.Helper()
+ var n int
+ if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_change_diffs WHERE step_id = ? AND runner_id = ?", step, runner).Scan(&n); err != nil {
+ r.t.Fatal(err)
+ }
+ return n
+}
+
+// A publication belongs to the primary it was given to. Replaced by
+// primary B (A removed while still connected), A's pending publication
+// fails, so the person can Retry; nothing B sends for A's publication
+// counts (diffs, its confirmation before the push, its published
+// report), and neither does anything A sends. Retry asks the worker for
+// its commit again, for B, and B's new publication is B's own.
+func TestContractPublicationBoundToItsPrimary(t *testing.T) {
+ r := newMacRig(t)
+ // Work A 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(0xd5)
+ task, d := r.macDispatch(w, "iOS replaced primary", base)
+ pub := r.committedAs(w, d, cand, wire.OutcomeCommitted, true)
+ a := r.primary
+ a.send(wire.FrameChangeDiff, publicationDiff(pub, base, swipeDiff))
+ if n := r.diffRowsBy(d.StepID, a.fr.Welcome.RunnerID); n != 1 {
+ t.Fatalf("A's upload for its own publication: %d rows", n)
+ }
+ r.remove(a.fr.Welcome.RunnerID, false)
token := r.inst.EnrolRunner(t).Token
h := primaryHello(0)
h.Protocol, h.Label = wire.ProtocolMacEngineering, "docs-t2"
@@ -244,12 +274,129 @@ func TestContractPublicationDiffsRefused(t *testing.T) {
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)
+ b := &peer{t: t, r: r.toolRig, fr: np}
+ bID := np.Welcome.RunnerID
+ if s := r.task(task).Steps[0]; s.Publication != wire.PublicationFailed || s.Pushed || r.needsYou(task) != wire.NeedsRetry {
+ t.Fatalf("A's publication after B took over: %+v needs %q", s, r.needsYou(task))
+ }
+ // Each guard on its own: A's publication as if it were still pending.
+ if _, err := r.inst.DB.Writer().Exec("UPDATE chat_steps SET publication = ? WHERE id = ?", wire.PublicationPending, d.StepID); err != nil {
+ t.Fatal(err)
+ }
+ b.send(wire.FrameChangeDiff, publicationDiff(pub, base, swipeDiff))
+ if n := r.diffRowsBy(d.StepID, bID); n != 0 {
+ t.Fatalf("B's upload for A's publication: %d rows", n)
+ }
+ if b.leasePublication(d.StepID, d.Attempt, pub.Publication) {
+ t.Fatal("B confirmed A's publication")
+ }
+ b.send(wire.FramePublished, publishedWith(pub, base, swipeDiff))
+ if s := r.task(task).Steps[0]; s.Pushed || s.Publication != wire.PublicationPending || s.ChangeFiles != nil {
+ t.Fatalf("B's published report for A's publication counted: %+v", s)
+ }
+ a.send(wire.FrameChangeDiff, publicationDiff(pub, base, swipeDiff))
+ if a.leasePublication(d.StepID, d.Attempt, pub.Publication) {
+ t.Fatal("the replaced primary confirmed its publication")
+ }
+ if _, err := r.inst.DB.Writer().Exec("UPDATE chat_steps SET publication = ? WHERE id = ?", wire.PublicationFailed, d.StepID); err != nil {
+ t.Fatal(err)
+ }
+ // Retry: the worker uploads its commit again, to B, and B publishes.
+ if _, err := r.client.RetryTask(r.ctx, task); err != nil {
+ t.Fatal(err)
+ }
+ _, body := w.expect(wire.FrameSendPack)
+ tr := body.(*wire.SendPackCommand).Transfer
+ if tr.Direction != wire.TransferOutbound || tr.CandidateSHA != cand || tr.BaseSHA != base || tr.Attempt != d.Attempt {
+ t.Fatalf("outbound again %+v", tr)
+ }
+ w.send(wire.FrameBlob, chunk(tr, []byte("PACK commit")))
+ b.expect(wire.FrameBlob)
+ _, body = b.expect(wire.FramePublish)
+ again := body.(*wire.PublishCommand)
+ if again.Publication == pub.Publication || again.Transfer != tr.ID || again.CandidateSHA != cand {
+ t.Fatalf("B's publication %+v", again)
+ }
+ b.send(wire.FrameChangeDiff, publicationDiff(again, base, swipeDiff))
+ if n, m := r.diffRowsBy(d.StepID, bID), r.diffRowsBy(d.StepID, a.fr.Welcome.RunnerID); n != 1 || m != 0 {
+ t.Fatalf("after B's publication: B %d rows, A %d", n, m)
+ }
+ if !b.leasePublication(d.StepID, d.Attempt, again.Publication) {
+ t.Fatal("B's own publication refused")
+ }
+ b.send(wire.FramePublished, publishedWith(again, base, swipeDiff))
+ r.shown(task, base, cand, swipeDiff)
+}
+
+// Slice F fields read from a runner count only at protocol 37: a worker
+// that reconnected below it cannot set the outcome, and a primary below
+// it cannot set change files, a diff collection or a publication's diffs.
+func TestContractSliceFFieldsBelow37(t *testing.T) {
+ for _, protocol := range []int{36, wire.ProtocolMacEngineering} {
+ t.Run(itoa(protocol), func(t *testing.T) {
+ r := newMacRig(t)
+ w := r.newMacEngineer("Mac A", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xf1)
+ task, d := r.macDispatch(w, "iOS fields", base)
+ if !w.lease(d.StepID, d.Attempt) {
+ t.Fatal("start refused")
+ }
+ // The worker comes back at protocol.
+ c := r.creds[w.fr]
+ wh := macEngineerHello(c[1], wire.EngineeringReady, protocol, false)
+ wh.Generation = w.fr.Welcome.Generation
+ w.fr.Close()
+ fr, err := DialRunnerHello(r.ctx, r.inst.URL, c[0], wh)
+ if err != nil || fr.Welcome.Protocol != protocol {
+ t.Fatalf("worker at %d: %+v %v", protocol, fr, err)
+ }
+ t.Cleanup(fr.Close)
+ r.creds[fr] = c
+ w = &peer{t: t, r: r.toolRig, fr: fr}
+ // Raw frames carrying the slice F keys, whatever Encode would do.
+ w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, OutcomePhase: wire.OutcomeUnfinished, XcodeAccess: wire.XcodeAccessSandboxed, SessionID: "sess-1", Findings: []wire.Finding{}})
+ _, body := w.expect(wire.FrameSendPack)
+ h := body.(*wire.SendPackCommand).Transfer
+ w.send(wire.FrameStep, workerDone(d, cand, wire.OutcomeUnfinished))
+ w.send(wire.FrameBlob, chunk(h, []byte("PACK commit")))
+ r.fromPrimary(wire.FrameBlob)
+ pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
+ want := ""
+ if protocol >= wire.ProtocolMacEngineering {
+ want = wire.OutcomeUnfinished
+ }
+ if pub.OutcomePhase != want {
+ t.Fatalf("at %d the outcome is %q, want %q", protocol, pub.OutcomePhase, want)
+ }
+ // The primary comes back at protocol.
+ ph := primaryHello(r.primary.fr.Welcome.Generation)
+ ph.Protocol = protocol
+ ph.Catalog[0].NeedsMacOS = true
+ r.primary.fr.Close()
+ p, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, ph)
+ if err != nil || p.Welcome.Protocol != protocol {
+ t.Fatalf("primary at %d: %+v %v", protocol, p, err)
+ }
+ t.Cleanup(p.Close)
+ r.runner, r.primary, r.held = p, &peer{t: t, r: r.toolRig, fr: p}, nil
+ r.primary.send(wire.FrameChangeDiff, publicationDiff(pub, base, swipeDiff))
+ rows := r.diffRows(d.StepID)
+ r.primary.send(wire.FramePublished, publishedWith(pub, base, swipeDiff))
+ s := r.task(task).Steps[0]
+ if !s.Pushed {
+ t.Fatalf("at %d not published: %+v", protocol, s)
+ }
+ if protocol < wire.ProtocolMacEngineering {
+ if rows != 0 || s.ChangeFiles != nil || s.Reason == "step_timeout" {
+ t.Fatalf("at %d slice F fields counted: %d rows, files %+v, reason %q", protocol, rows, s.ChangeFiles, s.Reason)
+ }
+ return
+ }
+ if rows != 1 || s.Reason != "step_timeout" {
+ t.Fatalf("at 37: %d rows, reason %q", rows, s.Reason)
+ }
+ r.shown(task, base, cand, swipeDiff)
+ })
}
}