oficina / equipo Public

runner: primary sends the dependency bundle to hosted checks

The instance opens the hosted pack and then the deps bundle, each under
its own transfer ID, and asks for the bundle with SendPackCommand.Deps
(refused below ProtocolHostedRunners). The primary answers after every
pack: it reads both trees from its clone, builds the bundle from its
module cache for ModulesFor(base, candidate) and sends it under the deps
transfer; past 256 MiB it sends a dataless declaration and the checks
end cannot_run deps_too_large. The instance's chunk and storage checks
and the primary's declaration use each kind's own limits, and a hosted
attempt's pack and bundle are closed when its checks end.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 29f9efcd225549c89563586651bc4ff5c77323e4 parent 91a0ba8
14 files changed, +1,070 −45
  • .rastrillo/budgets.txt +3 −3
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +40 −0
  • internal/equipo/chat/hosted_deps_test.go +229 −0
  • internal/equipo/chat/hosted_pack_test.go +5 −7
  • internal/equipo/chat/hosted_place_test.go +4 −3
  • internal/equipo/chat/tasks.go +17 −7
  • internal/equipo/chat/transfers.go +21 −11
  • internal/runner/depsbundle/gittree.go +80 −0
  • internal/runner/depsbundle/gittree_test.go +70 −0
  • internal/runner/thin/relay.go +107 −10
  • internal/runner/thin/relay_test.go +471 −0
  • internal/wire/hosted.go +4 −3
  • internal/wire/hosted_test.go +16 −0
  • internal/wire/runners.go +3 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index db10d580..395893a4 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -16,7 +16,7 @@ time internal/equipotest 300s Final fix package rerun measured 187.035s (review
time internal/equipo/hostedrun 60s Hosted slice 2 Task 21: TestDispatcherSimulation runs 200 seeds of the real chat store (SQLite) and dispatcher against a fake controller, with unlinked VMs that run to their 90-minute lifetime since review round 1, and one test drives the real controller over TLS for 90 simulated minutes; about 35 s of CPU in parallel subtests; measured 14 s on a 16 CPU docs-t1 under load 2.4; 60s covers a loaded 4 CPU runner.
size internal/equipo 25304 8741 Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, installer, abilities, lookups, Mac waits, slice F codes, D1, probe details, Design's copy, /api/team; measured 24735. Hosted slice 2 Task 15 review 1: work.reason.pack_incomplete (pending); 24736. Task 17: work.reason.deps_conflict, deps_new_module, deps_missing, deps_too_large and token_renewal_failed (pending); 24741. Task 18: the owner setting "Run checks in a hosted VM" (config flag, routes, section, handler, four pending keys); 24825. Its review round 1: chatMe reports a roster denial as chat.ErrForbidden too (chatDenied); 24837. Task 21: the hosted dispatcher started only with EQUIPO_HOSTED_RUNNERS=1, execution on and a controller configured (EQUIPO_HOSTED_* config, RevokeRunner wiring), and the work.reason words for hosted_enrol_timeout, hosted_vm_lost and hosted_unavailable (pending); 24867. Task 22: hosted_enrol.go, a hosted VM's enrolment (POST /api/hosted/enrol) and its runner's challenge and renewal under /api/runner/v2 (the store methods over the runner and credential rows, the handlers, the routes only with EQUIPO_HOSTED_RUNNERS=1 and an admission reader), and mintRunnerCredential's lifetime and cap; 25248. Its tests (hosted_enrol_test.go: the routes through the whole application, and the runner's hosted.Start end to end through the test proxy) drive the unexported store, router and admission reader, so they live beside them and take the directory past the 8000-line test default; measured 8563 test lines. Task 22 review 1: the controller's deadline in the credential cap, and tests for a stale admission after a newer refusal, the first sighting and its window, code single use alone and the controller's deadline; 25256/8669. Review 2: a renewal reads the controller's admission record first, outside the transaction, and is capped by its current deadline; its tests (a deadline moved earlier after launch, the controller away or without a record); 25304/8724. Review 3: enrolment tests for a deadline moved earlier before enrolment and one already passed; 25304/8741.
-size internal/wire 9899 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), abilities, 36 lookups, 37 Mac Engineering, 38 Design, unproven and probe detail codes, 39 hosted runners (hosted.go: placement, hosted_pack and deps transfer limits, enrolment types); measured 9848. Task 15 opened TransferHeader.Valid to hosted_pack (inbound, base then candidate) and added ReasonPackIncomplete; 9860. Its review round 1 registered it in StepReasons; 9862. Task 17: the hosted worker's reasons (deps_conflict, deps_new_module, deps_missing, deps_too_large, token_renewal_failed) registered in StepReasons, and TransferHeader.Valid opened to deps with the hosted_pack rules (the worker accepts the bundle; Task 23 sends it); 9884. Task 21: ReasonHostedEnrolTimeout, ReasonHostedVMLost and ReasonHostedUnavailable, registered in StepReasons; 9899.
+size internal/wire 9902 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), abilities, 36 lookups, 37 Mac Engineering, 38 Design, unproven and probe detail codes, 39 hosted runners (hosted.go: placement, hosted_pack and deps transfer limits, enrolment types); measured 9848. Task 15 opened TransferHeader.Valid to hosted_pack (inbound, base then candidate) and added ReasonPackIncomplete; 9860. Its review round 1 registered it in StepReasons; 9862. Task 17: the hosted worker's reasons (deps_conflict, deps_new_module, deps_missing, deps_too_large, token_renewal_failed) registered in StepReasons, and TransferHeader.Valid opened to deps with the hosted_pack rules (the worker accepts the bundle; Task 23 sends it); 9884. Task 21: ReasonHostedEnrolTimeout, ReasonHostedVMLost and ReasonHostedUnavailable, registered in StepReasons; 9899. Task 23: SendPackCommand.Deps, refused below ProtocolHostedRunners; 9902.
size internal/equipotest - 12693 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures, Rastrillo asset contract, renderer archive link; measured 0/12693 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).
@@ -41,7 +41,7 @@ perf GET /releases/* skip Verified runner release file downloads, not browser GE
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;
time internal/runner/linuxworker 30s Hosted slice 2 Task 17: each test starts real bubblewrap namespaces through the containment manager over real git stores (base gates, pins, restart and cancel proof, offline, staged cache, six dependency outcomes); measured 11.6 to 14.5s on a loaded docs-t1; review round 1 tests: 15 to 23s under load.
-size internal/runner/thin 36076 35882 Protocols 31-35, merge credential, publication guards, kept work, scans, 36 lookups; Mac pin, Engineering, asks, F probes, D1, P2, held reports; 38 Design step, renderer; hosted slice 2 Task 11 moved the base-gate checks to checkrun (source down) and pinned the primary and Mac behaviour with tests (test up), and its round 1 fixes added the worker step-engine wiring test; Task 12 added Link.TokenSource and Link.HTTPClient (a hosted runner's bearer is read at each dial and its dial goes through the proxy) and their two tests; 35831/35453. Task 14 review round 1 added Link.ReconnectWait (the wait between connections, a fake clock's in the hosted renewal tests, which drive the real Link through certificate rotation and bearer renewal); 35839/35453. Task 15: the hosted pack (inboundHeader selects by attempt and kind, Worker.Hosted indexes the base and the candidate into an empty store, pack_incomplete) and hosted_pack_test.go; 35863/35688. Task 17 wiring for the Linux checks worker (hosted_worker.go): Options.Hosted (HostedLink: the session's in-memory credential, proxy client, Work context, Flush on a failed renewal and token_renewal_failed), WorkerKind.Checks and Probe, runHosted, the Linux worker refusal outside hosted-run, the hand-off of an indexed hosted attempt and its deps bundle to the kind's checks, the receiver's per-kind transfer limits; its two tests; 36073/35768. Review round 1: the deps header checked before the wait, and TestDepsPackPerKindLimits (the receiver past the old 64 MiB and chunk limits); 36076/35824. Review round 2: TestPrimaryChecksCancelledChangedGate (a certified changed-gate run cancelled in its base run ends cancelled, no diagnostic); 36076/35882.
+size internal/runner/thin 36173 36353 Protocols 31-35, merge credential, publication guards, kept work, scans, 36 lookups; Mac pin, Engineering, asks, F probes, D1, P2, held reports; 38 Design step, renderer; hosted slice 2 Task 11 moved the base-gate checks to checkrun (source down) and pinned the primary and Mac behaviour with tests (test up), and its round 1 fixes added the worker step-engine wiring test; Task 12 added Link.TokenSource and Link.HTTPClient (a hosted runner's bearer is read at each dial and its dial goes through the proxy) and their two tests; 35831/35453. Task 14 review round 1 added Link.ReconnectWait (the wait between connections, a fake clock's in the hosted renewal tests, which drive the real Link through certificate rotation and bearer renewal); 35839/35453. Task 15: the hosted pack (inboundHeader selects by attempt and kind, Worker.Hosted indexes the base and the candidate into an empty store, pack_incomplete) and hosted_pack_test.go; 35863/35688. Task 17 wiring for the Linux checks worker (hosted_worker.go): Options.Hosted (HostedLink: the session's in-memory credential, proxy client, Work context, Flush on a failed renewal and token_renewal_failed), WorkerKind.Checks and Probe, runHosted, the Linux worker refusal outside hosted-run, the hand-off of an indexed hosted attempt and its deps bundle to the kind's checks, the receiver's per-kind transfer limits; its two tests; 36073/35768. Review round 1: the deps header checked before the wait, and TestDepsPackPerKindLimits (the receiver past the old 64 MiB and chunk limits); 36076/35824. Review round 2: TestPrimaryChecksCancelledChangedGate (a certified changed-gate run cancelled in its base run ends cancelled, no diagnostic); 36076/35882. Task 23: the primary's dependency bundle (Relay.deps after every pack, Engineer.depsBundle from the clone's trees and its module cache, a deps request refused unless it is exactly one), per-kind limits and a dataless oversize declaration in queueUpload; the relay_test.go tests, the 100 MiB end-to-end relay through the instance's store included; 36173/36353.
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 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally.
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).
@@ -60,7 +60,7 @@ perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON
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.
perf GET /api/v1/assistant/abilities skip Assistant person API: bearer-only JSON for Base's Settings line, not a browser screen.
-size internal/equipo/chat 46937 20971 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. Its review round 2: an admission record's current deadline is kept too (hostedAdmitted, for the dispatcher's refresh and the renewal's HostedRenewAdmit); 46932/20971. Round 3: HostedEnrolAdmit returns the job re-read after recording the admission, so the enrolment caps by its deadline; 46937/20971.
+size internal/equipo/chat 46957 21199 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. Its review round 2: an admission record's current deadline is kept too (hostedAdmitted, for the dispatcher's refresh and the renewal's HostedRenewAdmit); 46932/20971. Round 3: HostedEnrolAdmit returns the job re-read after recording the admission, so the enrolment caps by its deadline; 46937/20971. Task 23: openHostedPack opens the deps bundle after the hosted pack (send_pack with Deps), the instance's chunk and byte checks per kind (wire.MaxChunks, wire.MaxBytes), deps_too_large for a bundle past its limit, and a hosted attempt's pack and bundle closed when its checks end; hosted_deps_test.go; 46957/21199.
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.
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 15c2faf3..90f1769b 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1784,3 +1784,43 @@ Mutation:
- **331** the reload removed (the re-read goes into a throwaway `HostedJob{}`). Same command: exit 1, the same failure at `:679` (11:35, want 10:20). Restored.
Green: the brief's command passes (6.2 s), as does `./internal/equipo/chat -run 'TestHosted|TestMigrationAdditive'`. `make migration-check budget build vet` exits 0. Budgets: `internal/equipo` 25304/8741, `internal/equipo/chat` 46937.
+
+## Task 23
+
+The dependency bundle relayed from the primary (S2-1's send half).
+
+- **Wire:** `SendPackCommand` gains `Deps bool` (`deps`, omitempty, so a checks send_pack keeps its bytes). `downgradeHostedRunners` refuses a send_pack with `Deps` below `ProtocolHostedRunners`, whatever its header.
+- **Instance:** `openHostedPack` (called by Task 21's dispatch of an enrolled job) opens two transfers, each with an instance-made `tr_` ID and its own send_pack to the primary: the hosted pack, then the deps bundle (`openTransfer` sets `Deps` for a deps header). It returns both. The instance's chunk check (`transfers.go`) and its per-transfer relay storage check use `wire.MaxChunks(tr.Kind)` and `wire.MaxBytes(tr.Kind)`. A deps transfer past its limit (a declared total, or bytes) ends the checks `cannot_run` `deps_too_large` (`tooLarge`), at once when not started, else withdrawn with that reason and the runner told to stop. When a checks step ends, however it ends (`saveStep`), its attempt's `hosted_pack` and `deps` transfers are closed (`closeTransfers` takes kinds): unacked chunks and send_packs voided, relayed chunk bodies emptied. When the job ends and the step goes again, `voidAttempt` already closes them.
+- **Primary:** `Relay.Once` answers every other send_pack first, then each bundle request (`Relay.deps`), so the bundle follows the pack. `Engineer.depsBundle` refuses (upload `refused`, never retried) anything but a valid deps header asked with `Deps`, for commits the clone has. It reads both trees from the clone with no checkout (`depsbundle.CommitTree`: `ls-tree`, then each go.mod `cat-file`d when `ModulesFor` opens it), takes `ModulesFor(base, candidate)`, and builds from `firstNonEmpty(Runner.ModuleCache, ~/go/pkg/mod)` (the cache its own checks mount) within `depsBundleLimit` (256 MiB). Too many modules or a bundle past the limit is `ErrTooLarge`: `queueOversize` sends no bundle bytes, one chunk with no data declaring `MaxChunks(deps)+1`, so the instance ends the step `deps_too_large`. A go.mod that does not parse gives an empty bundle (MODULES only): the hosted worker's checks then fail as a personal runner's would, instead of waiting for a bundle. `queueUpload` declares by the kind's own bound (`wire.MaxBytes`). Every oversize declaration, for any kind, now carries no data (it used to carry the first chunk's bytes, which no receiver read).
+- `depsbundle.CommitTree` (new `gittree.go`) lists only regular go.mod and vendor/modules.txt files (a symlink is not a file) and refuses a name that is not a full object name before git runs. A listing past 64 MiB is `ErrTooLarge`.
+
+Red (API stubs only: the `Deps` field and `depsBundleLimit` declared):
+- `CGO_ENABLED=0 go test ./internal/wire -run TestHostedKindsNeedProtocol -count=1`: FAIL `hosted_test.go:97: a deps send_pack at 38 = ({..."deps":true}, <nil>), want ErrProtocol`.
+- `CGO_ENABLED=0 go test ./internal/equipo/chat -run 'TestPrimarySendsBundle|TestNoBundle|TestBundleTooLarge|TestDepsTransfer' -count=1`: FAIL `TestPrimarySendsBundleForHostedStep`, `TestBundleTooLargeEndsStep`, `TestDepsTransferInstanceLimits`, both `TestDepsTransferCleanedUp` subtests: `hosted_deps_test.go:...: send_pack commands to the primary: 1 [{... Kind:hosted_pack ... Deps:false}], want the hosted pack and the deps bundle`. `TestNoBundleForPersonalWorker` passed (a personal worker already got no bundle); mutations 332 and 333 below are its failing evidence.
+- `CGO_ENABLED=0 go test ./internal/runner/thin -run 'TestPrimarySendsBundle|TestNoBundle|TestBundleTooLarge|TestDepsTransfer' -count=1`: FAIL `relay_test.go:463: bundle sent false; uploads sent and pending`; `relay_test.go:512: a blob under {ID:tr_wrong_0 ... Kind: ...}, want only the checks pack` (the old primary packed a checks header asked with Deps); `relay_test.go:536: an oversize bundle sent 0 chunks [], want one declaring 1822 chunks with no data`; `TestDepsTransferAbove64MiB`: `100_MiB: relay_test.go:643: the worker's assembly of 0 chunks: pack incomplete`, `257_MiB: relay_test.go:637: 257 MiB: sent 0, relayed 0, transfer open, checks {State:queued ...}; want one declaring chunk, nothing relayed, cannot_run deps_too_large`.
+- Written after their code (mutations their failing evidence): `TestPrimarySendsBundleMalformedGoMod` (340) and `depsbundle`'s `TestCommitTree` (343).
+
+`TestDepsTransferAbove64MiB` is in process, end to end: the primary's real `Relay` and `Engineer` over a git remote and a module cache whose module zip is a 100 MiB sparse file; the instance's real `chat.Store` (`Apply` of each chunk, `Pending` to the VM's runner, `Apply` of each ack, which closes the transfer after the last); the worker's `State.AcceptChunk` and its assembly (`pack`). 712 chunks arrive under the deps header and reassemble to the primary's digest; the transfer is closed after the last ack. A 257 MiB zip: the primary sends one dataless chunk declaring 1822 chunks, the instance relays nothing and the checks end `cannot_run` `deps_too_large`. The three SQLite stores run with `synchronous=OFF` in this test only: with fsync per chunk it took 16.5 s on docs-t1 (7 s of CPU), without it 7.4 s.
+
+Green:
+- The brief's command, `CGO_ENABLED=0 go test ./internal/runner/thin ./internal/equipo/chat -run 'TestPrimarySendsBundle|TestNoBundle|TestBundleTooLarge|TestDepsTransfer' -count=1`: ok (thin 11.7 s, `TestDepsTransferAbove64MiB` 9 s of it; chat 0.5 s).
+- Also ok: `./internal/wire`, `./internal/runner/depsbundle`, the whole `./internal/equipo/chat` (25.6 s), `./internal/equipo/hostedrun` (simulation included), `./internal/runner/linuxworker`, `./internal/equipo -run 'TestHosted|TestStepReasons|Copy'`, thin `-run 'TestRelay|TestHosted|TestPack|TestWorker|TestInbound|TestEmptyStore|TestMissingBase|TestTransfer|TestEngineeringTransfer|TestDepsPack|TestPrimaryChecks|TestMacWorker|TestPublish|TestPrepareBase|TestCheck|TestLinuxWorker'` (81 s under load), thintest `-run 'TestContractTransfer|TestOutboundPackOversize|TestReview|TestContractWorker|TestWorker|TestContractPublication|TestContractMac|TestPlacement|TestWbfix|TestContractEngineering'`.
+- Two earlier tests follow the new opening: `TestHostedPackSendPackFromInstance` takes both transfers from `openHostedPack`, and `TestEnrolledJobDispatches` expects the hosted pack and then the bundle.
+- `make migration-check budget build vet`: exit 0. staticcheck v0.7.0 on depsbundle, thin, chat, wire: only the old `mac_fprobe.go:182 xcode is unused`. gofmt and `git diff --check`: clean.
+
+Mutations (each an exact-string replace by a script under `$TMPDIR`, one at a time, the named test run, the file restored from the original text and compared):
+- **332** the instance always asks for the bundle (`Deps: tr.Kind == wire.TransferKindDeps` → `Deps: true` in `openTransfer`). `CGO_ENABLED=0 go test ./internal/equipo/chat -run TestNoBundleForPersonalWorker -count=1`: exit 1, `hosted_deps_test.go:118: send_packs for a personal worker [{... Kind: ... Deps:true}], want the candidate's pack alone`. Restored.
+- **333** the brief's mutation, always send the bundle, at the instance (a personal worker's checks dispatched with `openHostedPack`). Same command: exit 1, `hosted_deps_test.go:118: send_packs for a personal worker [{... Kind:hosted_pack ... Deps:false} {... Kind:deps ... Deps:true}], want the candidate's pack alone`. Restored.
+- **334** the brief's mutation at the primary: a bundle for any request (`!u.Deps || h.Kind != wire.TransferKindDeps ||` removed from `depsBundle`). `CGO_ENABLED=0 go test ./internal/runner/thin -run TestNoBundleForPersonalWorker -count=1`: exit 1, `relay_test.go:548: a blob under {ID:tr_deps ... Kind:deps ...}, want only the checks pack`. Restored.
+- **335** the instance's chunk check at 64 MiB's bound (`wire.MaxChunks(tr.Kind)` → `wire.MaxTransferChunks`). `CGO_ENABLED=0 go test ./internal/equipo/chat -run TestDepsTransferInstanceLimits -count=1`: exit 1, `hosted_deps_test.go:171: a deps total of 458 chunks (past the 456 of other kinds): transfer closed, relayed 0; want open and relayed`. Restored.
+- **336** the instance's relay storage at 64 MiB (`wire.MaxBytes(tr.Kind)` → `wire.MaxTransferBytes`). Same command: exit 1, `hosted_deps_test.go:176: deps transfer closed received 1, relayed 0; want both chunks relayed`. Restored.
+- **337** the primary declares past 64 MiB for every kind (`wire.MaxBytes(h.Kind)` → `wire.MaxTransferBytes` in `queueUpload`). `CGO_ENABLED=0 go test ./internal/runner/thin -run TestDepsTransferAbove64MiB -count=1`: exit 1, `100_MiB: relay_test.go:630: chunk 0 declares 1822 chunks (deps bound 1821)`. Restored.
+- **338** a bundle past its limit ends as checks_unavailable (`wire.ReasonDepsTooLarge` → `"checks_unavailable"` in `tooLarge`). `CGO_ENABLED=0 go test ./internal/equipo/chat -run TestBundleTooLargeEndsStep -count=1`: exit 1, `hosted_deps_test.go:149: checks done cannot_run checks_unavailable, want done cannot_run deps_too_large`. Restored.
+- **339** no clean-up when the checks end (the `closeTransfers` call in `saveStep` replaced by `error(nil)`). `CGO_ENABLED=0 go test ./internal/equipo/chat -run TestDepsTransferCleanedUp -count=1`: exit 1, `step_ends: hosted_deps_test.go:219: transfer tr_... (hosted_pack) is open, want closed`. Restored.
+- **340** a malformed go.mod leaves the bundle unsent (`want, err = nil, nil` → `want = nil`). `CGO_ENABLED=0 go test ./internal/runner/thin -run TestPrimarySendsBundleMalformedGoMod -count=1`: exit 1, `relay_test.go:520: bundle for a malformed go.mod: entries [], upload pending; want an empty MODULES, sent`. Restored.
+- **341** the bundle before the pack (deps answered in the first loop, in arrival order). `CGO_ENABLED=0 go test ./internal/runner/thin -run TestPrimarySendsBundleForHostedStep -count=1`: exit 1, `relay_test.go:467: a hosted pack chunk after the bundle's`. Restored.
+- **342** `Deps` not protocol-gated (`h.hostedTransfer() || ok && sp.Deps` → `h.hostedTransfer()`). `CGO_ENABLED=0 go test ./internal/wire -run TestHostedKindsNeedProtocol -count=1`: exit 1, `hosted_test.go:97: a deps send_pack at 38 = ({..."deps":true}, <nil>), want ErrProtocol`. Restored.
+- **343** a symlinked go.mod read as a file (`fields[0] != "100644" && fields[0] != "100755"` → `fields[0] == "040000"` in `CommitTree`). `CGO_ENABLED=0 go test ./internal/runner/depsbundle -run TestCommitTree -count=1`: exit 1, `gittree_test.go:55: ModulesFor over the commit's tree = [example.com/dep@v1.0.0 example.com/linked@v0.2.0], <nil>; want example.com/dep only`. Restored.
+- **344** the bundle limit ignored (`depsBundleLimit` → `1<<40` in `Build`'s call). `CGO_ENABLED=0 go test ./internal/runner/thin -run TestBundleTooLargeEndsStep -count=1`: exit 1, `relay_test.go:576: an oversize bundle sent 1 chunks, the first declaring 1 with 25260 bytes of data; want one declaring 1822 chunks with no data`. Restored.
+
+Budgets, each with its reason: `internal/wire` 9902, `internal/runner/thin` 36173/36353, `internal/equipo/chat` 46957/21199. `internal/runner/depsbundle` stays within the defaults.
diff --git a/internal/equipo/chat/hosted_deps_test.go b/internal/equipo/chat/hosted_deps_test.go
new file mode 100644
index 00000000..36029182
--- /dev/null
+++ b/internal/equipo/chat/hosted_deps_test.go
@@ -0,0 +1,229 @@
+package chat
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Hosted slice 2, Task 23: the dependency bundle. When the instance asks
+// the primary for an enrolled hosted job's pack it opens a second
+// transfer, the deps bundle, under its own ID, and asks for it with
+// SendPackCommand.Deps; the bundle may pass 64 MiB, up to wire's deps
+// limit; past it the checks end cannot_run deps_too_large; and a hosted
+// attempt's transfers go when its step ends.
+
+// primaryLease is P1's connection at ProtocolHostedRunners.
+func primaryLease() Lease {
+ return Lease{Runner: RunnerPrincipal{RunnerID: hpPrimary, Person: hkOwner}, Generation: 1, Process: "p", Protocol: wire.ProtocolHostedRunners, Role: wire.RolePrimary}
+}
+
+// sendPacks are the send_pack commands to the primary, in order.
+func (r *hkRig) sendPacks() []wire.SendPackCommand {
+ r.t.Helper()
+ var out []wire.SendPackCommand
+ for _, c := range r.commands(hpPrimary, wire.FrameSendPack) {
+ var sp wire.SendPackCommand
+ r.must(json.Unmarshal([]byte(c.Body), &sp))
+ out = append(out, sp)
+ }
+ return out
+}
+
+func (r *hkRig) transfer(id string) transferRecord {
+ r.t.Helper()
+ var tr transferRecord
+ r.must(r.s.db.G.Where("id = ?", id).First(&tr).Error)
+ return tr
+}
+
+// chunk applies one blob from runner's lease: Total chunks declared,
+// data its bytes, sum the whole pack's digest.
+func (r *hkRig) chunk(l Lease, h wire.TransferHeader, idx, total int, data []byte, sum string) error {
+ b := wire.Blob{Transfer: h, Index: idx, Total: total, SHA256: sum, Data: base64.StdEncoding.EncodeToString(data)}
+ f, err := wire.NewFrame("b-"+h.ID+"-"+itoa64(int64(idx)), wire.FrameBlob, b)
+ if err != nil {
+ return err
+ }
+ return r.s.Apply(r.ctx, l, f, &b)
+}
+
+func digestOf(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) }
+
+// hostedTransfers places s1 on VM vm-1 enrolled as H1 and returns its
+// hosted pack and deps send_packs.
+func (r *hkRig) hostedTransfers() (pack, deps wire.SendPackCommand) {
+ r.t.Helper()
+ r.checksStep("s1", "tkp")
+ r.hostedOnVM("vm-1", "H1")
+ sps := r.sendPacks()
+ if len(sps) != 2 {
+ r.t.Fatalf("send_pack commands to the primary: %d %+v, want the hosted pack and the deps bundle", len(sps), sps)
+ }
+ return sps[0], sps[1]
+}
+
+// TestPrimarySendsBundleForHostedStep: an enrolled job's dispatch asks
+// the primary for the hosted pack and then for the dependency bundle:
+// two transfers the instance made, from the primary to the VM's runner,
+// the second a deps header for the same attempt asked with Deps. Below
+// ProtocolHostedRunners the bundle's send_pack is refused.
+func TestPrimarySendsBundleForHostedStep(t *testing.T) {
+ r := hostedPlaceRig(t)
+ pack, deps := r.hostedTransfers()
+ if pack.Transfer.Kind != wire.TransferKindHostedPack || pack.Deps {
+ t.Fatalf("first send_pack %+v deps %v, want the hosted pack without the bundle", pack.Transfer, pack.Deps)
+ }
+ want := pack.Transfer
+ want.ID, want.Kind = deps.Transfer.ID, wire.TransferKindDeps
+ if !deps.Deps || deps.Transfer != want || !deps.Transfer.Valid() {
+ t.Fatalf("second send_pack %+v deps %v, want %+v asking for the bundle", deps.Transfer, deps.Deps, want)
+ }
+ if !strings.HasPrefix(deps.Transfer.ID, "tr_") || deps.Transfer.ID == pack.Transfer.ID {
+ t.Fatalf("transfer IDs %q and %q, want two the instance made", pack.Transfer.ID, deps.Transfer.ID)
+ }
+ for _, sp := range []wire.SendPackCommand{pack, deps} {
+ tr := r.transfer(sp.Transfer.ID)
+ if tr.FromRunner != hpPrimary || tr.ToRunner != "H1" || tr.State != transferOpen || transferHeader(tr) != sp.Transfer {
+ t.Fatalf("transfer %+v for %+v", tr, sp.Transfer)
+ }
+ }
+ f, err := wire.NewFrame("sp", wire.FrameSendPack, deps)
+ r.must(err)
+ if _, err := wire.Encode(f, wire.ProtocolHostedRunners-1); !errors.Is(err, wire.ErrProtocol) {
+ t.Fatalf("the bundle's send_pack below ProtocolHostedRunners: %v", err)
+ }
+}
+
+// TestNoBundleForPersonalWorker: checks placed on a person's own Mac
+// worker get the candidate's pack alone; no bundle is asked for.
+func TestNoBundleForPersonalWorker(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.runner("M1", wire.RoleWorker)
+ r.online("M1", wire.ProtocolHostedRunners)
+ hello, _ := json.Marshal(wire.Hello{Sandbox: wire.SandboxSeatbelt, Capabilities: &wire.Capabilities{Tags: []string{wire.TagMacOS, wire.TagXcode}}})
+ r.exec("UPDATE runner_sessions SET hello = ? WHERE runner_id = 'M1'", string(hello))
+ r.must(r.s.db.G.Create(&stepRecord{ID: "e1", TaskID: "tkp", Idx: 1, Person: hkOwner, State: wire.StepDone, Attempt: 1, Specialist: wire.SpecialistEngineering, Apple: true, CreatedAt: r.now, UpdatedAt: r.now}).Error)
+ if s := r.checksStep("s1", "tkp"); s.RunnerID != "M1" {
+ t.Fatalf("checks placed %q on %q, want the Mac M1", s.Placement, s.RunnerID)
+ }
+ sps := r.sendPacks()
+ if len(sps) != 1 || sps[0].Deps || sps[0].Transfer.Kind != "" {
+ t.Fatalf("send_packs for a personal worker %+v, want the candidate's pack alone", sps)
+ }
+ var n int64
+ r.must(r.s.db.G.Model(&transferRecord{}).Where("kind = ?", wire.TransferKindDeps).Count(&n).Error)
+ if n != 0 {
+ t.Fatalf("%d deps transfers for a personal worker", n)
+ }
+}
+
+// TestBundleTooLargeEndsStep: the primary's chunk declaring a bundle past
+// the deps limit closes the transfer, relays nothing, and ends the checks
+// not run with deps_too_large: at once before the attempt started, or,
+// once started, withdrawn with that reason and the VM's runner told to
+// stop.
+func TestBundleTooLargeEndsStep(t *testing.T) {
+ for _, started := range []bool{false, true} {
+ r := hostedPlaceRig(t)
+ _, deps := r.hostedTransfers()
+ if started {
+ r.exec("UPDATE chat_steps SET state = ?, started_at = ? WHERE id = 's1'", wire.StepRunning, r.now)
+ }
+ r.must(r.chunk(primaryLease(), deps.Transfer, 0, wire.MaxChunks(wire.TransferKindDeps)+1, nil, digestOf(nil)))
+ if tr := r.transfer(deps.Transfer.ID); tr.State != transferClosed {
+ t.Fatalf("started %v: deps transfer %s after an oversize declaration, want closed", started, tr.State)
+ }
+ if got := r.commands("H1", wire.FrameBlob); len(got) != 0 {
+ t.Fatalf("started %v: relayed %d chunks of an oversize bundle", started, len(got))
+ }
+ s := r.step("s1")
+ if !started {
+ if s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != wire.ReasonDepsTooLarge {
+ t.Fatalf("checks %s %s %s, want done cannot_run deps_too_large", s.State, s.Checks, s.Reason)
+ }
+ continue
+ }
+ if !s.Withdrawn || s.Reason != wire.ReasonDepsTooLarge || len(r.commands("H1", wire.FrameCancelStep)) != 1 {
+ t.Fatalf("started: withdrawn %v reason %q, cancels %d; want withdrawn for deps_too_large and one cancel", s.Withdrawn, s.Reason, len(r.commands("H1", wire.FrameCancelStep)))
+ }
+ }
+}
+
+// TestDepsTransferInstanceLimits: the instance counts a deps transfer's
+// chunks and bytes against wire's deps limits, not the 64 MiB of every
+// other kind: a total past the old chunk bound is relayed, as is a chunk
+// that takes it past 64 MiB; one that takes it past the deps limit ends
+// the checks deps_too_large.
+func TestDepsTransferInstanceLimits(t *testing.T) {
+ r := hostedPlaceRig(t)
+ _, deps := r.hostedTransfers()
+ total := wire.MaxTransferChunks + 2
+ sum := strings.Repeat("ab", 32)
+ r.must(r.chunk(primaryLease(), deps.Transfer, 0, total, []byte("first"), sum))
+ if tr := r.transfer(deps.Transfer.ID); tr.State != transferOpen || len(r.commands("H1", wire.FrameBlob)) != 1 {
+ t.Fatalf("a deps total of %d chunks (past the %d of other kinds): transfer %s, relayed %d; want open and relayed", total, wire.MaxTransferChunks, tr.State, len(r.commands("H1", wire.FrameBlob)))
+ }
+ r.exec("UPDATE runner_transfers SET bytes = ? WHERE id = ?", wire.MaxTransferBytes, deps.Transfer.ID)
+ r.must(r.chunk(primaryLease(), deps.Transfer, 1, total, []byte("past 64 MiB"), sum))
+ if tr := r.transfer(deps.Transfer.ID); tr.State != transferOpen || tr.Received != 2 || len(r.commands("H1", wire.FrameBlob)) != 2 {
+ t.Fatalf("deps transfer %s received %d, relayed %d; want both chunks relayed", tr.State, tr.Received, len(r.commands("H1", wire.FrameBlob)))
+ }
+ r.exec("UPDATE runner_transfers SET bytes = ? WHERE id = ?", wire.DepsTransferMax-4, deps.Transfer.ID)
+ r.must(r.chunk(primaryLease(), deps.Transfer, 2, total, []byte("past the deps limit"), sum))
+ if tr, s := r.transfer(deps.Transfer.ID), r.step("s1"); tr.State != transferClosed || s.Reason != wire.ReasonDepsTooLarge || s.Checks != wire.ChecksCannotRun {
+ t.Fatalf("past the deps limit: transfer %s, checks %s %s; want closed, cannot_run deps_too_large", tr.State, s.Checks, s.Reason)
+ }
+}
+
+// TestDepsTransferCleanedUp: when a hosted step ends, however it ends,
+// its bundle's chunks are emptied and nothing of it is served again; the
+// hosted pack's go too. When the job ends and the step is placed again,
+// the old attempt's transfers are gone as well.
+func TestDepsTransferCleanedUp(t *testing.T) {
+ gone := func(r *hkRig, ids ...string) {
+ r.t.Helper()
+ for _, id := range ids {
+ if tr := r.transfer(id); tr.State != transferClosed {
+ r.t.Fatalf("transfer %s (%s) is %s, want closed", id, tr.Kind, tr.State)
+ }
+ var live int64
+ r.must(r.s.db.G.Model(&commandRecord{}).Where("body LIKE ? AND (acked_at IS NULL OR (kind = ? AND body <> '{}'))", `%"transfer":{"id":"`+id+`"%`, wire.FrameBlob).Count(&live).Error)
+ if live != 0 {
+ r.t.Fatalf("%d commands of transfer %s still served or holding bytes", live, id)
+ }
+ }
+ }
+ t.Run("step ends", func(t *testing.T) {
+ r := hostedPlaceRig(t)
+ pack, deps := r.hostedTransfers()
+ r.must(r.chunk(primaryLease(), deps.Transfer, 0, 2, []byte("half a bundle"), strings.Repeat("cd", 32)))
+ if got := r.commands("H1", wire.FrameBlob); len(got) != 1 {
+ t.Fatalf("relayed %d chunks", len(got))
+ }
+ r.must(r.tx(func(tx *txn) error {
+ s := r.step("s1")
+ k, err := tx.loadTask(s.TaskID)
+ if err != nil {
+ return err
+ }
+ endFailed(tx, &s, "checks_timeout")
+ return tx.saveStep(&s, &k)
+ }))
+ gone(r, pack.Transfer.ID, deps.Transfer.ID)
+ })
+ t.Run("job ends", func(t *testing.T) {
+ r := hostedPlaceRig(t)
+ pack, deps := r.hostedTransfers()
+ r.must(r.chunk(primaryLease(), deps.Transfer, 0, 2, []byte("half a bundle"), strings.Repeat("cd", 32)))
+ jobs := r.jobsOf("s1")
+ r.stopped(jobs[len(jobs)-1].AttemptID, "vm_lost")
+ gone(r, pack.Transfer.ID, deps.Transfer.ID)
+ })
+}
diff --git a/internal/equipo/chat/hosted_pack_test.go b/internal/equipo/chat/hosted_pack_test.go
index 186aabff..bd12ca9e 100644
--- a/internal/equipo/chat/hosted_pack_test.go
+++ b/internal/equipo/chat/hosted_pack_test.go
@@ -21,7 +21,8 @@ import (
// Hosted slice 2, Task 15: the instance asks the primary for a hosted
// checks step's pack, the base and the candidate, under a transfer ID it
// makes; the send_pack never reaches a primary below
-// ProtocolHostedRunners. Placement (Task 21) calls openHostedPack.
+// ProtocolHostedRunners. Placement (Task 21) calls openHostedPack, which
+// opens Task 23's bundle after it under an ID of its own.
func TestHostedPackSendPackFromInstance(t *testing.T) {
src, err := hkTemplatePath()
if err != nil {
@@ -54,16 +55,13 @@ func TestHostedPackSendPackFromInstance(t *testing.T) {
var pack, deps transferRecord
if err := s.tx(context.Background(), func(tx *txn) error {
var err error
- if pack, err = tx.openHostedPack(k, st, "R1", base); err != nil {
- return err
- }
// Task 23's bundle, for the same attempt, under its own ID.
- deps, err = tx.openTransfer(k, st, "R1", "R2", wire.TransferHeader{Direction: wire.TransferInbound, Kind: wire.TransferKindDeps, BaseSHA: base, CandidateSHA: candidate})
+ pack, deps, err = tx.openHostedPack(k, st, "R1", base)
return err
}); err != nil {
t.Fatal(err)
}
- if !strings.HasPrefix(pack.ID, "tr_") || pack.ID == deps.ID || pack.FromRunner != "R1" || pack.ToRunner != "R2" {
+ if !strings.HasPrefix(pack.ID, "tr_") || pack.ID == deps.ID || pack.FromRunner != "R1" || pack.ToRunner != "R2" || deps.Kind != wire.TransferKindDeps || deps.ToRunner != "R2" {
t.Fatalf("hosted pack transfer %+v beside deps %s", pack, deps.ID)
}
want := wire.TransferHeader{ID: pack.ID, Direction: wire.TransferInbound, Repo: "amadan.net/oficina/sample", TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: base, CandidateSHA: candidate, Kind: wire.TransferKindHostedPack}
@@ -88,7 +86,7 @@ func TestHostedPackSendPackFromInstance(t *testing.T) {
// No base, or a base that is the candidate: no transfer, no command.
for _, b := range []string{"", candidate} {
if err := s.tx(context.Background(), func(tx *txn) error {
- _, err := tx.openHostedPack(k, st, "R1", b)
+ _, _, err := tx.openHostedPack(k, st, "R1", b)
return err
}); !errors.Is(err, ErrInvalid) {
t.Fatalf("hosted pack on base %q: %v, want ErrInvalid", b, err)
diff --git a/internal/equipo/chat/hosted_place_test.go b/internal/equipo/chat/hosted_place_test.go
index 8ae18da5..9e18be7f 100644
--- a/internal/equipo/chat/hosted_place_test.go
+++ b/internal/equipo/chat/hosted_place_test.go
@@ -271,7 +271,8 @@ func TestRepeatedPlacementOneJob(t *testing.T) {
}
// TestEnrolledJobDispatches: an enrolled job's step goes to its runner
-// with the hosted pack (base and candidate) asked of the primary; while
+// with the hosted pack (base and candidate) asked of the primary, and
+// then its dependency bundle (Task 23); while
// the VM's runner is away, or below ProtocolHostedRunners, it waits.
func TestEnrolledJobDispatches(t *testing.T) {
r := hostedPlaceRig(t)
@@ -293,8 +294,8 @@ func TestEnrolledJobDispatches(t *testing.T) {
t.Fatalf("dispatches to H1: %+v", got)
}
packs := r.commands(hpPrimary, wire.FrameSendPack)
- if len(packs) != 1 {
- t.Fatalf("send_pack to the primary: %d, want 1", len(packs))
+ if len(packs) != 2 || !strings.Contains(packs[1].Body, `"kind":"deps"`) {
+ t.Fatalf("send_pack to the primary: %d, want the hosted pack and the bundle", len(packs))
}
var sp wire.SendPackCommand
r.must(json.Unmarshal([]byte(packs[0].Body), &sp))
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 8cec2583..a8aa392b 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -839,7 +839,11 @@ func (t *txn) saveStep(s *stepRecord, k *taskRecord) error {
return t.releaseResearch(k)
}
if s.Specialist == wire.SpecialistChecks && wire.StepTerminal(s.State) {
- // Checks ended, however they ended: a hosted VM for them stops.
+ // Checks ended, however they ended: a hosted VM for them stops,
+ // and its pack and bundle go from the relay.
+ if err := t.closeTransfers(s.ID, s.Attempt, wire.TransferKindHostedPack, wire.TransferKindDeps); err != nil {
+ return err
+ }
return t.hostedStepEnded(s.ID)
}
return nil
@@ -1138,15 +1142,21 @@ func (t *txn) startTask(r turnRecord, id, brief, maker string) (wire.ToolResult,
}
// openHostedPack asks the primary for a hosted checks attempt's pack, the
-// base and the candidate (wire.TransferKindHostedPack), under a transfer
+// base and the candidate (wire.TransferKindHostedPack), and then for its
+// dependency bundle (wire.TransferKindDeps, Deps), each under a transfer
// ID of its own. Placement on a hosted VM needs ProtocolHostedRunners on
-// both ends; Encode refuses the send_pack below it.
-func (t *txn) openHostedPack(k taskRecord, s stepRecord, primary, base string) (transferRecord, error) {
+// both ends; Encode refuses both send_packs below it.
+func (t *txn) openHostedPack(k taskRecord, s stepRecord, primary, base string) (pack, deps transferRecord, err error) {
h := wire.TransferHeader{Direction: wire.TransferInbound, Kind: wire.TransferKindHostedPack, BaseSHA: base, CandidateSHA: s.CandidateSHA}
if !h.Valid() {
- return transferRecord{}, fmt.Errorf("%w: hosted pack for %s", ErrInvalid, s.ID)
+ return pack, deps, fmt.Errorf("%w: hosted pack for %s", ErrInvalid, s.ID)
+ }
+ if pack, err = t.openTransfer(k, s, primary, s.RunnerID, h); err != nil {
+ return pack, deps, err
}
- return t.openTransfer(k, s, primary, s.RunnerID, h)
+ h.Kind = wire.TransferKindDeps
+ deps, err = t.openTransfer(k, s, primary, s.RunnerID, h)
+ return pack, deps, err
}
// dispatchStep queues the dispatch command for the step's attempt on the
@@ -1358,7 +1368,7 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
if hosted, err := t.hostedBound(*s, s.RunnerID); err != nil {
return err
} else if hosted {
- if _, err := t.openHostedPack(*k, *s, primary, cmd.BaseSHA); err != nil {
+ if _, _, err := t.openHostedPack(*k, *s, primary, cmd.BaseSHA); err != nil {
return err
}
} else if _, err := t.openTransfer(*k, *s, primary, s.RunnerID, wire.TransferHeader{Direction: wire.TransferInbound, BaseSHA: cmd.BaseSHA, CandidateSHA: s.CandidateSHA}); err != nil {
diff --git a/internal/equipo/chat/transfers.go b/internal/equipo/chat/transfers.go
index 77868b25..ec6acc3e 100644
--- a/internal/equipo/chat/transfers.go
+++ b/internal/equipo/chat/transfers.go
@@ -32,7 +32,8 @@ var hexDigest = regexp.MustCompile(`^[0-9a-f]{64}$`)
// placed it (inbound) or accepted its candidate (outbound), and asks the
// sender for the pack (send_pack names the transfer it uploads under). h
// gives the direction and the commits (kind, base, old base, candidate);
-// the attempt's own fields come from the step.
+// the attempt's own fields come from the step. A deps transfer asks for
+// the dependency bundle (Deps).
func (t *txn) openTransfer(k taskRecord, s stepRecord, from, to string, h wire.TransferHeader) (transferRecord, error) {
var p projectRecord
if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil {
@@ -43,18 +44,22 @@ func (t *txn) openTransfer(k taskRecord, s stepRecord, from, to string, h wire.T
if err := t.db.Create(&tr).Error; err != nil {
return tr, err
}
- return tr, t.commandTo(from, s.Person, wire.FrameSendPack, wire.SendPackCommand{Transfer: transferHeader(tr), Have: []string{}})
+ return tr, t.commandTo(from, s.Person, wire.FrameSendPack, wire.SendPackCommand{Transfer: transferHeader(tr), Have: []string{}, Deps: tr.Kind == wire.TransferKindDeps})
}
func transferHeader(tr transferRecord) wire.TransferHeader {
return wire.TransferHeader{ID: tr.ID, Direction: tr.Direction, Repo: tr.Repo, TaskID: tr.TaskID, StepID: tr.StepID, Attempt: tr.Attempt, BaseSHA: tr.BaseSHA, CandidateSHA: tr.CandidateSHA, Kind: tr.Kind, OldBaseSHA: tr.OldBaseSHA}
}
-// closeTransfers ends every transfer of a step attempt: nothing of it is
-// served again and its chunks are gone.
-func (t *txn) closeTransfers(stepID string, attempt int64) error {
+// closeTransfers ends every transfer of a step attempt (of kinds, when
+// given): nothing of it is served again and its chunks are gone.
+func (t *txn) closeTransfers(stepID string, attempt int64, kinds ...string) error {
+ q := t.db.Where("step_id = ? AND attempt = ? AND state <> ?", stepID, attempt, transferClosed)
+ if len(kinds) > 0 {
+ q = q.Where("coalesce(kind, '') IN ?", kinds)
+ }
var trs []transferRecord
- if err := t.db.Where("step_id = ? AND attempt = ? AND state <> ?", stepID, attempt, transferClosed).Find(&trs).Error; err != nil {
+ if err := q.Find(&trs).Error; err != nil {
return err
}
for _, tr := range trs {
@@ -114,9 +119,10 @@ func (t *txn) blob(l Lease, v *wire.Blob) error {
if s.Attempt != tr.Attempt || s.Withdrawn || wire.FinalStage(k.Stage) || k.CancelRequested || tr.Direction == wire.TransferInbound && wire.StepTerminal(s.State) {
return errTransferRefused("attempt not current")
}
- if v.Total > wire.MaxTransferChunks {
+ if v.Total > wire.MaxChunks(tr.Kind) {
// Declared too large to relay: the checks cannot run on that runner,
- // nor Engineering on that Mac.
+ // nor Engineering on that Mac. Each kind has its bounds (a deps
+ // bundle's are its own).
return t.tooLarge(&k, &s, tr)
}
data, err := base64.StdEncoding.DecodeString(v.Data)
@@ -126,7 +132,7 @@ func (t *txn) blob(l Lease, v *wire.Blob) error {
if tr.Received > 0 && (v.Total != tr.Total || v.SHA256 != tr.SHA256) || v.Index != tr.Received {
return errTransferRefused("chunk out of order")
}
- if tr.Bytes+int64(len(data)) > wire.MaxTransferBytes {
+ if tr.Bytes+int64(len(data)) > wire.MaxBytes(tr.Kind) {
return t.tooLarge(&k, &s, tr)
}
tr.Total, tr.SHA256, tr.Received, tr.Bytes = v.Total, v.SHA256, tr.Received+1, tr.Bytes+int64(len(data))
@@ -146,7 +152,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), and Engineering on a Mac ends
+// not run (checks_unavailable, or deps_too_large for a hosted attempt's
+// dependency bundle), and Engineering on a Mac ends
// workspace_too_large with Needs you (it never runs on Linux instead).
// Outbound, a worker's commit that cannot reach the primary ends its
// step workspace_too_large too, with Needs you and Retry.
@@ -163,8 +170,11 @@ func (t *txn) tooLarge(k *taskRecord, s *stepRecord, tr transferRecord) error {
if tr.Direction != wire.TransferInbound || wire.StepTerminal(s.State) {
return nil
}
- if tr.Kind == wire.TransferKindEngineering {
+ switch tr.Kind {
+ case wire.TransferKindEngineering:
return t.withdrawFailing(k, s, wire.ReasonWorkspaceTooLarge)
+ case wire.TransferKindDeps:
+ return t.withdrawResolving(k, s, wire.ReasonDepsTooLarge)
}
return t.withdrawResolving(k, s, "checks_unavailable")
}
diff --git a/internal/runner/depsbundle/gittree.go b/internal/runner/depsbundle/gittree.go
new file mode 100644
index 00000000..1e819dc0
--- /dev/null
+++ b/internal/runner/depsbundle/gittree.go
@@ -0,0 +1,80 @@
+package depsbundle
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io/fs"
+ "path"
+ "regexp"
+ "strings"
+ "testing/fstest"
+)
+
+// Git runs git against one repository with args: at most limit bytes of
+// its output, and whether there was more.
+type Git func(ctx context.Context, limit int, args ...string) (out []byte, clipped bool, err error)
+
+// maxTreeListing bounds a commit's recursive tree listing (a repository
+// of about half a million files). Past it is ErrTooLarge.
+const maxTreeListing = 64 << 20
+
+var objectName = regexp.MustCompile(`^[0-9a-f]{40}([0-9a-f]{24})?$`)
+
+// CommitTree is commit's tree as ModulesFor reads it, from git's objects
+// with no checkout: every go.mod and vendor/modules.txt that is a regular
+// file (mode 100644 or 100755) at its path, each go.mod's bytes read when
+// it is opened (only the module directories ModulesFor keeps are read).
+// No other file is there; a symlink is not a file. A listing past
+// maxTreeListing is ErrTooLarge.
+func CommitTree(ctx context.Context, git Git, commit string) (fs.FS, error) {
+ if !objectName.MatchString(commit) {
+ return nil, fmt.Errorf("%w: commit %q", ErrMalformed, commit)
+ }
+ out, clipped, err := git(ctx, maxTreeListing, "ls-tree", "-r", "-z", "--full-tree", "--end-of-options", commit)
+ if err != nil {
+ return nil, err
+ }
+ if clipped {
+ return nil, fmt.Errorf("depsbundle: the tree of %s: %w", commit, ErrTooLarge)
+ }
+ t := gitTree{MapFS: fstest.MapFS{}, objects: map[string]string{}, git: git, ctx: ctx}
+ for _, entry := range bytes.Split(out, []byte{0}) {
+ meta, name, ok := strings.Cut(string(entry), "\t")
+ fields := strings.Fields(meta)
+ if !ok || len(fields) != 3 || fields[1] != "blob" || fields[0] != "100644" && fields[0] != "100755" || !fs.ValidPath(name) {
+ continue
+ }
+ switch {
+ case path.Base(name) == "go.mod":
+ t.objects[name] = fields[2]
+ t.MapFS[name] = &fstest.MapFile{Mode: 0o444}
+ case path.Base(name) == "modules.txt" && path.Base(path.Dir(name)) == "vendor":
+ // Only its presence counts (a vendored module).
+ t.MapFS[name] = &fstest.MapFile{Mode: 0o444}
+ }
+ }
+ return t, nil
+}
+
+// gitTree is CommitTree's fs.FS: the listing, and go.mod bytes read from
+// git on Open.
+type gitTree struct {
+ fstest.MapFS
+ objects map[string]string
+ git Git
+ ctx context.Context
+}
+
+func (t gitTree) Open(name string) (fs.File, error) {
+ object, ok := t.objects[name]
+ if !ok {
+ return t.MapFS.Open(name)
+ }
+ // One byte past ModulesFor's bound, so it sees a go.mod too large.
+ data, _, err := t.git(t.ctx, maxModFile+1, "cat-file", "blob", object)
+ if err != nil {
+ return nil, &fs.PathError{Op: "open", Path: name, Err: err}
+ }
+ return fstest.MapFS{name: &fstest.MapFile{Data: data, Mode: 0o444}}.Open(name)
+}
diff --git a/internal/runner/depsbundle/gittree_test.go b/internal/runner/depsbundle/gittree_test.go
new file mode 100644
index 00000000..d2e396f2
--- /dev/null
+++ b/internal/runner/depsbundle/gittree_test.go
@@ -0,0 +1,70 @@
+package depsbundle
+
+import (
+ "context"
+ "errors"
+ "slices"
+ "strings"
+ "testing"
+)
+
+// TestCommitTree: a commit's tree, from git's listing, as ModulesFor
+// reads it: regular go.mod files (each read when opened), a vendor
+// marker hiding its module, a symlinked go.mod not a file, a listing
+// past its bound ErrTooLarge, and a name that is not a commit refused
+// before git runs.
+func TestCommitTree(t *testing.T) {
+ commit := strings.Repeat("c", 40)
+ blobs := map[string]string{
+ strings.Repeat("1", 40): "module example.com/app\n\nrequire example.com/dep v1.0.0\n",
+ strings.Repeat("2", 40): "module example.com/app/vendored\n\nrequire example.com/vendored v0.1.0\n",
+ strings.Repeat("3", 40): "module example.com/app/linked\n\nrequire example.com/linked v0.2.0\n",
+ strings.Repeat("4", 40): "# example.com/vendored v0.1.0\n",
+ }
+ listing := strings.Join([]string{
+ "100644 blob " + strings.Repeat("1", 40) + "\tgo.mod",
+ "100644 blob " + strings.Repeat("2", 40) + "\tvendored/go.mod",
+ "100644 blob " + strings.Repeat("4", 40) + "\tvendored/vendor/modules.txt",
+ "120000 blob " + strings.Repeat("3", 40) + "\tlinked/go.mod",
+ "100644 blob " + strings.Repeat("5", 40) + "\tREADME.md",
+ }, "\x00") + "\x00"
+ var calls [][]string
+ git := func(_ context.Context, limit int, args ...string) ([]byte, bool, error) {
+ calls = append(calls, args)
+ switch args[0] {
+ case "ls-tree":
+ if args[len(args)-1] != commit {
+ return nil, false, errors.New("listed another commit")
+ }
+ return []byte(listing), false, nil
+ case "cat-file":
+ body, ok := blobs[args[len(args)-1]]
+ if !ok {
+ return nil, false, errors.New("no such blob")
+ }
+ return []byte(body), false, nil
+ }
+ return nil, false, errors.New("unexpected git " + args[0])
+ }
+ tree, err := CommitTree(context.Background(), git, commit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want, err := ModulesFor(tree, tree)
+ if err != nil || !slices.Equal(want, []Module{{"example.com/dep", "v1.0.0"}}) {
+ t.Fatalf("ModulesFor over the commit's tree = %v, %v; want example.com/dep only", want, err)
+ }
+ for _, c := range calls {
+ if c[0] == "cat-file" && c[len(c)-1] != strings.Repeat("1", 40) {
+ t.Fatalf("read %v, which ModulesFor skips", c)
+ }
+ }
+ clipped := func(context.Context, int, ...string) ([]byte, bool, error) { return []byte(listing), true, nil }
+ if _, err := CommitTree(context.Background(), clipped, commit); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("a clipped listing: %v, want ErrTooLarge", err)
+ }
+ calls = nil
+ if _, err := CommitTree(context.Background(), git, "main"); !errors.Is(err, ErrMalformed) || len(calls) != 0 {
+ t.Fatalf("a branch name: %v after %d git runs, want ErrMalformed and none", err, len(calls))
+ }
+}
diff --git a/internal/runner/thin/relay.go b/internal/runner/thin/relay.go
index db64576c..8ab80756 100644
--- a/internal/runner/thin/relay.go
+++ b/internal/runner/thin/relay.go
@@ -11,6 +11,7 @@ import (
"encoding/json"
"errors"
"io"
+ "io/fs"
"log/slog"
"os"
"os/exec"
@@ -20,6 +21,7 @@ import (
"sync"
"time"
+ "amadan.net/oficina/equipo/internal/runner/depsbundle"
"amadan.net/oficina/equipo/internal/runner/forge"
"amadan.net/oficina/equipo/internal/runner/workspace"
"amadan.net/oficina/equipo/internal/wire"
@@ -223,17 +225,25 @@ func (s *State) dropStepChunks(ctx context.Context, step string, attempt int64)
}
// queueUpload puts a pack's chunks in the outbox and marks the upload
-// sent, in one transaction: resent until acked, never built twice.
+// sent, in one transaction: resent until acked, never built twice. A
+// pack past its kind's bound (wire.MaxBytes) is declared instead.
func (s *State) queueUpload(ctx context.Context, h wire.TransferHeader, pack []byte) error {
+ if int64(len(pack)) > wire.MaxBytes(h.Kind) {
+ return s.queueOversize(ctx, h)
+ }
+ return s.queueChunks(ctx, h, pack, (len(pack)+wire.MaxBlobChunk-1)/wire.MaxBlobChunk)
+}
+
+// queueOversize declares a pack too large to relay, sending none of it:
+// one chunk with no data and a total past the kind's chunk bound, which
+// the instance refuses at once (the checks end as not run).
+func (s *State) queueOversize(ctx context.Context, h wire.TransferHeader) error {
+ return s.queueChunks(ctx, h, nil, wire.MaxChunks(h.Kind)+1)
+}
+
+func (s *State) queueChunks(ctx context.Context, h wire.TransferHeader, pack []byte, total int) error {
sum := sha256.Sum256(pack)
digest := hex.EncodeToString(sum[:])
- total := (len(pack) + wire.MaxBlobChunk - 1) / wire.MaxBlobChunk
- if int64(len(pack)) > wire.MaxTransferBytes {
- // Too large to relay: one chunk says so (the instance refuses a
- // total past the bound and the checks end as not run).
- total = wire.MaxTransferChunks + 1
- pack = pack[:wire.MaxBlobChunk]
- }
return s.tx(ctx, func(t *sql.Tx) error {
res, err := t.Exec("UPDATE uploads SET state=? WHERE transfer=? AND state=?", relaySent, h.ID, relayPending)
if err != nil {
@@ -242,7 +252,8 @@ func (s *State) queueUpload(ctx context.Context, h wire.TransferHeader, pack []b
if n, _ := res.RowsAffected(); n != 1 {
return nil
}
- for i := 0; i*wire.MaxBlobChunk < len(pack); i++ {
+ // A declaration (no data, a total past the bound) is one chunk.
+ for i := 0; i*wire.MaxBlobChunk < len(pack) || i == 0 && pack == nil; i++ {
part := pack[i*wire.MaxBlobChunk : min(len(pack), (i+1)*wire.MaxBlobChunk)]
if err := s.enqueue(t, wire.FrameBlob, "", wire.Blob{Transfer: h, Index: i, Total: total, SHA256: digest, Data: base64.StdEncoding.EncodeToString(part)}); err != nil {
return err
@@ -405,6 +416,9 @@ func (x *Relay) Once(ctx context.Context) {
ups, err := x.State.pendingUploads(ctx)
x.log("relay uploads", err)
for _, u := range ups {
+ if u.Deps || u.Transfer.Kind == wire.TransferKindDeps {
+ continue // after every pack, below
+ }
pack, err := x.Engine.packCommits(ctx, u.Transfer)
if err != nil {
x.log("relay pack", err)
@@ -413,6 +427,11 @@ func (x *Relay) Once(ctx context.Context) {
x.log("relay upload", x.State.queueUpload(ctx, u.Transfer, pack))
x.notify()
}
+ for _, u := range ups {
+ if u.Deps || u.Transfer.Kind == wire.TransferKindDeps {
+ x.deps(ctx, u)
+ }
+ }
pubs, err := x.State.openPublications(ctx)
x.log("relay publications", err)
for _, p := range pubs {
@@ -425,6 +444,28 @@ func (x *Relay) Once(ctx context.Context) {
}
}
+// deps answers a hosted attempt's request for its dependency bundle,
+// after the packs: the bundle (depsBundle), or, past its limit, a
+// declaration that sends none of it. A request that is not exactly a deps
+// header asked with Deps is refused and never tried again.
+func (x *Relay) deps(ctx context.Context, u wire.SendPackCommand) {
+ bundle, err := x.Engine.depsBundle(ctx, u)
+ switch {
+ case errors.Is(err, errPackRefused):
+ x.log("relay deps refused", errors.New("not a hosted attempt's bundle request"))
+ x.log("relay upload", x.State.refuseUpload(ctx, u.Transfer.ID))
+ return
+ case errors.Is(err, depsbundle.ErrTooLarge):
+ x.log("relay upload", x.State.queueOversize(ctx, u.Transfer))
+ case err != nil:
+ x.log("relay deps", err)
+ return
+ default:
+ x.log("relay upload", x.State.queueUpload(ctx, u.Transfer, bundle))
+ }
+ x.notify()
+}
+
// workerUploads answers each outbound send_pack from the worker's store:
// the thin pack of a committed attempt's candidate, or, for one it must
// never send, a refusal that stops it being tried again.
@@ -502,7 +543,7 @@ func (e *Engineer) prepareBase(ctx context.Context, c wire.PrepareBaseCommand) (
// 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()
- // A deps transfer is a dependency bundle, never a git pack (Task 23).
+ // A deps transfer is a dependency bundle, never a git pack (depsBundle).
if !forgekey.ValidHub(h.Repo) || !h.Valid() || h.Kind == wire.TransferKindDeps || len(commits) == 0 {
return nil, errPackRefused
}
@@ -547,6 +588,58 @@ func (e *Engineer) packCommits(ctx context.Context, h wire.TransferHeader) ([]by
return out.Bytes(), nil
}
+// depsBundle is a hosted attempt's dependency bundle: every module the
+// base's and the candidate's go.mod files require (depsbundle.ModulesFor,
+// over their trees in the clone), from this runner's module cache as its
+// own checks use it, within depsBundleLimit. Too many modules, or a
+// bundle past the limit, is depsbundle.ErrTooLarge. A go.mod that does
+// not parse gives an empty bundle: the hosted worker reaches its own
+// verdict, as a personal runner's checks would. A request that is not a
+// valid deps header asked with Deps, for commits the clone has, is
+// refused before anything is read.
+func (e *Engineer) depsBundle(ctx context.Context, u wire.SendPackCommand) ([]byte, error) {
+ h := u.Transfer
+ if !u.Deps || h.Kind != wire.TransferKindDeps || !h.Valid() || !forgekey.ValidHub(h.Repo) {
+ return nil, errPackRefused
+ }
+ ctx, cancel := context.WithTimeout(ctx, prepTimeout)
+ defer cancel()
+ if err := e.fetch(ctx, h.Repo); err != nil {
+ return nil, err
+ }
+ git := func(ctx context.Context, limit int, args ...string) ([]byte, bool, error) {
+ cmd := groupCommand(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + e.Clones.Path(h.Repo)}, args...)...)
+ for k, v := range workspace.GitEnvironment() {
+ cmd.Env = append(cmd.Env, k+"="+v)
+ }
+ cmd.Env = append(cmd.Env, "HOME=/nonexistent")
+ return boundedOutput(cmd, limit)
+ }
+ var trees [2]fs.FS
+ for i, c := range []string{h.BaseSHA, h.CandidateSHA} {
+ if !e.hasCommit(ctx, h.Repo, c) {
+ return nil, errPackRefused
+ }
+ tree, err := depsbundle.CommitTree(ctx, git, c)
+ if err != nil {
+ return nil, err
+ }
+ trees[i] = tree
+ }
+ want, err := depsbundle.ModulesFor(trees[0], trees[1])
+ if errors.Is(err, depsbundle.ErrMalformed) {
+ want, err = nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ b, err := depsbundle.Build(ctx, firstNonEmpty(e.O.Runner.ModuleCache, homeModuleCache()), want, depsBundleLimit)
+ if err != nil {
+ return nil, err
+ }
+ return b.Bytes(), nil
+}
+
// limitWriter keeps at most n bytes and drops the rest (the caller sees
// a pack past the bound by its length).
type limitWriter struct {
@@ -570,6 +663,10 @@ func (l *limitWriter) Write(p []byte) (int, error) {
return len(p), nil
}
+// depsBundleLimit is the most a dependency bundle may be (tests lower
+// it).
+var depsBundleLimit int64 = wire.DepsTransferMax
+
// relayFault, in tests, stops a publication at a named point ("indexed",
// "pushed"), as a crash there would.
var relayFault func(point string) bool
diff --git a/internal/runner/thin/relay_test.go b/internal/runner/thin/relay_test.go
index 4cbaea8c..29266af7 100644
--- a/internal/runner/thin/relay_test.go
+++ b/internal/runner/thin/relay_test.go
@@ -1,20 +1,30 @@
package thin
import (
+ "archive/tar"
+ "bytes"
"context"
"crypto/sha256"
+ "database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
+ "io"
+ "log/slog"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
+ "time"
+ "amadan.net/oficina/equipo/internal/equipo/chat"
"amadan.net/oficina/equipo/internal/runner/workspace"
"amadan.net/oficina/equipo/internal/wire"
+ "amadan.net/rastrillo/rastrillo/db"
+ "golang.org/x/mod/module"
+ "gorm.io/gorm"
)
// pushForge is a bare remote on disk; fail makes the next pushes fail.
@@ -289,3 +299,464 @@ func TestRelayDeclaresOversize(t *testing.T) {
t.Fatalf("the receiver took a declared oversize: %v", err)
}
}
+
+// Hosted slice 2, Task 23: the primary sends a hosted attempt's
+// dependency bundle, built from its own module cache for the modules the
+// base's and the candidate's go.mod files require, under the deps
+// transfer the instance made, after the hosted pack.
+
+// cacheModule is one module in a test module cache: its zip is size
+// bytes (a sparse file, so a large one costs no disk).
+type cacheModule struct {
+ path, version string
+ zip int64
+}
+
+// moduleCache writes mods under cache/download in dir, as the go
+// command lays them out.
+func moduleCache(t *testing.T, dir string, mods ...cacheModule) {
+ t.Helper()
+ for _, m := range mods {
+ esc, err := module.EscapePath(m.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ at := filepath.Join(dir, "cache", "download", filepath.FromSlash(esc), "@v")
+ if err := os.MkdirAll(at, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ os.WriteFile(filepath.Join(at, m.version+".mod"), []byte("module "+m.path+"\n"), 0o644)
+ os.WriteFile(filepath.Join(at, m.version+".info"), []byte(`{"Version":"`+m.version+`"}`), 0o644)
+ f, err := os.Create(filepath.Join(at, m.version+".zip"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.WriteString("PK zip of " + m.path)
+ if err := f.Truncate(max(m.zip, 32)); err != nil {
+ t.Fatal(err)
+ }
+ f.Close()
+ }
+}
+
+// candidateGoMod is depsRig's candidate go.mod: the base's and one
+// module more.
+const candidateGoMod = "module example.com/app\n\ngo 1.26\n\nrequire (\n\texample.com/alpha v1.0.0\n\texample.com/gamma v0.3.0\n)\n"
+
+// depsRig is a relay rig whose remote has a base on main with go.mod
+// files and a candidate on the task branch that requires one module
+// more, and a module cache holding each module (zip bytes each).
+func depsRig(t *testing.T, zip int64) (r *relayRig, pack, deps wire.TransferHeader) {
+ return depsRigWith(t, zip, candidateGoMod)
+}
+
+// depsRigWith is depsRig whose candidate's go.mod is gomod.
+func depsRigWith(t *testing.T, zip int64, gomod string) (r *relayRig, pack, deps wire.TransferHeader) {
+ t.Helper()
+ r = newRelayRig(t)
+ work := filepath.Join(r.root, "gomod")
+ gitOut(t, r.root, "init", "-q", "-b", "main", work)
+ write := func(name, text string) {
+ os.MkdirAll(filepath.Dir(filepath.Join(work, name)), 0o755)
+ os.WriteFile(filepath.Join(work, name), []byte(text), 0o644)
+ }
+ write("go.mod", "module example.com/app\n\ngo 1.26\n\nrequire example.com/alpha v1.0.0\n")
+ write("tools/go.mod", "module example.com/app/tools\n\ngo 1.26\n\nrequire example.com/beta v1.2.0\n")
+ // Go ignores testdata: its requirement is never bundled.
+ write("testdata/go.mod", "module example.com/fixture\n\ngo 1.26\n\nrequire example.com/ignored v0.1.0\n")
+ gitOut(t, work, "add", "-A")
+ gitOut(t, work, "commit", "-q", "-m", "base")
+ base := gitOut(t, work, "rev-parse", "HEAD")
+ gitOut(t, work, "checkout", "-q", "-b", relayBranch)
+ write("go.mod", gomod)
+ gitOut(t, work, "add", "-A")
+ gitOut(t, work, "commit", "-q", "-m", "candidate")
+ candidate := gitOut(t, work, "rev-parse", "HEAD")
+ remote := filepath.Join(r.root, "gomod.git")
+ gitOut(t, r.root, "clone", "-q", "--bare", "--no-single-branch", work, remote)
+ r.f.dir = remote
+ cache := filepath.Join(r.root, "gomodcache")
+ moduleCache(t, cache, cacheModule{"example.com/alpha", "v1.0.0", zip}, cacheModule{"example.com/beta", "v1.2.0", 64}, cacheModule{"example.com/gamma", "v0.3.0", 64}, cacheModule{"example.com/ignored", "v0.1.0", 64})
+ r.e.O.Runner.ModuleCache = cache
+ pack = wire.TransferHeader{ID: "tr_pack", Direction: wire.TransferInbound, Kind: wire.TransferKindHostedPack, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: base, CandidateSHA: candidate}
+ deps = pack
+ deps.ID, deps.Kind = "tr_deps", wire.TransferKindDeps
+ return r, pack, deps
+}
+
+// outboxBlobs are the blobs the primary queued, in order.
+func outboxBlobs(t *testing.T, s *State) []wire.Blob {
+ t.Helper()
+ var out []wire.Blob
+ after := int64(0)
+ for {
+ frames, last, err := s.Unacked(context.Background(), after)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range frames {
+ if f.Type != wire.FrameBlob {
+ continue
+ }
+ var b wire.Blob
+ if err := json.Unmarshal(f.Data, &b); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, b)
+ }
+ if last == after {
+ return out
+ }
+ after = last
+ }
+}
+
+func uploadState(t *testing.T, s *State, transfer string) string {
+ t.Helper()
+ var state string
+ if err := s.db.QueryRow("SELECT state FROM uploads WHERE transfer=?", transfer).Scan(&state); err != nil {
+ t.Fatal(err)
+ }
+ return state
+}
+
+// tarFiles reads a bundle's entries, in order, name to content.
+func tarFiles(t *testing.T, bundle []byte) ([]string, map[string][]byte) {
+ t.Helper()
+ tr := tar.NewReader(bytes.NewReader(bundle))
+ var names []string
+ files := map[string][]byte{}
+ for {
+ h, err := tr.Next()
+ if errors.Is(err, io.EOF) {
+ return names, files
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := io.ReadAll(tr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ names, files[h.Name] = append(names, h.Name), data
+ }
+}
+
+// TestPrimarySendsBundleForHostedStep: asked for a hosted attempt's pack
+// and its bundle (the bundle's send_pack first), the primary uploads the
+// pack and then the bundle under the deps transfer: MODULES lists every
+// requirement of the base's and the candidate's go.mod files (testdata
+// skipped), and each module's files come from its module cache.
+func TestPrimarySendsBundleForHostedStep(t *testing.T) {
+ r, pack, deps := depsRig(t, 4096)
+ ctx := context.Background()
+ if err := r.e.O.State.AcceptUpload(ctx, "sp-deps", wire.SendPackCommand{Transfer: deps, Have: []string{}, Deps: true}); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.e.O.State.AcceptUpload(ctx, "sp-pack", wire.SendPackCommand{Transfer: pack, Have: []string{}}); err != nil {
+ t.Fatal(err)
+ }
+ r.relay.Once(ctx)
+ blobs := outboxBlobs(t, r.e.O.State)
+ var bundle []byte
+ seenDeps := false
+ for _, b := range blobs {
+ switch b.Transfer {
+ case pack:
+ if seenDeps {
+ t.Fatal("a hosted pack chunk after the bundle's")
+ }
+ case deps:
+ seenDeps = true
+ data, _ := base64.StdEncoding.DecodeString(b.Data)
+ bundle = append(bundle, data...)
+ default:
+ t.Fatalf("a blob under %+v", b.Transfer)
+ }
+ }
+ if !seenDeps || uploadState(t, r.e.O.State, deps.ID) != relaySent || uploadState(t, r.e.O.State, pack.ID) != relaySent {
+ t.Fatalf("bundle sent %v; uploads %s and %s", seenDeps, uploadState(t, r.e.O.State, pack.ID), uploadState(t, r.e.O.State, deps.ID))
+ }
+ names, files := tarFiles(t, bundle)
+ if len(names) == 0 || names[0] != "MODULES" {
+ t.Fatalf("bundle entries %v, want MODULES first", names)
+ }
+ if got, want := string(files["MODULES"]), "example.com/alpha v1.0.0\nexample.com/beta v1.2.0\nexample.com/gamma v0.3.0\n"; got != want {
+ t.Fatalf("MODULES %q, want %q", got, want)
+ }
+ for _, m := range []string{"example.com/alpha/@v/v1.0.0", "example.com/beta/@v/v1.2.0", "example.com/gamma/@v/v0.3.0"} {
+ for _, ext := range []string{".mod", ".zip", ".info"} {
+ want, err := os.ReadFile(filepath.Join(r.e.O.Runner.ModuleCache, "cache", "download", filepath.FromSlash(m+ext)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, ok := files["cache/download/"+m+ext]; !ok || !bytes.Equal(got, want) {
+ t.Fatalf("bundle's %s: %d bytes (present %v), want the cache's %d", m+ext, len(got), ok, len(want))
+ }
+ }
+ }
+ if _, ok := files["cache/download/example.com/ignored/@v/v0.1.0.mod"]; ok {
+ t.Fatal("a testdata module's requirement was bundled")
+ }
+}
+
+// TestPrimarySendsBundleMalformedGoMod: a candidate go.mod that does not
+// parse still gets a bundle, an empty one (MODULES and nothing else): the
+// hosted worker's own checks then fail as a personal runner's would,
+// instead of the step waiting for a bundle that never comes.
+func TestPrimarySendsBundleMalformedGoMod(t *testing.T) {
+ r, _, deps := depsRigWith(t, 64, "module example.com/app\n\nrequire example.com/alpha\n")
+ ctx := context.Background()
+ if err := r.e.O.State.AcceptUpload(ctx, "sp-deps", wire.SendPackCommand{Transfer: deps, Have: []string{}, Deps: true}); err != nil {
+ t.Fatal(err)
+ }
+ r.relay.Once(ctx)
+ var bundle []byte
+ for _, b := range outboxBlobs(t, r.e.O.State) {
+ data, _ := base64.StdEncoding.DecodeString(b.Data)
+ bundle = append(bundle, data...)
+ }
+ if names, files := tarFiles(t, bundle); len(names) != 1 || names[0] != "MODULES" || len(files["MODULES"]) != 0 || uploadState(t, r.e.O.State, deps.ID) != relaySent {
+ t.Fatalf("bundle for a malformed go.mod: entries %v, upload %s; want an empty MODULES, sent", names, uploadState(t, r.e.O.State, deps.ID))
+ }
+}
+
+// TestNoBundleForPersonalWorker: a checks transfer's send_pack (a
+// personal worker's) gets the candidate's pack and no bundle; a request
+// for the bundle under any header but a deps one, or a deps header not
+// asked with Deps, is refused and sends nothing.
+func TestNoBundleForPersonalWorker(t *testing.T) {
+ r, pack, deps := depsRig(t, 64)
+ ctx := context.Background()
+ checks := wire.TransferHeader{ID: "tr_checks", Direction: wire.TransferInbound, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: pack.BaseSHA, CandidateSHA: pack.CandidateSHA}
+ if err := r.e.O.State.AcceptUpload(ctx, "sp-checks", wire.SendPackCommand{Transfer: checks, Have: []string{}}); err != nil {
+ t.Fatal(err)
+ }
+ asked := []wire.SendPackCommand{{Transfer: deps, Have: []string{}}}
+ for i, h := range []wire.TransferHeader{checks, pack} {
+ h.ID = "tr_wrong_" + itoa(int64(i))
+ asked = append(asked, wire.SendPackCommand{Transfer: h, Have: []string{}, Deps: true})
+ }
+ for i, c := range asked {
+ if err := r.e.O.State.AcceptUpload(ctx, "sp-"+itoa(int64(i)), c); err != nil {
+ t.Fatal(err)
+ }
+ }
+ r.relay.Once(ctx)
+ for _, b := range outboxBlobs(t, r.e.O.State) {
+ if b.Transfer != checks {
+ t.Fatalf("a blob under %+v, want only the checks pack", b.Transfer)
+ }
+ }
+ for _, c := range asked {
+ if got := uploadState(t, r.e.O.State, c.Transfer.ID); got != relayRefused {
+ t.Errorf("send_pack %s (%s, deps %v) is %s, want refused", c.Transfer.ID, c.Transfer.Kind, c.Deps, got)
+ }
+ }
+}
+
+// TestBundleTooLargeEndsStep: a bundle past its limit is never sent: one
+// chunk with no data declares a total past the deps chunk bound, which
+// the receiver refuses (the instance ends the checks deps_too_large).
+func TestBundleTooLargeEndsStep(t *testing.T) {
+ r, _, deps := depsRig(t, 8192)
+ ctx := context.Background()
+ defer func(was int64) { depsBundleLimit = was }(depsBundleLimit)
+ depsBundleLimit = 4096
+ if err := r.e.O.State.AcceptUpload(ctx, "sp-deps", wire.SendPackCommand{Transfer: deps, Have: []string{}, Deps: true}); err != nil {
+ t.Fatal(err)
+ }
+ r.relay.Once(ctx)
+ blobs := outboxBlobs(t, r.e.O.State)
+ if len(blobs) != 1 || blobs[0].Transfer != deps || blobs[0].Total != wire.MaxChunks(wire.TransferKindDeps)+1 || blobs[0].Data != "" {
+ var first wire.Blob
+ if len(blobs) > 0 {
+ first = blobs[0]
+ }
+ t.Fatalf("an oversize bundle sent %d chunks, the first declaring %d with %d bytes of data; want one declaring %d chunks with no data", len(blobs), first.Total, len(first.Data), wire.MaxChunks(wire.TransferKindDeps)+1)
+ }
+ if err := r.e.O.State.AcceptChunk(ctx, "in-1", blobs[0]); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.e.O.State.pack(ctx, deps); !errors.Is(err, errPackRefused) {
+ t.Fatalf("the receiver took a declared oversize bundle: %v", err)
+ }
+}
+
+// TestDepsTransferAbove64MiB: a 100 MiB bundle travels end to end, in
+// process: the primary's relay builds and chunks it, the instance's store
+// relays every chunk to the hosted VM's runner, and the worker reassembles
+// it under the deps transfer, past every kind's 64 MiB. A 257 MiB one is
+// refused at the header: the primary declares it, the instance relays
+// nothing and the checks end cannot_run deps_too_large.
+func TestDepsTransferAbove64MiB(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ zip int64
+ fits bool
+ }{{"100 MiB", 100 << 20, true}, {"257 MiB", 257 << 20, false}} {
+ t.Run(c.name, func(t *testing.T) {
+ ctx := context.Background()
+ r, _, deps := depsRig(t, c.zip)
+ in := depsInstance(t, deps)
+ worker, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { worker.Close() })
+ // Durability is not what this measures: no fsync per chunk.
+ for _, db := range []*sql.DB{r.e.O.State.db, worker.db, in.d.Writer()} {
+ if _, err := db.Exec("PRAGMA synchronous=OFF"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := r.e.O.State.AcceptUpload(ctx, "sp-deps", wire.SendPackCommand{Transfer: deps, Have: []string{}, Deps: true}); err != nil {
+ t.Fatal(err)
+ }
+ r.relay.Once(ctx)
+ // Primary to instance: every chunk applied, then acked.
+ sent, digest := 0, ""
+ for after := int64(0); ; {
+ frames, last, err := r.e.O.State.Unacked(ctx, after)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range frames {
+ var b wire.Blob
+ if err := json.Unmarshal(f.Data, &b); err != nil {
+ t.Fatal(err)
+ }
+ if c.fits && b.Total > wire.MaxChunks(wire.TransferKindDeps) || !c.fits && b.Total <= wire.MaxChunks(wire.TransferKindDeps) {
+ t.Fatalf("chunk %d declares %d chunks (deps bound %d)", b.Index, b.Total, wire.MaxChunks(wire.TransferKindDeps))
+ }
+ if err := in.s.Apply(ctx, in.lease("P1", wire.RolePrimary), f, &b); err != nil {
+ t.Fatalf("the instance refused chunk %d of %d: %v", b.Index, b.Total, err)
+ }
+ if err := r.e.O.State.Acked(ctx, f.ID); err != nil {
+ t.Fatal(err)
+ }
+ sent, digest = sent+1, b.SHA256
+ }
+ if last == after {
+ break
+ }
+ after = last
+ }
+ // Instance to the hosted VM's runner: each chunk kept, then acked.
+ relayed := 0
+ for after := int64(0); ; {
+ frames, last, err := in.s.Pending(ctx, in.lease("H1", wire.RoleWorker), after)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range frames {
+ if f.Type != wire.FrameBlob {
+ continue
+ }
+ var b wire.Blob
+ if err := json.Unmarshal(f.Data, &b); err != nil {
+ t.Fatal(err)
+ }
+ if err := worker.AcceptChunk(ctx, f.ID, b); err != nil {
+ t.Fatal(err)
+ }
+ ack, _ := wire.NewFrame("ack-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID})
+ if err := in.s.Apply(ctx, in.lease("H1", wire.RoleWorker), ack, &wire.Ack{ID: f.ID}); err != nil {
+ t.Fatal(err)
+ }
+ relayed++
+ }
+ if last == after {
+ break
+ }
+ after = last
+ }
+ if !c.fits {
+ var step struct{ State, Checks, Reason string }
+ in.must(in.d.G.Raw("SELECT state, checks, reason FROM chat_steps WHERE id = 's1'").Scan(&step).Error)
+ if sent != 1 || relayed != 0 || in.transferState(deps.ID) != "closed" || step.State != wire.StepDone || step.Checks != wire.ChecksCannotRun || step.Reason != wire.ReasonDepsTooLarge {
+ t.Fatalf("257 MiB: sent %d, relayed %d, transfer %s, checks %+v; want one declaring chunk, nothing relayed, cannot_run deps_too_large", sent, relayed, in.transferState(deps.ID), step)
+ }
+ return
+ }
+ bundle, err := worker.pack(ctx, deps)
+ if err != nil {
+ t.Fatalf("the worker's assembly of %d chunks: %v", relayed, err)
+ }
+ if sum := sha256.Sum256(bundle); int64(len(bundle)) <= c.zip || hex.EncodeToString(sum[:]) != digest || relayed != sent || sent <= wire.MaxTransferChunks {
+ t.Fatalf("bundle of %d bytes in %d chunks (relayed %d), want past %d bytes and the primary's digest", len(bundle), sent, relayed, c.zip)
+ }
+ if in.transferState(deps.ID) != "closed" {
+ t.Fatalf("deps transfer %s after the last ack, want closed", in.transferState(deps.ID))
+ }
+ })
+ }
+}
+
+// depsRelayInstance is an instance's chat store holding one hosted checks
+// step on H1, placed by P1's primary, with the deps transfer h open.
+type depsRelayInstance struct {
+ t *testing.T
+ d *db.DB
+ s *chat.Store
+}
+
+func (in *depsRelayInstance) must(err error) {
+ in.t.Helper()
+ if err != nil {
+ in.t.Fatal(err)
+ }
+}
+
+func (in *depsRelayInstance) lease(runner, role string) chat.Lease {
+ return chat.Lease{Runner: chat.RunnerPrincipal{RunnerID: runner, Person: "p@x"}, Generation: 1, Process: "p", Protocol: wire.ProtocolHostedRunners, Role: role}
+}
+
+func (in *depsRelayInstance) transferState(id string) string {
+ in.t.Helper()
+ var state string
+ in.must(in.d.G.Raw("SELECT state FROM runner_transfers WHERE id = ?", id).Scan(&state).Error)
+ return state
+}
+
+func depsInstance(t *testing.T, h wire.TransferHeader) *depsRelayInstance {
+ t.Helper()
+ d, err := db.Open(filepath.Join(t.TempDir(), "instance.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = d.Close() })
+ in := &depsRelayInstance{t: t, d: d}
+ in.must(d.G.AutoMigrate(chat.Models...))
+ now := time.Now().UTC()
+ for _, q := range []struct {
+ sql string
+ args []any
+ }{
+ {"CREATE TABLE members (address text PRIMARY KEY, active integer, role text)", nil},
+ {"CREATE TABLE teams (id text PRIMARY KEY)", nil},
+ {"INSERT INTO teams(id) VALUES ('TEAM1')", nil},
+ {"INSERT INTO members(address, active, role) VALUES ('p@x', 1, 'owner')", nil},
+ {"INSERT INTO chat_projects(id, repo, state, revision) VALUES ('p1', ?, 'active', 1)", []any{h.Repo}},
+ {"INSERT INTO chat_tasks(id, project_id, title, stage, creator, revision, created_at, updated_at, branch, base_sha) VALUES (?, 'p1', 'Checks', ?, 'p@x', 1, ?, ?, ?, ?)", []any{h.TaskID, wire.StageInReview, now, now, relayBranch, h.BaseSHA}},
+ {"INSERT INTO chat_steps(id, task_id, idx, person, state, attempt, specialist, runner_id, on_worker, base_sha, candidate_sha, revision, created_at, updated_at) VALUES (?, ?, 1, 'p@x', ?, ?, ?, 'H1', 1, ?, ?, 1, ?, ?)", []any{h.StepID, h.TaskID, wire.StepQueued, h.Attempt, wire.SpecialistChecks, h.BaseSHA, h.CandidateSHA, now, now}},
+ {"INSERT INTO runner_transfers(id, person, from_runner, to_runner, repo, task_id, step_id, attempt, base_sha, candidate_sha, kind, old_base_sha, direction, state, sha256, total, received, bytes, expires_at, created_at) VALUES (?, 'p@x', 'P1', 'H1', ?, ?, ?, ?, ?, ?, ?, '', ?, 'open', '', 0, 0, 0, ?, ?)", []any{h.ID, h.Repo, h.TaskID, h.StepID, h.Attempt, h.BaseSHA, h.CandidateSHA, h.Kind, h.Direction, now.Add(wire.TransferTTL), now}},
+ {"INSERT INTO runner_sessions(runner_id, generation, connected, process, revision, hello, seen_at, protocol) VALUES ('P1', 1, 1, 'p', 1, '', ?, ?), ('H1', 1, 1, 'p', 1, '', ?, ?)", []any{now, wire.ProtocolHostedRunners, now, wire.ProtocolHostedRunners}},
+ } {
+ in.must(d.G.Exec(q.sql, q.args...).Error)
+ }
+ in.s = chat.NewStore(d, chat.Authority{
+ Copy: func(k string) string { return k },
+ Audit: func(*gorm.DB, string, string, string) error { return nil },
+ CurrentPerson: func(context.Context, *gorm.DB) error { return nil },
+ CurrentRunner: func(*gorm.DB, chat.RunnerPrincipal) error { return nil },
+ PrimaryRunner: func(*gorm.DB, string) (string, error) { return "P1", nil },
+ RunnerRole: func(_ *gorm.DB, id string) (string, error) {
+ if id == "H1" {
+ return wire.RoleWorker, nil
+ }
+ return wire.RolePrimary, nil
+ },
+ }, nil)
+ return in
+}
diff --git a/internal/wire/hosted.go b/internal/wire/hosted.go
index 39eb9774..feeed286 100644
--- a/internal/wire/hosted.go
+++ b/internal/wire/hosted.go
@@ -86,8 +86,9 @@ func (h TransferHeader) hostedTransfer() bool {
}
// downgradeHostedRunners refuses a hosted_pack or deps transfer's chunk or
-// pack request below ProtocolHostedRunners, rather than drop its kind and
-// send it as a checks transfer.
+// pack request, and any request for the bundle (SendPackCommand.Deps),
+// below ProtocolHostedRunners, rather than drop its kind or the request
+// and send it as a checks transfer.
func downgradeHostedRunners(body any, protocol int) error {
if protocol >= ProtocolHostedRunners {
return nil
@@ -101,7 +102,7 @@ func downgradeHostedRunners(body any, protocol int) error {
default:
return nil
}
- if h.hostedTransfer() {
+ if sp, ok := body.(*SendPackCommand); h.hostedTransfer() || ok && sp.Deps {
return fmt.Errorf("%w: a %s transfer at protocol %d", ErrProtocol, h.Kind, protocol)
}
return nil
diff --git a/internal/wire/hosted_test.go b/internal/wire/hosted_test.go
index c95eb01c..fd580573 100644
--- a/internal/wire/hosted_test.go
+++ b/internal/wire/hosted_test.go
@@ -86,6 +86,22 @@ func TestHostedKindsNeedProtocol(t *testing.T) {
if same, err := wire.Encode(checks, 38); err != nil || !bytes.Equal(same.Data, checks.Data) {
t.Fatalf("checks blob at 38: %v %s", err, same.Data)
}
+ // A request for the dependency bundle (Task 23) is refused below the
+ // protocol whatever its header, and the checks send_pack keeps its
+ // bytes (no deps key).
+ plain := wire.SendPackCommand{Transfer: wire.TransferHeader{ID: "tr_3", Direction: wire.TransferInbound, CandidateSHA: sha}, Have: []string{}}
+ asked := plain
+ asked.Deps = true
+ deps, _ := wire.NewFrame("sp", wire.FrameSendPack, asked)
+ if got, err := wire.Encode(deps, 38); !errors.Is(err, wire.ErrProtocol) || got.Data != nil {
+ t.Errorf("a deps send_pack at 38 = (%s, %v), want ErrProtocol", got.Data, err)
+ }
+ if !bytes.Contains(deps.Data, []byte(`"deps":true`)) {
+ t.Errorf("deps send_pack %s, want the deps key", deps.Data)
+ }
+ if f, _ := wire.NewFrame("sp", wire.FrameSendPack, plain); bytes.Contains(f.Data, []byte(`"deps"`)) {
+ t.Errorf("checks send_pack %s carries the deps key", f.Data)
+ }
}
func TestHostedEnrolWireNames(t *testing.T) {
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index 4e4a7fb3..1ee28866 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -657,10 +657,12 @@ type Blob struct {
// SendPackCommand asks the primary for the pack of the header's Commits,
// which it uploads as the transfer's blobs (Have: commits the receiver
// holds). A hosted_pack (ProtocolHostedRunners) asks for the base and the
-// candidate; Encode refuses it below that protocol.
+// candidate; Encode refuses it below that protocol. Deps (the same
+// protocol) asks, under a deps header, for the dependency bundle instead.
type SendPackCommand struct {
Transfer TransferHeader `json:"transfer"`
Have []string `json:"have"`
+ Deps bool `json:"deps,omitempty"`
}
// PublishCommand asks the primary to push a worker's commit, received in