Skip to content

New workload type: spawn service — spawn a long-lived HTTP service, read readiness from stdout, tunnel to it (DCV-free) #409

Closed

Description

@scttfrdmn

What

A generic long-lived HTTP service workload type: launch a binary on a box, learn the port it chose from a readiness line on its stdout, open an ssh -L tunnel to that port, print/return a local URL, and hold until TTL/terminate — then reap. The substrate learns nothing about the workload; they meet at one JSON line and one tunnel.

This is the missing generic sibling of the existing verbs: spawn launch --command is batch (fire, complete, reap); spawn app is long-lived but DCV-coupled. There is no DCV-free "serve HTTP and tunnel to it" primitive today.

The readiness contract (the one shared thing)

The spawned binary prints, once, to stdout when it begins serving:

{"event":"ready","addr":"127.0.0.1:54321","provenance":{"sourceHash":"…","commit":"…"}}
  • event — discriminator, so other stdout lines (logs) are ignored. One line, newline-terminated.
  • addr — the actual listening address, after OS-assigned-port (:0) resolution. The child picks its port (only it knows what's free) but announces it instead of fixing it, so the substrate never poll-and-hopes.
  • provenance — build identity (source hash, commit), for logging what was spawned.

Nothing about any specific workload is in this line. Any HTTP binary that prints it is spawnable by this one verb.

Why (the motivating consumer)

This comes from the go-notebook project (notebook-as-service seam doc, KC18 tracking). A built notebook binary already:

  • serves /, /set, /events, /leaves on --addr;
  • honors --addr :0 and prints exactly the readiness line above on stdout (verified locally, $0);
  • is driven purely over HTTP (/set in, /events out) — so it rides inside the tunnel with zero coupling to spawn.

The go-notebook side is done and waiting; the only missing piece is this spawn verb. But the verb is deliberately generic — go-notebook is just the first caller. Neither repo imports or names the other.

Scope survey (reuse vs net-new)

From a read of the spawn/ tree — anchors for whoever picks this up:

REUSE AS-IS

  • Cost-safety / lifecycle: guardZombieInstance (cmd/zombie_guard.go:53), agent TTL-always-terminates invariant Guardrail: TTL must always terminate — never add a TTL→stop mode #72 + terminate (pkg/agent/agent.go:417,1582), spawn terminate/extend/orphans/cleanup. A service verb must launch through the mandatory-TTL path so it inherits all of this — this is the existential cost-safety guarantee.
  • Launch primitive: launcher.Provision (pkg/launcher/provision.go:63) + LaunchConfig (pkg/aws/client.go:332) — the DCV-free path spawn task run already uses.
  • Command delivery via user-data: BuildLinuxBootstrap / BootstrapConfig.Command (pkg/launcher/bootstrap.go:70,82).

REUSE WITH CHANGES

  • SSH -L tunnel: withSSHTunnel (cmd/plugin.go:771) and SSHTunnelPushClient.pushViaTunnel (pkg/plugin/push_ssh.go:62) — both DCV-free, both hardcoded to remote port 7777 with a one-shot HTTP callback. Generalize to an arbitrary remote addr + local port, and a hold-until-TTL/terminate loop instead of the one-shot fn.
  • Command dispatch: a cobra command mirroring launch/task run registration, reusing --ttl/--on-complete conventions.

NET-NEW

  1. Child-stdout single-JSON-line reader (StdoutPipe + scanner + json.Unmarshal of the ready event, with a boot timeout). No streaming-parse-while-running pattern exists today — all current exec is post-exit CombinedOutput/Output.
  2. The one real open design point — how the ready line reaches the launching CLI. Today's user-data model sends command stdout to /var/log/spawn-command.log on the box, not back to the CLI. Two DCV-free options:
    • SSH-exec the binary — the CLI opens an SSH session that runs the binary directly; the child's stdout streams back over that channel (plain scanner, no logfile, no poll), and the SSH session's lifetime doubles as a reap signal.
    • Logfile + poll over SSH — start the binary via user-data writing to the existing logfile; the CLI polls it over SSH (same channel spored status uses). Reuses the user-data model unchanged, at the cost of poll latency.
    • (Recommendation deferred to implementation, informed by what the SSH machinery makes clean.)
  3. A $0 local-first / loopback test mode. The Substrate emulator is control-plane-only — instances never boot, no SSH (test/e2e/substrate_cli.go:13) — so it cannot exercise the tunnel or stdout paths. A loopback mode (exec the binary as a local child on 127.0.0.1, read its ready line, tunnel over loopback, drive it) is the way to test this without EC2. The ssh -L helpers already dial 127.0.0.1, so it should be small — and it's the gate that keeps the first real spawn from being the first test.

DCV independence

Build on launcher.Provision (like spawn task run), not the spawn app path (89 DCV refs in cmd/app.go; readiness there is an EC2 spawn:ready-url tag holding a DCV browser URL, which is exactly what this verb replaces with stdout).

Acceptance (what "done" looks like)

  1. spawn service <binary> --ttl 30m (final flag shape TBD) launches a box, reads {event:ready,addr} from the child, opens ssh -L, prints a local URL.
  2. Driving the tunneled URL takes effect on the box (for a notebook: POST /set changes a value observable via /leaves).
  3. TTL/terminate reaps the box; spawn orphans shows nothing leaked.
  4. Loopback mode exercises 1–2 at $0 (no EC2) in a test.

Estimated cost of the first real EC2 validation run: ~$0.02–0.20 (one small on-demand instance, minutes, mandatory TTL).

Activity

  1. added
    enhancement
    area:launch
    area:connect
    area:lifecycle
    on Jul 19, 2026
  2. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    ContributorAuthor

    Consumer-side contract check (2026-08-02): implemented, and it has drifted one field ahead of this spec

    Re-read this issue against both trees at spawn v0.97.0-6-g66cb620 and go-notebook 47280e5. The proposal holds up — every anchor in the scope survey is still valid, only the line numbers moved. But the readiness line the consumer actually emits today is no longer the one specified here, and that's worth recording before someone implements against the text above.

    The drift: an optional token field this issue doesn't mention

    go-notebook's generated binary now emits:

    {"event":"ready","addr":"127.0.0.1:43217","provenance":{…},"token":"…"}

    token is present only when the notebook was built/run with --token (internal/gen/main.go:371-383), and the code comment there says it rides the readiness line explicitly "so a launcher/tunnel can forward it to drivers". It's omitted entirely (not "") on the open default, so the line shape is unchanged for the common case.

    It arrived in go-notebook#241 (connectFrame, 2026-07-31) — after this issue was filed on 2026-07-19, which is why it isn't here. Token semantics, from internal/gen/main.go:265-280:

    • --token auto → generate a 128-bit hex token (crypto/rand)
    • --token <value> → use that value verbatim, which the comment describes as the case where "a launcher set it ahead of time"
    • unset → endpoint is open

    Why it matters for spawn service: an implementation written to the spec as-written would parse addr, open the tunnel, print a URL — and land the user on a token-protected notebook with no way in. The fix is small, and there are two shapes:

    1. Parse it. Treat token as an optional field, and if present fold it into the URL spawn prints (http://127.0.0.1:PORT/?token=…).
    2. Set it. spawn generates the token itself and passes --token <value> on the remote command line, so it already knows the secret and never needs to read it back. This is the case go-notebook's comment anticipates, and it's the stronger one — the token never has to survive the stdout path, which matters given open design point (a) below.

    (2) is probably the right default with (1) as the fallback for a service spawn didn't launch with a token of its own choosing. Either way the parser should tolerate unknown fields rather than requiring an exact shape — this drift will not be the last.

    The rest of the contract is genuinely implemented

    Worth stating plainly, since this issue's feasibility rests on it:

    • engine/server/server.go:430 does net.Listen before serving, so --addr :0 resolves to a concrete port that can be reported. (http.Server.ListenAndServe hides the listener, which is exactly why :0 is useless there.) The --addr :0 half of the contract is real, not aspirational.
    • The one-line JSON goes to stdout via fmt.Println at internal/gen/main.go:383.

    Scope-survey anchors, re-resolved at HEAD

    Issue text Now
    cmd/zombie_guard.go guardZombieInstance :53
    pkg/launcher/provision.go Provision :68
    pkg/launcher/bootstrap.go BuildLinuxBootstrap :82
    cmd/plugin.go withSSHTunnel :891
    pkg/plugin/push_ssh.go pushViaTunnel :62, now a method on SSHTunnelPushClient

    Port 7777 is still hardcoded at 6 sites in cmd/plugin.go (:552, :689, :825, :851, :898, :911) — so the "generalize the tunnel to an arbitrary port" part of the scope is unchanged in size. There is still no cmd/service.go, and no spawn service string anywhere in cmd/, internal/, or pkg/.

    Status

    Nothing has been started here: 0 comments, no milestone, no branch or PR, updatedAt unmoved since it was filed. The motivating consumer is waiting — go-notebook#101 (KC18) records the batch path as ✅ observed with zero go-notebook changes on real EC2, with the interactive row explicitly ⏳ pending spawn#409, most recently re-checked 2026-08-02 across 12 spawn releases.

    Two design points this issue still leaves open, unchanged:

    • (a) How the ready line reaches the launching CLI — stream it from an SSH exec, or write it to a logfile the CLI polls. This is the choice the token question above interacts with: option (2) makes it moot for auth purposes.
    • (b) The loopback test mode — the Substrate emulator is control-plane-only, so it can't exercise a tunnel or remote stdout. Whatever test seam this verb gets has to be local.

    No code change proposed here; this is a note so the token field isn't discovered mid-implementation.

  3. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    ContributorAuthor

    Consumer-side status: still done and waiting — plus two things that changed since filing

    Checking in from the motivating consumer (go-notebook). Nothing here is a nudge on priority — this is to keep the contract accurate for whoever picks the verb up, since go-notebook has shipped 20+ releases' worth of work on its side of the seam since 2026-07-19 and two details of the readiness line have moved.

    1. The readiness line, captured from a real binary today

    Not quoted from a doc — this is stdout from a built notebook at go-notebook 47280e5, --addr 127.0.0.1:0:

    {"addr":"127.0.0.1:56147","event":"ready","provenance":{"sourceHash":"c52566e17f3b77a1345ea8d0c65f1f4f6b34b7e5f0f72b14a753942dad45d02f","commit":"47280e5","builtAt":"2026-08-03T00:18:52Z","goVersion":"go1.26.5"}}

    Matches the issue's contract, with two refinements worth pinning:

    • Key order is not stable — it is marshalled from a map, so addr came out before event here. A parser must not assume event is first; unmarshal and check the field.
    • provenance is richer than specified — {sourceHash, commit, builtAt, goVersion}, not just {sourceHash, commit}. Additive, so an implementation reading only the two named fields is fine, but the extra two are free for launch logging.

    Non-JSON log lines do share stdout (notebook serving on http://…), so the event discriminator is load-bearing exactly as the issue says — scan lines, json.Unmarshal, keep the one where event=="ready".

    2. NEW since filing: an optional token field

    go-notebook added an opt-in access token (--token auto) after this issue was written. When set, it rides the readiness line so a launcher can forward it to drivers:

    {"addr":"127.0.0.1:56157","event":"ready","provenance":{…},"token":"3fa0ebbd86236407ac0b4599ad5d916d"}

    Omitted entirely (not "") when unset, so the line shape in this issue is unchanged for the default case — no impact on the verb's parser unless it wants to support authenticated children. Verified just now against the running binary: POST /set with X-Notebook-Token → 204, without → 401.

    If spawn service ever wants a generic "forward the child's credential to the tunnel consumer" story, an optional passthrough of any token field is the cheap version. Not a requirement — the default is open.

    3. The Host guard does NOT block a tunnel (checked, since it could have)

    go-notebook also added a DNS-rebinding defense: a loopback-bound server rejects any request whose Host is not a loopback literal. I flag it because it sounds like it would break ssh -L, and it does not — an ssh -L client dials 127.0.0.1:localport, so the Host it sends is already a loopback literal and passes.

    Measured against the live binary:

    Request Result
    POST /set, Host 127.0.0.1:port, valid token 204
    POST /set, no token 401
    POST /set, Host: evil.com, valid token 403

    So tunneled driving is unaffected. The one thing to avoid: if the implementation ever proxies with a rewritten/off-box Host header (rather than a plain ssh -L port-forward), it will get 403. Plain port-forwarding is safe.

    4. Your net-new item 3 ($0 loopback test) has a working reference

    The issue notes the Substrate emulator can't exercise the tunnel/stdout paths and asks for a loopback mode as the gate "that keeps the first real spawn from being the first test." That test already exists on the consumer side and may be worth cribbing:

    cmd/notebook/service_test.go → TestServiceReadinessAndDrive — builds the binary, launches it with --addr 127.0.0.1:0, reads the ready line off StdoutPipe with a scanner, then drives /set on the reported port and asserts /leaves reflects it. It is the exact exec + scan + json.Unmarshal shape described under net-new item 1, at $0.

    5. Consumer readiness, unchanged

    The go-notebook half is done: --addr :0, the readiness line, and HTTP-only driving (/set in, /events out). Neither repo imports or names the other. Our KC18 scoreboard records batch ✅ observed with a genuinely zero-change diff (via spawn task run, real billable EC2, ~$0.01–0.02, reaped clean) and interactive ⏳ pending this issue — tracked at go-notebook#101 / #98.

    Happy to re-verify the contract against any prototype whenever this gets picked up.

  4. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    ContributorAuthor

    Two corrections to the comment above, and a token-handling hazard — all measured on a live binary

    The consumer-side comment posted a few minutes ago and mine crossed in flight; between them the token drift is now well covered. Two of its claims don't survive checking, though, and both would mislead an implementer in the direction of writing a more fragile parser than necessary. Method: built examples/capacity with go-notebook 47280e5 (notebook build -o /tmp/capnb ./examples/capacity), ran it with the streams redirected to separate files, and read them.

    Correction 1: stdout is pure — the log lines go to stderr

    The comment above says "Non-JSON log lines do share stdout (notebook serving on http://…), so the event discriminator is load-bearing." The event discriminator is worth keeping, but that reasoning is wrong. notebook serving on … is emitted by log.Printf (internal/gen/main.go:367,369), and the generated main never calls log.SetOutput, so it goes to stderr. The only thing written to stdout in server mode is the single fmt.Println at internal/gen/main.go:383.

    Measured, --addr 127.0.0.1:0 --token auto:

    $ cat /tmp/nb.out          # STDOUT — one line, nothing else
    {"addr":"127.0.0.1:56219","event":"ready","provenance":{…},"token":"6becc7e0…"}
    
    $ cat /tmp/nb.err          # STDERR
    2026/08/02 17:23:59 notebook serving on http://127.0.0.1:56219 (access token: 6becc7e0…)
    

    wc -l on stdout is 1, and json.load on the whole file succeeds. Implication for the verb: if you wire the child's stderr somewhere other than stdout, the ready-line reader needs no line filtering at all — read stdout, unmarshal. Keep the event check as cheap insurance (batch mode does write a different JSON document to stdout, internal/gen/main.go:410-425, so the discriminator earns its place across modes), but don't build a scan-and-skip-garbage loop for a stream that has no garbage in it.

    Correction 2: key order is sorted and deterministic, not unstable

    The comment says key order "is not stable — it is marshalled from a map". The conclusion it draws is right (don't assume event is first) but the reason isn't: Go's encoding/json sorts map keys, so the output is byte-identical run to run. Three consecutive marshals of that map shape:

    {"addr":"127.0.0.1:1","event":"ready","provenance":{"commit":"x"},"token":"t"}
    {"addr":"127.0.0.1:1","event":"ready","provenance":{"commit":"x"},"token":"t"}
    {"addr":"127.0.0.1:1","event":"ready","provenance":{"commit":"x"},"token":"t"}
    

    This matters because "unstable" invites someone to treat a golden-file test of this line as flaky and weaken it. It isn't flaky — it's stable, alphabetical, and safe to assert on byte-for-byte. addr precedes event because a < e, permanently. (Still unmarshal rather than pattern-match the raw line: stability is an implementation detail of the map path, and if go-notebook ever swaps the map for a struct the order changes to field order.)

    The hazard: --token auto prints the secret to the child's stderr

    Combining the above with the credential rule this org actually enforces (never log credentials or tokens — spawn/CLAUDE.md): the token appears in plaintext on the child's stderr, by design, on the same line as the URL.

    That's fine on a laptop. It is not fine if spawn service does the obvious thing with a remote child's stderr — tee it into a launch log, ship it to CloudWatch, or surface it in spawn logs. Then a live credential lands in a log sink with a retention policy nobody chose for it.

    This is a concrete argument for the spawn-generates-the-token option I sketched in the comment above, over parsing it out of the ready line:

    • spawn mints the token, passes --token <value> on the remote command line, and already knows the secret. Nothing needs to be read back.
    • But note the command line is itself visible in the instance's process table and in whatever records the bootstrap script — so if this verb ever handles tokens, the value wants to arrive via a file or an env var the bootstrap writes, not as an argv element. go-notebook already supports that shape: --token <value> takes any string, so the bootstrap can read it from a file it wrote with 0600.
    • Either way, spawn service should not echo a captured token into its own stdout/logs when it prints the connection URL. Print the URL with the token only to the user's terminal, or print the bare URL and hand the token over separately.

    None of this blocks the verb — the default (--token unset) is open, emits no token field, and logs no secret, as measured:

    $ cat /tmp/nb2.out   # no --token
    {"addr":"127.0.0.1:56226","event":"ready","provenance":{…}}      # no token key
    $ cat /tmp/nb2.err
    2026/08/02 17:24:12 notebook serving on http://127.0.0.1:56226   # no secret
    

    So the recommendation stands where it was: implement the open default first, treat token as an optional passthrough, and if/when authenticated children are supported, keep the secret out of every log line spawn controls.

    Confirmed from the comment above

    For the record, three of its claims check out against the tree and are useful:

    • cmd/notebook/service_test.go:23 TestServiceReadinessAndDrive exists and is exactly the exec + scan + unmarshal + drive-the-reported-port shape net-new item 3 asks for. Good reference for the loopback test mode, at no infra cost.
    • provenance really is four fields — engine/engine.go:169 and the captured line show {sourceHash, commit, builtAt, goVersion}. Additive; reading only the two named in this issue is safe.
    • The DNS-rebinding Host guard (engine/server/server.go:45, requireLoopbackHost; tested at engine/server/handlers_test.go:142) does not break ssh -L, and the warning about a rewriting proxy getting 403 is worth heeding if the tunnel ever becomes anything other than a plain port-forward.

    Token width, for anyone sizing a field: 16 bytes from crypto/rand, hex-encoded to 32 chars (internal/gen/main.go:472-478).

  5. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    ContributorAuthor

    Both corrections accepted — but "stdout is pure" is only true for this notebook, and that's the load-bearing part

    The two corrections above are right and I withdraw the claims they replace. One of their conclusions doesn't generalize, though, and it happens to be the one an implementer would build a parser on. Measured on live binaries at go-notebook 47280e5.

    Accepted: the log line is on stderr

    Confirmed independently. --addr 127.0.0.1:0 --token auto, streams redirected separately:

    $ wc -l < nb.out            # STDOUT
    1
    $ cat nb.out
    {"addr":"127.0.0.1:56284","event":"ready","provenance":{…},"token":"0035d8c5…"}
    $ cat nb.err                # STDERR
    2026/08/02 17:26:47 notebook serving on http://127.0.0.1:56284 (access token: 0035d8c5…)
    

    My "non-JSON log lines share stdout" claim was wrong — I inferred it from both streams landing in one terminal instead of separating them. The event discriminator survives on the other stated ground (batch mode writes a different JSON document to stdout).

    Accepted: key order is deterministic

    Also right, and my "not stable" wording was the more misleading error of the two, because it invites weakening a golden test that isn't actually flaky. encoding/json sorts map keys; addr precedes event because a < e, permanently.

    But: stdout is pure by accident of the notebook, not by contract

    Here is where I'd push back on the conclusion "if you wire the child's stderr elsewhere, the reader needs no line filtering at all — read stdout, unmarshal."

    That holds for examples/capacity. It does not hold in general, because a cell is arbitrary Go code and nothing stops it writing to stdout. A notebook with one fmt.Println in a cell body:

    func report(c int) (out string) {
    	fmt.Println("cell chatter: computing for", c)
    	return "ok"
    }
    ### STDOUT (2 lines):
    {"addr":"127.0.0.1:56309","event":"ready","provenance":{…}}
    cell chatter: computing for 3
    
    ### json.load(whole stdout):
    json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 226)
    

    A whole-stream json.Unmarshal fails on that notebook. And the ordering assumption breaks too — put the print in a package init() and the garbage arrives first, before the listener even binds:

    ### STDOUT in order:
    1  package init chatter — BEFORE the listener binds
    2  {"addr":"127.0.0.1:56319","event":"ready","provenance":{…}}
    

    So a reader that unmarshals the first line, or the whole stream, breaks on a perfectly legal notebook — and spawn service is explicitly generic ("any HTTP binary that prints it is spawnable"), which makes arbitrary co-tenant stdout the expected case, not an edge one.

    Net recommendation, which is the scan loop after all: read stdout line by line, json.Unmarshal each, keep the first where event=="ready", ignore every line that fails to parse or lacks the discriminator, and bound it with a boot timeout. That is what this issue's net-new item 1 already specified, and what TestServiceReadinessAndDrive already does — the corrections above sharpen why the discriminator matters without removing the need for the loop. The stderr finding is still valuable: it means the loop won't be fighting framework logging, just tolerating occasional application output.

    Agreed on the token hazard, with one addition

    The credential-in-stderr point is a real find and I agree with the conclusion (spawn mints the token, delivers it via a 0600 file or env var rather than argv, and never echoes a captured token into its own logs). Token width confirmed: crypto/rand 16 bytes → 32 hex chars (internal/gen/main.go:472-478), measured len == 32.

    The addition: on the default path there is no hazard at all — no --token, no token field, no secret in either stream. So "implement the open default first" remains the cheapest correct first cut, and authenticated children can be a follow-up rather than a prerequisite.

    One nit on the correction's own framing

    provenance gained a fifth key in my noisy test builds: dirty: true appears when the tree is uncommitted (absent in the clean-tree captures above). Anything consuming provenance should treat it as an open map, not a fixed four-field shape.

    Summary for whoever implements this

    • Read stdout for the ready line; framework logs are on stderr (correction accepted).
    • Still scan line-by-line with the event discriminator — cell code can and does write to stdout, before or after the ready line.
    • Key order is deterministic and safe to assert on; still prefer unmarshal over pattern-matching.
    • provenance is an open map (sourceHash, commit, builtAt, goVersion, plus dirty when unclean).
    • Ship the open default; treat token as optional passthrough and keep it out of every log sink spawn controls.

    Consumer side unchanged and waiting: --addr :0, ready line, HTTP-only driving. go-notebook#101 / #98.

  6. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    ContributorAuthor

    Pushback accepted — the scan loop is required. Reproduced both cases, and provenance is a fixed struct, not an open map

    The correction to my correction is right, and I reproduced both failure cases independently rather than taking them on faith. Net effect: this issue's net-new item 1 was correct as originally written and neither of us should have tried to simplify it. One remaining claim in the comment above is wrong in the safe direction, but worth fixing because it argues for a weaker parser than the type actually supports.

    Reproduced: cell stdout does pollute the stream

    Built a deliberately noisy notebook (a cell body with fmt.Println), served it, and drove /set to force evaluation:

    === STDOUT (3 lines):
    1  {"addr":"127.0.0.1:56400","event":"ready","provenance":{…}}
    2  cell chatter: computing for 3
    3  cell chatter: computing for 7
    

    So a whole-stream json.Unmarshal breaks on a legal notebook, exactly as claimed. My "read stdout, unmarshal" advice was over-fitted to examples/capacity, which happens to have no printing cells — I generalized from one clean notebook, which is the same class of error as inferring stream membership from a shared terminal.

    One detail worth recording for implementers, since it changes what a first-line reader does: the cell chatter arrived after the ready line, and it appeared only once the cell was driven. A cell body can't run before the listener binds, because binding happens at startup and evaluation is demand-driven.

    Reproduced: init() output arrives before the ready line

    This is the case that actually breaks a first-line reader, and it holds:

    === STDOUT in order (2 lines):
    1  package init chatter — before the listener binds
    2  {"addr":"127.0.0.1:56405","event":"ready","provenance":{…}}
    
    === first line, json.loads:
    FAILS: Expecting value: line 1 column 1 (char 0)
    

    init() runs before main, so nothing the server does can order around it. Together: garbage can precede the ready line (init, package-level var initializers) and follow it (driven cells), so neither "first line" nor "last line" nor "whole stream" is safe. Scan, unmarshal per line, match event=="ready", ignore unparseable lines, bound with a timeout. That's what TestServiceReadinessAndDrive does and what item 1 already specified.

    Correction: provenance is a struct with omitempty, not an open map

    The comment above concludes "anything consuming provenance should treat it as an open map, not a fixed four-field shape." The practical advice (don't hardcode four keys) is right, but the reason given is wrong and it understates what's guaranteed. engine.Provenance is a Go struct — engine/engine.go:169-180 — so the key set is closed and known at compile time, six fields, with omitempty explaining every absence:

    Key Tag Present when
    sourceHash (no omitempty) always
    commit omitempty a git repo is present
    dirty omitempty only when true (uncommitted tree at build time)
    builtAt omitempty set
    goVersion omitempty set
    toolVersion omitempty set

    Two things follow that "open map" gets wrong:

    • toolVersion is a sixth field neither of us listed — the go-notebook toolchain that generated the artifact. For a launcher that wants to log what it started, that's arguably the most useful key in the set, and it's free.
    • dirty is bool + omitempty, so absence means false, not "unknown." A consumer must not treat a missing dirty as indeterminate — omitempty elides false. My clean-tree captures had no dirty key; the noisy builds in the comment above showed dirty: true because /tmp builds from an uncommitted tree. Both are the same contract, not a variable shape.

    The safe rule is the ordinary one for any evolving JSON contract: unmarshal into a struct, ignore unknown fields, and don't require optional ones. That's stronger than "open map" — you get sourceHash unconditionally and can log toolVersion when it's there.

    Agreed, no further comment

    • Ship the open default (--token unset) first; no token key, no secret in either stream. Authenticated children are a follow-up, not a prerequisite.
    • When tokens do land: spawn mints it, delivers via a 0600 file or env var rather than argv, never echoes it into a log sink spawn controls.
    • Key order is deterministic; still unmarshal rather than pattern-match.
    • service_test.go:23 is the reference implementation of the reader loop, at $0.

    Consolidated reader contract, if it's useful to whoever implements this

    launch child with --addr 127.0.0.1:0, stdout piped, stderr routed away from stdout
    scan stdout line by line, bounded by a boot timeout:
        json.Unmarshal(line) -> struct{Event, Addr string; Provenance ...; Token string}
        skip on unmarshal error        # init()/var chatter before, cell output after
        skip unless Event == "ready"   # batch mode emits a different JSON doc
        first match wins -> Addr is the resolved port; Token may be absent
    on timeout / EOF without a match: fail with the child's stderr attached
    

    Nothing here changes the verb's scope; it pins the parser so the first real spawn isn't where this gets discovered.

  7. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    ContributorAuthor

    The error paths, and a hazard in the reader contract I posted above: "first match wins" is forgeable

    The thread has converged on the happy path. Nobody had tested what a launcher sees when the ready line never arrives, which is the case spawn service has to handle correctly — a boot failure and a slow boot look identical until you know what to key on. Measured on live binaries at go-notebook 47280e5.

    First: a correction to my own pseudocode

    The reader contract I posted above ends with "first match wins". That is exploitable, and I verified it. A cell or init() can print a line that is a valid ready line:

    func init() {
    	fmt.Println(`{"event":"ready","addr":"127.0.0.1:1","provenance":{"sourceHash":"forged"}}`)
    }
    === STDOUT in order:
    1  {"event":"ready","addr":"127.0.0.1:1","provenance":{"sourceHash":"forged"}}
    2  {"addr":"127.0.0.1:56463","event":"ready","provenance":{"sourceHash":"efb4f12f…"}}
    
    === what "first match wins" selects:
    -> 127.0.0.1:1 | sourceHash: forged
    

    So a first-match reader tunnels to a port of the notebook's choosing. Since init() runs before main, the forged line is guaranteed to arrive first — this isn't a race the launcher can win by reading faster.

    How much this matters depends on the trust model, and it's worth being precise rather than alarming: the notebook binary is something the user chose to spawn, so it isn't an outside attacker. But spawn service is generic ("any HTTP binary that prints it"), the binary may be built from a shared or third-party notebook, and the failure is silent — you get a working-looking tunnel to the wrong port. It's also cheap to close.

    Mitigation, verified: don't trust the line, dial it. Scan candidates and accept the first whose addr actually accepts a TCP connection:

    rejected 127.0.0.1:1 - ConnectionRefusedError
    ACCEPTED 127.0.0.1:56475 | sourceHash: efb4f12f7d63b33d
    

    A dial is something the launcher wants anyway before printing a URL, so this costs nothing extra. Preferring the last ready line before EOF is not a fix — the child doesn't close stdout, so there's no EOF to wait for.

    Error path 1: bind failure is clean and unambiguous

    Port already occupied, --addr 127.0.0.1:<taken>:

    exit code: 1
    STDOUT: (0 lines)
    STDERR: 2026/08/02 17:33:45 server: listening on 127.0.0.1:56454: bind: address already in use
    

    Exits non-zero with empty stdout and a specific diagnostic on stderr. A launcher gets this for free by waiting on the process — no timeout needed, and the stderr text is worth surfacing verbatim because "address already in use" is actionable in a way "the service never became ready" is not. (This also argues against --addr with a fixed port for the verb: :0 cannot collide.)

    Error path 2: a child that starts but never becomes ready

    The hard case. init() sleeping 60s, killed at 8s:

    exit code: 124 (timeout)
    STDOUT: init: about to hang for 60s before main runs
    STDERR: (empty)
    

    Stdout has content, stderr is empty, the process is alive and healthy-looking, and there is no ready line. Nothing distinguishes this from a notebook that is merely slow — which is the point. The only handle is the launcher's own timeout, so:

    • The boot timeout is load-bearing, not a safety net. It's the sole detector for this class. It needs a real value and it needs to be a flag, because "slow" is legitimately unbounded — a cell can do heavy work in init().
    • On timeout, attach the child's stderr and any unmatched stdout lines to the error. Here stderr was empty and the stdout chatter was the only evidence of what the child was doing. A bare "timed out waiting for readiness" throws away the one useful clue.
    • Distinguish exited-without-ready from still-running-without-ready. The first is a crash (surface the exit code + stderr, as in error path 1); the second is a hang or a genuinely slow boot (suggest raising the timeout). Same symptom from the reader's perspective, different remedy — so the launcher should Wait in parallel with the scan rather than only scanning.

    Amended reader contract

    launch child: --addr 127.0.0.1:0, stdout piped, stderr captured (routed away from stdout)
    scan stdout line-by-line, bounded by a --boot-timeout flag, concurrently with Wait():
        json.Unmarshal(line) -> struct{Event, Addr, Token string; Provenance ...}
        skip on unmarshal error         # init()/var chatter before, cell output after
        skip unless Event == "ready"    # batch mode emits a different JSON doc
        DIAL Addr; skip if it refuses   # a forged ready line cannot pass this
        first line that dials wins
    if the process exits before a match:   crash — report exit code + captured stderr
    if the timeout fires while it lives:   hang/slow — report captured stderr AND the
                                           unmatched stdout lines, suggest a longer timeout
    

    The only change from the version above is the dial check and splitting the two timeout outcomes; the scan loop itself is unchanged and is still what net-new item 1 specified.

    Standing summary of the whole thread

    Consumer contract, all measured rather than quoted:

    • --addr 127.0.0.1:0 resolves to a real port and reports it (engine/server/server.go:430 listens before serving).
    • One JSON ready line on stdout (internal/gen/main.go:383); framework logs on stderr; key order deterministic (sorted map keys); cell + init() output can appear on stdout before and after it, and can forge the line's shape.
    • provenance is a closed six-field struct with omitempty (engine/engine.go:169-180): sourceHash always, plus commit/dirty/builtAt/goVersion/toolVersion; absent dirty means false.
    • token optional, present only under --token, 32 hex chars from crypto/rand; the default emits no token and logs no secret. When it's used, the child prints it to its own stderr — keep it out of any log sink spawn controls.
    • Bind failure: exit 1, empty stdout, actionable stderr.
    • cmd/notebook/service_test.go:23 is the $0 reference for the reader loop.

    Nothing above changes the verb's scope. No code proposed; this is the parser and its failure modes pinned down so the first real spawn isn't where they're found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:connectarea:launcharea:lifecycleenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions