carlos / platform Public

carlos run: rootfs rows run in their image; --version runs a staged build

The console admits a rootfs record (which never hibernates) on a
platform box and keeps the fleet refusal for every record (D4); a
meta.version is checked (RFS-3-C19, C20) and written to request.json
and the run-start row. The box hands req.Version to RunCmd and reports
ErrCmdVersion as refused version (RFS-3-C22); the CLI sends --version
(RFS-3-C17, usage RFS-3-C18) and exits 3 with RFS-3-C21. The keyed
create's digest covers a named build and is unchanged without one.
docs/site/cli.md carries RFS-3-C26 to C28. The run gate honours the
pinned runCopySuperseded (RUN-C47 by RFS-3-C18) [pf 8.4].
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 56cc06aa7451f9d0f610f7c60f69f0cbf2620ac8 parent 6c6f860
14 files changed, +332 −16
  • approved_rootfs_copy_test.go +4 −0
  • approved_run_copy_test.go +59 −2
  • docs/site/cli.md +4 −0
  • internal/console/apiruns.go +41 −4
  • internal/console/apiruns_rootfs_test.go +98 −0
  • internal/host/runevents.go +2 −0
  • internal/host/runexec.go +9 −5
  • internal/host/runexec_linux_test.go +23 −0
  • internal/host/runexec_test.go +27 −0
  • internal/runs/keys.go +9 −2
  • internal/runs/keys_test.go +6 −0
  • internal/runs/runs.go +11 −0
  • run.go +7 −3
  • run_test.go +32 −0
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go
index 7794547bc..b3865b198 100644
--- a/approved_rootfs_copy_test.go
+++ b/approved_rootfs_copy_test.go
@@ -187,6 +187,10 @@ var rootfsCopyBuilt = []string{
// Plan 3 Task 8: the resident restart event (internal/rolloutwords/words.go)
// and the resident backoff's 503 body (internal/activator/activator.go)
"RFS-3-C11", "RFS-3-C16",
+ // Plan 3 Task 12: carlos run on rootfs rows and --version (run.go,
+ // internal/console/apiruns.go, internal/host/runevents.go,
+ // docs/site/cli.md)
+ "RFS-3-C17", "RFS-3-C18", "RFS-3-C19", "RFS-3-C20", "RFS-3-C21", "RFS-3-C22", "RFS-3-C26", "RFS-3-C27", "RFS-3-C28",
}
func mustParseRootfsRecord(t *testing.T) []copyRow {
diff --git a/approved_run_copy_test.go b/approved_run_copy_test.go
index 7a8a66a0c..628865fb5 100644
--- a/approved_run_copy_test.go
+++ b/approved_run_copy_test.go
@@ -35,6 +35,49 @@ var runCopyIDs = func() []string {
// task that writes a row's text adds its id here in the same commit.
var runCopyBuilt = []string{"RUN-C1", "RUN-C2", "RUN-C3", "RUN-C4", "RUN-C5", "RUN-C6", "RUN-C7", "RUN-C8", "RUN-C9", "RUN-C10", "RUN-C11", "RUN-C12", "RUN-C13", "RUN-C14", "RUN-C15", "RUN-C16", "RUN-C17", "RUN-C18", "RUN-C19", "RUN-C20", "RUN-C21", "RUN-C22", "RUN-C23", "RUN-C24", "RUN-C25", "RUN-C26", "RUN-C27", "RUN-C28", "RUN-C29", "RUN-C30", "RUN-C31", "RUN-C32", "RUN-C33", "RUN-C34", "RUN-C35", "RUN-C36", "RUN-C37", "RUN-C38", "RUN-C39", "RUN-C40", "RUN-C41", "RUN-C42", "RUN-C43", "RUN-C44", "RUN-C45", "RUN-C46", "RUN-C47", "RUN-C48", "RUN-C49", "RUN-C50", "RUN-C51", "RUN-C52", "RUN-C53", "RUN-C54", "RUN-C55", "RUN-C56", "RUN-C57", "RUN-C58", "RUN-C59", "RUN-C60", "RUN-C61", "RUN-C62", "RUN-C63", "RUN-C64", "RUN-C65", "RUN-C66", "RUN-C67", "RUN-C68", "RUN-C69", "RUN-C70", "RUN-C71", "RUN-C72", "RUN-C73", "RUN-C74", "RUN-C75", "RUN-C76", "RUN-C77", "RUN-C78", "RUN-C79", "RUN-C80", "RUN-C81", "RUN-C82", "RUN-C83", "RUN-C84", "RUN-C85", "RUN-C86", "RUN-C87"}
+// runCopySuperseded is every run-deck id whose text a later deck's built
+// row replaces, pinned, with the id that replaces it. The run deck has no
+// struck status, so the run gate reads this instead [Plan 3 pf 8.4]: a
+// superseded id is not checked as applied, and counts as built while its
+// replacing id is built and applied in its own deck's gate.
+var runCopySuperseded = map[string]string{"RUN-C47": "RFS-3-C18"}
+
+// runBuiltLive is runCopyBuilt without the superseded ids.
+func runBuiltLive() []string {
+ var out []string
+ for _, id := range runCopyBuilt {
+ if _, gone := runCopySuperseded[id]; !gone {
+ out = append(out, id)
+ }
+ }
+ return out
+}
+
+// runSupersessionProblems is why a superseded id does not count as built:
+// its replacing id is not in rootfsCopyBuilt, or is not applied.
+func runSupersessionProblems(t *testing.T, id string) []string {
+ t.Helper()
+ by, ok := runCopySuperseded[id]
+ if !ok {
+ return []string{fmt.Sprintf("%s is not superseded", id)}
+ }
+ var built bool
+ for _, b := range rootfsCopyBuilt {
+ built = built || b == by
+ }
+ if !built {
+ return []string{fmt.Sprintf("%s is superseded by %s, which is not built", id, by)}
+ }
+ rows := builtRows(mustParseRootfsRecord(t), []string{by})
+ for i := range rows {
+ rows[i].Text = rootfsAppliedText(rows[i].Text)
+ }
+ if len(rows) != 1 {
+ return []string{fmt.Sprintf("%s is superseded by %s, which the rootfs deck has no row for", id, by)}
+ }
+ return checkRunApplied(rows, ".")
+}
+
func mustParseRunRecord(t *testing.T) []copyRow {
t.Helper()
rows, err := parseMovesCopyRecord(runCopyRecordPath)
@@ -136,7 +179,14 @@ func checkRunApplied(rows []copyRow, root string) []string {
}
func TestRunBuiltCopyIsApplied(t *testing.T) {
- reportAll(t, checkRunApplied(builtRows(mustParseRunRecord(t), runCopyBuilt), "."))
+ reportAll(t, checkRunApplied(builtRows(mustParseRunRecord(t), runBuiltLive()), "."))
+}
+
+func TestRunCopySupersededIsPinned(t *testing.T) {
+ if len(runCopySuperseded) != 1 || runCopySuperseded["RUN-C47"] != "RFS-3-C18" {
+ t.Fatalf("runCopySuperseded = %v, pinned {RUN-C47: RFS-3-C18}", runCopySuperseded)
+ }
+ reportAll(t, runSupersessionProblems(t, "RUN-C47"))
}
// Each fixture case is a state the gate must refuse, for the right reason.
@@ -189,12 +239,19 @@ func TestRunCopyGateRefusesTheNegativeFixtures(t *testing.T) {
}
// The series is done only when every deck row is in the code or the docs.
+// A superseded row is built while its replacement is built and applied.
func TestRunCopyIsFullyBuilt(t *testing.T) {
built := map[string]bool{}
- for _, id := range runCopyBuilt {
+ for _, id := range runBuiltLive() {
built[id] = true
}
for _, id := range runCopyIDs {
+ if _, gone := runCopySuperseded[id]; gone {
+ for _, p := range runSupersessionProblems(t, id) {
+ t.Errorf("%s is in the deck, superseded, and not built: %s", id, p)
+ }
+ continue
+ }
if !built[id] {
t.Errorf("%s is in the deck but no task built it", id)
}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 08d959a04..54db901b0 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -633,6 +633,10 @@ The command runs for at most 30 minutes unless you pass --timeout, up to 6 hours
A hibernating instance is woken first. A live one keeps serving, and the command opens the same database beside it. One run at a time per instance. carlos run needs the instance's box on the nested layout, and it is refused while the instance is moving.
+For a rootfs app the command after -- runs inside the instance's image and is found on the image's PATH. carlos run does not reach instances on a customer fleet yet.
+
+--version runs another build of the app against the instance, for example the build a deploy is about to bring in. The build must already be on the instance's box. The command still gets the environment the instance serves with.
+
carlos run exits with the command's own status, 128 plus the signal number when a signal ended it, 124 when it timed out, 125 when it was interrupted or the instance let go of it without a result, 130 when you cancelled it, 3 when the box refused it or did not pick it up within 60 seconds, and 2 when the console refused it.
carlos logs shows when each run started, who asked for it and how it ended. The command's output is not kept there. A service's run reads "started by service ci", with the person it named, if any, marked as the service's statement.
diff --git a/internal/console/apiruns.go b/internal/console/apiruns.go
index b9d61437c..cb3ef82a2 100644
--- a/internal/console/apiruns.go
+++ b/internal/console/apiruns.go
@@ -264,14 +264,18 @@ func runMetaRefusalCode(msg string) string {
}
// runClassRefusal is spec §5.1 refusal 5 as a sentence, "" for a
-// platform-run, hibernating exec instance on a platform box.
+// platform-run, hibernating exec instance on a platform box, or a rootfs
+// instance (which never hibernates: the platform runs its process always)
+// on a platform box. A record on a customer fleet is refused whatever its
+// runtime (rootfs apps Plan 3, D4) until runs reach fleet boxes through
+// the console's door (Plan 6 Task 16).
func runClassRefusal(rec provision.Record) string {
switch {
case rec.Kind != "" && rec.Kind != "instance":
return fmt.Sprintf("%s is a %s route. carlos run works on instances", rec.Host, rec.Kind)
case rec.Addr != "" || len(rec.Addrs) > 0:
return fmt.Sprintf("%s is served from its own address, so the platform does not run its process", rec.Host)
- case !rec.HibernateOrDefault():
+ case !rec.HibernateOrDefault() && rec.Runtime != provision.RuntimeRootfsV1:
return fmt.Sprintf("%s does not sleep, so the platform does not run its process", rec.Host)
case rec.Pool != "":
return fmt.Sprintf("%s is a pooled instance. carlos run works on instances with a process of their own", rec.Host)
@@ -282,6 +286,32 @@ func runClassRefusal(rec provision.Record) string {
return ""
}
+// runVersionChecked checks a create's --version (meta.Version) and writes
+// the refusal when it does not stand: a name that is not a build version
+// (400), a build the app has never shipped (409), or a store that cannot
+// say (502). "" names no build and passes. Whether the build is staged on
+// the instance's box is the box's to say (runs.RefusedVersion).
+func (s *Server) runVersionChecked(ctx context.Context, w http.ResponseWriter, sqid, app, version string) bool {
+ if version == "" {
+ return true
+ }
+ if !release.ValidVersion(version) {
+ jsonErrorCode(w, http.StatusBadRequest, runCodeInvalidRequest, fmt.Sprintf("%s is not a build name", version))
+ return false
+ }
+ _, err := release.GetManifest(ctx, s.cfg.Releases, sqid, app, version)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ jsonErrorCode(w, http.StatusConflict, runCodeInvalidRequest, fmt.Sprintf("%s has no build %s", app, version))
+ return false
+ case err != nil:
+ log.Printf("console: api run %s/%s: read the manifest of %s: %v", sqid, app, version, err)
+ jsonErrorCode(w, http.StatusBadGateway, runCodeReadFailed, runReadFailedMsg)
+ return false
+ }
+ return true
+}
+
// runMetaRefusal is refusal 8 as a sentence, "" when meta is valid.
func runMetaRefusal(m runs.Meta) string {
switch err := runs.CheckArgv(m.Argv); {
@@ -469,6 +499,9 @@ func (s *Server) handleAPIRunCreate(w http.ResponseWriter, r *http.Request) {
jsonErrorCode(w, http.StatusBadRequest, runMetaRefusalCode(msg), msg)
return
}
+ if !s.runVersionChecked(ctx, w, acct.Sqid, app, meta.Version) {
+ return
+ }
if msg := onBehalfOfRefusal(p, meta.OnBehalfOf); msg != "" {
jsonErrorCode(w, http.StatusBadRequest, runCodeOnBehalfOfInvalid, msg)
return
@@ -540,7 +573,7 @@ func (s *Server) handleAPIRunCreate(w http.ResponseWriter, r *http.Request) {
}
now := time.Now().UTC()
req := runs.Request{Schema: 1, ID: id, Account: acct.Sqid, App: app, Host: host, Incarnation: inc,
- Argv: meta.Argv, TimeoutS: meta.TimeoutS, By: actor, RequestedAt: now, IdempotencyKey: scoped}
+ Argv: meta.Argv, TimeoutS: meta.TimeoutS, By: actor, RequestedAt: now, IdempotencyKey: scoped, Version: meta.Version}
if p.Kind == PrincipalService {
req.ByService, req.ByCredential, req.OnBehalfOf = p.Name, p.CredentialID, meta.OnBehalfOf
}
@@ -643,8 +676,12 @@ func (s *Server) handleAPIRunCreate(w http.ResponseWriter, r *http.Request) {
// run on its context too: a caller that left after it must not cost the
// box its prompt pickup or the row its version.
s.bumpSerial(wctx)
+ version := req.Version
+ if version == "" {
+ version = s.runVersion(wctx, acct.Sqid, app, rec.Channel)
+ }
s.auditActivity(acct, app, actor, Activity{Action: "run-start", TargetType: "instance", Target: host,
- Detail: runStartDetail(req, s.runVersion(wctx, acct.Sqid, app, rec.Channel))})
+ Detail: runStartDetail(req, version)})
writeJSON(w, http.StatusAccepted, runs.Created{ID: id, Host: host, State: state})
}
diff --git a/internal/console/apiruns_rootfs_test.go b/internal/console/apiruns_rootfs_test.go
new file mode 100644
index 000000000..fe094c711
--- /dev/null
+++ b/internal/console/apiruns_rootfs_test.go
@@ -0,0 +1,98 @@
+package console
+
+// Rootfs apps Plan 3 Task 12: the run door admits a rootfs instance (which
+// never hibernates) on a platform box, keeps the fleet refusal for every
+// record (D4), and checks a run's --version against the app's shipped
+// builds.
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/runs"
+)
+
+// putRootfsShopRecord writes a rootfs instance record of the shop app:
+// runtime rootfs-v1, hibernation off, as Plan 2 mints one.
+func putRootfsShopRecord(t *testing.T, fx *consoleFixture, host, region string) {
+ t.Helper()
+ no := false
+ putShopRecord(t, fx, provision.Record{Host: host, Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: region, CreatedAt: time.Now().UTC()})
+}
+
+func TestRunDoorAdmitsRootfsResident(t *testing.T) {
+ fx := runFixture(t)
+ putRootfsShopRecord(t, fx.consoleFixture, "rootfs.example.com", "uk")
+ status, body := postRun(t, fx.runsURL("rootfs.example.com"), fx.member, okMeta(), nil)
+ if status != http.StatusAccepted {
+ t.Fatalf("a rootfs instance on a platform box: %d %s, want 202", status, body)
+ }
+ // A binary instance that does not sleep is still refused.
+ no := false
+ putShopRecord(t, fx.consoleFixture, provision.Record{Host: "awake.example.com", Hibernate: &no})
+ if status, body := postRun(t, fx.runsURL("awake.example.com"), fx.member, okMeta(), nil); status != http.StatusConflict || !strings.Contains(errorOf(t, body), "does not sleep") {
+ t.Errorf("an always-on binary instance: %d %s, want today's refusal", status, body)
+ }
+}
+
+func TestRunDoorStillRefusesFleet(t *testing.T) {
+ fx := runFixture(t)
+ putRootfsShopRecord(t, fx.consoleFixture, "fleet.example.com", "fleet/pi")
+ status, body := postRun(t, fx.runsURL("fleet.example.com"), fx.member, okMeta(), nil)
+ if status != http.StatusConflict || errorOf(t, body) != "fleet.example.com runs on your fleet pi. carlos run works on platform boxes only" {
+ t.Fatalf("a rootfs instance on a fleet: %d %s, want today's fleet refusal", status, body)
+ }
+}
+
+func TestRunDoorVersionChecks(t *testing.T) {
+ fx := runFixture(t)
+ ctx := context.Background()
+ if err := release.Ship(ctx, fx.rel, release.OpsAccount, release.Manifest{
+ Schema: 1, App: "shop", Version: "v2", Kind: "binary", BuiltAt: "2026-10-24T10:00:00Z",
+ Artifacts: map[string]release.Artifact{"linux-arm64": {File: "shop"}},
+ }, map[string][]byte{"linux-arm64": []byte("bin")}); err != nil {
+ t.Fatal(err)
+ }
+ with := func(v string) runs.Meta { m := okMeta(); m.Version = v; return m }
+
+ status, body := postRun(t, fx.runsURL(runTestHost), fx.member, with("v 1"), nil)
+ if status != http.StatusBadRequest || errorOf(t, body) != "v 1 is not a build name" {
+ t.Errorf("a version that is not a build name: %d %s", status, body)
+ }
+ status, body = postRun(t, fx.runsURL(runTestHost), fx.member, with("v9"), nil)
+ if status != http.StatusConflict || errorOf(t, body) != "shop has no build v9" {
+ t.Errorf("an unknown build: %d %s", status, body)
+ }
+ if rec, err := provision.GetRecord(ctx, fx.rel, release.OpsAccount, "shop", runTestHost); err != nil || rec.ActiveRun != nil {
+ t.Fatalf("a refused version admitted a run: %+v, %v", rec.ActiveRun, err)
+ }
+
+ status, body = postRun(t, fx.runsURL(runTestHost), fx.member, with("v2"), nil)
+ if status != http.StatusAccepted {
+ t.Fatalf("a shipped build: %d %s, want 202", status, body)
+ }
+ var c runs.Created
+ if err := json.Unmarshal([]byte(body), &c); err != nil {
+ t.Fatal(err)
+ }
+ req, err := runs.ReadRequest(ctx, fx.rel, release.OpsAccount, "shop", c.ID)
+ if err != nil || req.Version != "v2" {
+ t.Fatalf("request.json version %q (%v), want v2", req.Version, err)
+ }
+ events, _ := fx.st.Events(OpsAccountID, "shop", 10)
+ found := false
+ for _, e := range events {
+ if e.Action == "run-start" && strings.Contains(e.Detail, c.ID) && strings.Contains(e.Detail, `"version":"v2"`) {
+ found = true
+ }
+ }
+ if !found {
+ t.Errorf("no run-start row naming version v2 in %+v", events)
+ }
+}
diff --git a/internal/host/runevents.go b/internal/host/runevents.go
index d20cbb054..143c6dc62 100644
--- a/internal/host/runevents.go
+++ b/internal/host/runevents.go
@@ -79,6 +79,8 @@ func runRefusedWords(res runs.Result) string {
return "the instance was deleted and created again after the run was requested"
case runs.RefusedImport:
return "the instance is an import that is not committed yet"
+ case runs.RefusedVersion:
+ return "the build is not on the box"
}
return res.Refused
}
diff --git a/internal/host/runexec.go b/internal/host/runexec.go
index 8168142a6..ca0e8b710 100644
--- a/internal/host/runexec.go
+++ b/internal/host/runexec.go
@@ -71,13 +71,16 @@ func exitOf(st instancectl.CmdStatus) (int, string) {
// runResultForLaunch maps RunCmd's refusals, and Prepare's, to the result
// the member reads. A route that is not an instance's (a worker) is
-// refused as a flat box is: runs need an instance on the nested layout.
-// Anything else (a busy hold, a failed download, a failed start) is the
-// box failing to start the command.
-func runResultForLaunch(err error) runs.Result {
+// refused as a flat box is: runs need an instance on the nested layout. A
+// build the run named (build, the request's Version) that is not staged
+// here is refused naming it. Anything else (a busy hold, a failed
+// download, a failed start) is the box failing to start the command.
+func runResultForLaunch(err error, build string) runs.Result {
var we *activator.CmdWakeError
var se *activator.CmdStoppedError
switch {
+ case errors.Is(err, activator.ErrCmdVersion):
+ return runs.Result{Refused: runs.RefusedVersion, Detail: build}
case errors.Is(err, activator.ErrCmdClaim):
return runs.Result{Refused: runs.RefusedClaim}
case errors.Is(err, activator.ErrCmdNotNested), errors.Is(err, activator.ErrCmdNotInstance):
@@ -159,6 +162,7 @@ func (w *runsWorker) execute(ctx context.Context, rec provision.Record, req runs
RunID: req.ID,
Args: req.Argv,
RunDir: filepath.Join(instDir, runs.DirName, req.ID),
+ Build: req.Version,
Stdout: chunks.Stream(runs.StreamOut),
Stderr: chunks.Stream(runs.StreamErr),
Prepare: func(ctx context.Context) error {
@@ -191,7 +195,7 @@ func (w *runsWorker) execute(ctx context.Context, rec provision.Record, req runs
log.Printf("agent: runs: %s %s: not launched: %v", rec.Host, req.ID, err)
return
}
- res := runResultForLaunch(err)
+ res := runResultForLaunch(err, req.Version)
recheckRefused := recheckErr != nil && !(launchEnded != nil && endedByContext(recheckErr))
if launchEnded != nil && !prepRefused && !recheckRefused {
// The admission ended with the run's own cancel or deadline:
diff --git a/internal/host/runexec_linux_test.go b/internal/host/runexec_linux_test.go
index 76b55e4cc..af530090a 100644
--- a/internal/host/runexec_linux_test.go
+++ b/internal/host/runexec_linux_test.go
@@ -5,6 +5,7 @@ import (
"crypto/sha256"
"encoding/hex"
"errors"
+ "fmt"
"io"
"os"
"strings"
@@ -76,6 +77,7 @@ func (h *fakeHandle) Release() { h.mu.Lock(); h.released = true; h.mu.Unlock() }
// a test that must start no unit fails at once instead of following one.
type fakeLauncher struct {
mu sync.Mutex
+ specs []activator.CmdSpec // every spec RunCmd was handed
calls int
units int
noUnit bool
@@ -90,6 +92,7 @@ func (l *fakeLauncher) started() int { l.mu.Lock(); defer l.mu.Unlock(); return
func (l *fakeLauncher) RunCmd(ctx context.Context, rt registry.Route, spec activator.CmdSpec) (activator.CmdHandle, error) {
l.mu.Lock()
l.calls++
+ l.specs = append(l.specs, spec)
l.mu.Unlock()
if l.err != nil {
return nil, l.err
@@ -434,6 +437,26 @@ func TestRunLaunchErrorsBecomeResults(t *testing.T) {
}
}
+// A run that names a build hands it to the launch (CmdSpec.Build), and a
+// build the box has not staged ends the run refused, naming the build.
+func TestRunVersionReachesTheLaunch(t *testing.T) {
+ t.Parallel()
+ s := release.NewDirStore(t.TempDir())
+ rec, req := pickedRun(t, s, 60)
+ req.Version = "v2"
+ l := &fakeLauncher{err: fmt.Errorf("shop.example.com: build v2: %w: no such file", activator.ErrCmdVersion)}
+ res := runWith(t, s, l, rec, req, newRunHandle())
+ if res.Refused != runs.RefusedVersion || res.Detail != "v2" {
+ t.Fatalf("result %+v, want refused version naming v2", res)
+ }
+ if len(l.specs) != 1 || l.specs[0].Build != "v2" {
+ t.Fatalf("the launch was handed %+v, want Build v2", l.specs)
+ }
+ if r := currentRun(t, s); r.State != provision.RunDone {
+ t.Fatalf("run %+v, want done", r)
+ }
+}
+
func TestRunInterruptedByAnInstanceStop(t *testing.T) {
s := release.NewDirStore(t.TempDir())
rec, req := pickedRun(t, s, 60)
diff --git a/internal/host/runexec_test.go b/internal/host/runexec_test.go
new file mode 100644
index 000000000..193e580c9
--- /dev/null
+++ b/internal/host/runexec_test.go
@@ -0,0 +1,27 @@
+package host
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/runs"
+)
+
+// RunCmd's ErrCmdVersion, however wrapped, is the run refused for its
+// build, and the result names the build the request asked for.
+func TestRunResultForVersionRefusal(t *testing.T) {
+ t.Parallel()
+ err := fmt.Errorf("shop.example.com: build v2: %w: open /opt/carlos/versions/v2/shop: no such file", activator.ErrCmdVersion)
+ if got := runResultForLaunch(err, "v2"); got != (runs.Result{Refused: runs.RefusedVersion, Detail: "v2"}) {
+ t.Fatalf("runResultForLaunch = %+v, want refused version naming v2", got)
+ }
+ if got := runEndedLine("r1", runs.Result{Refused: runs.RefusedVersion, Detail: "v2"}, false); got != "run r1 did not start: the build is not on the box" {
+ t.Fatalf("the ended line is %q", got)
+ }
+ // Any other failure is still the box failing to start the command.
+ if got := runResultForLaunch(errors.New("start cmd unit: 502"), "v2"); got.Refused != "" || got.Interrupted != runs.InterruptedStartFailed {
+ t.Fatalf("runResultForLaunch(502) = %+v", got)
+ }
+}
diff --git a/internal/runs/keys.go b/internal/runs/keys.go
index e697bd388..dcde25320 100644
--- a/internal/runs/keys.go
+++ b/internal/runs/keys.go
@@ -77,8 +77,8 @@ func ValidFileHash(h string) bool {
func NormalFileHash(h string) string { return strings.ToLower(h) }
// MetaDigest is the hex sha256 of a canonical encoding of what a create
-// asks for: argv, timeout_s, on_behalf_of, and each file's name, size and
-// sha256 (lowercased), in meta's order. Every string and count is
+// asks for: argv, timeout_s, on_behalf_of, each file's name, size and
+// sha256 (lowercased), in meta's order, and the build it names, if any. Every string and count is
// length-prefixed, so no two different requests share an encoding. A retry
// with the same key must have the same digest.
func MetaDigest(m Meta) string {
@@ -96,6 +96,13 @@ func MetaDigest(m Meta) string {
num(h, uint64(f.Size))
str(h, NormalFileHash(f.SHA256))
}
+ // A named build is part of the request; with none the digest is the
+ // one every earlier create had, so a key recorded before --version
+ // still matches its own retry.
+ if m.Version != "" {
+ str(h, "version")
+ str(h, m.Version)
+ }
return hex.EncodeToString(h.Sum(nil))
}
diff --git a/internal/runs/keys_test.go b/internal/runs/keys_test.go
index 120991aef..58d225ebc 100644
--- a/internal/runs/keys_test.go
+++ b/internal/runs/keys_test.go
@@ -69,6 +69,11 @@ func TestMetaDigestCoversEveryField(t *testing.T) {
if MetaDigest(base()) != want {
t.Fatal("MetaDigest is not deterministic")
}
+ // A create that names no build digests exactly as before --version, so
+ // a key recorded by an older console still matches its own retry.
+ if want != "41b95897b5d80ec7e7c3c5f2d7257d65329e0998751373cc12b7480956b44826" {
+ t.Fatalf("the digest of a create naming no build changed: %s", want)
+ }
for name, change := range map[string]func(*Meta){
"argv": func(m *Meta) { m.Argv[1] = "y.csv" },
"argv split": func(m *Meta) { m.Argv = []string{"importx.csv"} },
@@ -81,6 +86,7 @@ func TestMetaDigestCoversEveryField(t *testing.T) {
"file sha256": func(m *Meta) { m.Files[0].SHA256 = strings.Repeat("b", 64) },
"no files": func(m *Meta) { m.Files = nil },
"a second file": func(m *Meta) { m.Files = append(m.Files, MetaFile{Name: "y.csv", Size: 1, SHA256: hash}) },
+ "version": func(m *Meta) { m.Version = "v2" },
} {
m := base()
change(&m)
diff --git a/internal/runs/runs.go b/internal/runs/runs.go
index a93e065e7..24d378bca 100644
--- a/internal/runs/runs.go
+++ b/internal/runs/runs.go
@@ -49,6 +49,9 @@ const (
RefusedWake = "wake"
RefusedIncarnation = "incarnation"
RefusedImport = "import"
+ // RefusedVersion: the build the run named (Request.Version) is not
+ // staged on the instance's box; Result.Detail names it.
+ RefusedVersion = "version"
// RefusedExpired is written by the console, not a box: the run expired
// before any box picked it up (run spec §5.2), so no box ever wrote a
// result. The CLI reports it as "not picked up".
@@ -151,6 +154,11 @@ type Meta struct {
// a run service may send it; it is recorded on the service's word and
// grants nothing (service runs spec §2).
OnBehalfOf string `json:"on_behalf_of,omitempty"`
+ // Version is the build to run instead of the one the instance serves
+ // (carlos run --version), "" for the serving build. The console checks
+ // it names a shipped build of the app; the box refuses one it does not
+ // have staged (RefusedVersion).
+ Version string `json:"version,omitempty"`
}
type MetaFile struct {
@@ -195,6 +203,9 @@ type Request struct {
// own words. It links the run to its key after the record has pruned
// the entry (service runs spec §§ 2, 3). Empty for an unkeyed create.
IdempotencyKey string `json:"idempotency_key,omitempty"`
+ // Version is Meta.Version as the console admitted it: the build the
+ // box runs the command from, "" for the build the instance serves.
+ Version string `json:"version,omitempty"`
}
// Timeout is the run's timeout as a duration.
diff --git a/run.go b/run.go
index 0da9a1bc9..89d8d49a2 100644
--- a/run.go
+++ b/run.go
@@ -27,7 +27,7 @@ import (
"github.com/carlosframework/platform/internal/runs"
)
-const runUsageRun = "usage: carlos run --app <app> --instance <host> [--file <path>]... [--timeout 30m] -- <arg>..."
+const runUsageRun = "usage: carlos run --app <app> --instance <host> [--file <path>]... [--timeout 30m] [--version <build>] -- <arg>..."
const runUsageFollow = "carlos run --app <app> --instance <host> --follow <id>"
@@ -47,6 +47,7 @@ var errRunUsage = errors.New("carlos run: usage")
type runOpts struct {
app, instance, follow, console string
idempotencyKey string
+ version string
acctRaw, acctIDRaw *string
files []string
timeout time.Duration
@@ -69,6 +70,7 @@ func parseRunArgs(args []string, stderr io.Writer) (runOpts, error) {
var files multiFlag
fs.Var(&files, "file", "a file to upload with the run (repeatable; 64 MB in total)")
timeout := fs.Duration("timeout", runs.DefaultTimeout, "how long the command may run (1s to 6h)")
+ version := fs.String("version", "", "a build of the app to run instead of the one the instance serves")
follow := fs.String("follow", "", "attach to a run already started, by its id")
key := fs.String("idempotency-key", "", "a key of your choosing: run again with the same key and the same request, and you follow the run already started instead of starting a second")
acctRaw, acctIDRaw, _ := accountFlags(fs)
@@ -82,7 +84,7 @@ func parseRunArgs(args []string, stderr io.Writer) (runOpts, error) {
}
o := runOpts{app: strings.TrimSpace(*app), instance: strings.TrimSpace(*instance), follow: strings.TrimSpace(*follow),
console: *console, acctRaw: acctRaw, acctIDRaw: acctIDRaw, files: files, timeout: *timeout, argv: argv,
- idempotencyKey: *key}
+ idempotencyKey: *key, version: strings.TrimSpace(*version)}
switch {
case o.instance == "":
return o, errors.New("--app and --instance name the instance to run against")
@@ -131,7 +133,7 @@ func runReadError(path string, err error) error {
// each file's sha256: the console needs it to tell a retry of the same
// request from a different one. The console checks all of it again.
func runMetaFor(o runOpts) (runs.Meta, error) {
- m := runs.Meta{Argv: o.argv, TimeoutS: int64(o.timeout / time.Second)}
+ m := runs.Meta{Argv: o.argv, TimeoutS: int64(o.timeout / time.Second), Version: o.version}
for _, p := range o.files {
st, err := os.Stat(p)
if err != nil {
@@ -755,6 +757,8 @@ func runExit(host string, r runs.Result) (int, []string) {
return 3, append(lines, fmt.Sprintf("%s was deleted and created again after this run was requested. the run did not start", host))
case r.Refused == runs.RefusedImport:
return 3, append(lines, fmt.Sprintf("%s is an import that is not committed yet. the run did not start", host))
+ case r.Refused == runs.RefusedVersion:
+ return 3, append(lines, fmt.Sprintf("%s: build %s is not on the instance's box, so the run did not start", host, r.Detail))
case r.Refused != "":
return 3, append(lines, fmt.Sprintf("carlos run: %s", r.Refused))
case r.Cancelled:
diff --git a/run_test.go b/run_test.go
index 0caf9cabe..42c4c1f27 100644
--- a/run_test.go
+++ b/run_test.go
@@ -59,6 +59,38 @@ func TestParseRunArgs(t *testing.T) {
}
}
+// --version names the build to run: it reaches the create's meta as
+// version (absent without it), and the box's refusal of a build it has not
+// staged is exit 3 with RFS-3-C21.
+func TestRunVersionFlag(t *testing.T) {
+ o, err := parseRunArgs([]string{"--app", "shop", "--instance", "h.example.com", "--version", "v2", "--", "bin/rails", "db:migrate:status"}, io.Discard)
+ if err != nil {
+ t.Fatal(err)
+ }
+ m, err := runMetaFor(o)
+ if err != nil || m.Version != "v2" {
+ t.Fatalf("meta %+v, %v; want version v2", m, err)
+ }
+ raw, err := json.Marshal(m)
+ if err != nil || !strings.Contains(string(raw), `"version":"v2"`) {
+ t.Fatalf("meta on the wire %s, %v; want version v2", raw, err)
+ }
+ o, err = parseRunArgs([]string{"--app", "shop", "--instance", "h.example.com", "--", "x"}, io.Discard)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if m, _ := runMetaFor(o); m.Version != "" {
+ t.Fatalf("meta names version %q with no --version", m.Version)
+ }
+ if raw, _ := json.Marshal(runs.Meta{Argv: []string{"x"}}); strings.Contains(string(raw), "version") {
+ t.Fatalf("meta with no build names one on the wire: %s", raw)
+ }
+ code, lines := runExit("shop.example.com", runs.Result{Refused: runs.RefusedVersion, Detail: "v2"})
+ if code != 3 || len(lines) != 1 || lines[0] != "shop.example.com: build v2 is not on the instance's box, so the run did not start" {
+ t.Fatalf("runExit = %d %q", code, lines)
+ }
+}
+
func TestRunMetaForStatsEveryFile(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "checkins.csv")