Repository navigation
update: notify when a newer stable release exists - #424
Conversation
37788b2 to
caaa70a
Compare
terencechotai2-commits
left a comment
There was a problem hiding this comment.
Reviewed at caaa70a9. I built it locally (Go 1.25.13, linux/amd64) with -X main.version=v0.1.0 and -X main.updateStablePointerURL pointed at a local server, then exercised the worker directly.
Detached worker: never holds the caller's descriptors ✅
- The child's stdin, stdout and stderr are left unset, so
os/execconnects them to/dev/null. - Every descriptor above 2 is marked
FD_CLOEXECbefore the fork. That matters because Go'sforkExecdoesn't close inherited non-CLOEXEC descriptors on its own. - The lock file, opened by Go with
O_CLOEXEC, is not inherited. Setsidon unix.DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUPon Windows, where Go's explicit handle list covers inheritance.- The child is reaped by a goroutine.
Repro, with a pointer server that stalls so the worker outlives the parent (about 3 s, the fetch timeout):
| caller | this PR | control: worker given caller's stdout/stderr | control: CLOEXEC sweep removed |
|---|---|---|---|
heygen config list | cat |
0.01 s, worker still alive | 3.02 s (hangs) | 0.01 s |
out=$(heygen config list) |
0.01 s | 3.02 s | 0.01 s |
heygen config list 3>&1 | cat |
0.02 s | 3.02 s | 3.02 s (hangs) |
Both controls hang, so the repro does detect each failure mode, and this head returns immediately in every case.
Other asks
- No network on the hot path: the parent only reads the cache, takes a non-blocking
flock, and spawns. The fetch happens only in the worker (3 s timeout, 64-byte cap, must be a stable tag). - Opt-out: with
CI=true,CI=1,GITHUB_ACTIONS=true,HEYGEN_NONINTERACTIVE=1,HEYGEN_NO_UPDATE_CHECK=1orupdate_check = falsein config, no cache was written and no worker spawned. WithCI=falseorCI=0the check stays on.--version,--help,help,__complete,completionandupdateare all skipped. - Notice on stderr only: the next run printed
{"notice":{"code":"cli_update_available",...}}on stderr. Its stdout was byte-identical to the previous run's and parses as JSON.--humanprintedNote: heygen v0.2.0 is available; .... A third run printed nothing, so the once-a-day limit holds. - Concurrency: a cold-cache 40-way burst produced 1 pointer fetch in 9 of 10 trials. See the inline comment for the 10th.
Low: now is sampled before the lock, so the future-timestamp guard can double-fire under concurrent runs
Inline comment below, with the fix I tested.
Info
- CI detection covers
CI/GITHUB_ACTIONS. Jenkins (JENKINS_URL), Azure Pipelines (TF_BUILD) and CodeBuild (CODEBUILD_BUILD_ID) don't setCI, so the check runs there. The cost is a background fetch and maybe a notice line in logs, not a hang, so it's only worth adding if those environments matter. HEYGEN_NO_UPDATE_CHECK=0also disables the check, because any non-empty value counts. That matchesHEYGEN_NO_ANALYTICS, so it's consistent; just noting it.
— tai2
| return nil | ||
| } | ||
| n := &updateNotifier{current: current} | ||
| now := updateNow() |
There was a problem hiding this comment.
Low: concurrent invocations can print the notice twice, or spawn two workers.
now is taken at line 86 (and at 119 in finish), before the lock is acquired. The re-check under the lock then compares the cache against that stale now.
Failure sequence:
- Process A acquires the lock, records
NotifiedAt(orLastAttempt) as A'snow, and releases. - Process B sampled its
nowslightly earlier. It gets the lock next and seesNotifiedAt.After(now). - The clock-set-back guard in
noticeDue/checkDuetreats that as elapsed, so B emits a second notice (or spawns a second worker).
Observed with 30–40-way parallel config list bursts (agents fanning out commands is exactly this shape):
- 2 notices in one 30-way burst
- 2 pointer fetches in 1 of 9 measured cold-cache 40-way bursts
With now = updateNow() re-sampled right after defer unlock() in both startUpdateCheck and finish, I saw exactly 1 notice and 1 fetch in all 20 bursts. That's a two-line change. Alternatively, only treat a timestamp as "future" beyond a skew margin (e.g. > now + time.Minute).
The impact is a duplicate notice or extra fetch, not a hang or data loss, so this is non-blocking.
There was a problem hiding this comment.
Fixed in 7559ee8: both startUpdateCheck and finish now read the clock again after taking the lock. TestUpdateCheck_ConcurrentStampBeforeLockIsHonored places a concurrent stamp between the first clock read and the lock, and fails without either clock read or either locked re-check.
|
Small correction to my review's Concurrency line: it should read "exactly 1 pointer fetch in 8 of the 9 cold-cache 40-way bursts I could measure" (the first trial's counter was unreadable), not "9 of 10". The inline comment has the corrected numbers. The finding itself is unchanged. — tai2 |
jrusso1020
left a comment
There was a problem hiding this comment.
Approving at caaa70a9. The detached worker holds nothing the caller reads, on every OS this ships to, and the gating and cache logic are sound. There are two should-fixes, both small and neither a hang. The first is tai2's duplicate-notice finding, which I confirmed deterministically.
The worker and the caller's descriptors (the hardest-look item)
- Linux, reproduced end to end. I built a binary stamped
v0.1.0against a local pointer server that stalls for 10 s, so the worker outlives the CLI. Every case below used a fresh config dir:
| caller | this PR | control: closeInheritedOnExec a no-op |
|---|---|---|
heygen config list | cat |
0.08 s | 0.01 s |
heygen config list 2>&1 | cat |
0.10 s | 0.02 s |
x=$(heygen config list) |
0.01 s | 0.01 s |
x=$(heygen config list 3>&1) |
0.01 s | 3.01 s |
(heygen config list 7>&1) | cat |
0.01 s | 3.01 s |
The worker was still alive in every row of this PR's column. The standard streams are safe even in the control, because exec.Cmd with nil streams opens the null device. The extra descriptors are what closeInheritedOnExec protects, and the control hangs for exactly the 3 s fetch timeout.
- macOS.
/dev/fdlists every open descriptor there.TestStartDetached_DoesNotHoldCallerStreamspasses an extra non-close-on-exec pipe throughExtraFiles, and it is green onmacos-latest. The release targets are only linux, darwin and windows (.goreleaser.yaml), so the BSDfdescfscaveat doesn't apply. - Windows. In Go 1.25,
syscall/exec_windows.go:370-374passesCreateProcessaPROC_THREAD_ATTRIBUTE_HANDLE_LISTholding only the child's three std handles, which are NUL here. So no caller handle can leak, and a no-opcloseInheritedOnExecis correct.DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUPgives the worker no console and keeps it out of a caller's Ctrl-C. - Exec leaking extra files.
ExtraFilesis unset. Go opens its own descriptors close-on-exec, which includes the lock file held across the spawn, so the worker never inherits the lock either. - The residual bound.
Setsidand a new process group do not leave a Windows job object or a Linux cgroup. A harness that waits on the whole tree rather than on pipes (PowerShellStart-Process -Wait, a systemd scope) would wait for the worker. That wait is bounded by the 3 s fetch context plus the 2 s lock wait. This is worth one line in the doc comment as the stated worst case. - Untested. Turning
Setsidoff survives the suite. The Ctrl-C and hangup claim is reasoned, not tested. I wouldn't add a TTY test for it.
Should-fix 1: duplicate notice or second worker in a burst (tai2's finding, confirmed)
finish and startUpdateCheck read updateNow() before taking the lock, and noticeDue and checkDue treat a timestamp in the future as elapsed. Suppose a peer read its clock a moment later but took the lock first. This invocation then takes the free lock, re-reads, sees the peer's stamp as "in the future", and repeats. I confirmed it with an in-package probe at updateTestNow:
- a cached
NotifiedAtofupdateTestNow + 1msemits a secondcli_update_availablenotice; - a cached
LastAttemptof+1msspawns a second worker.
The fix is to read now := updateNow() again after lockUpdateCache succeeds, in both places. Alternatively, treat a stamp as clock skew only when it is more than an interval ahead. Relatedly, deleting the locked re-check in startUpdateCheck also survives the suite, so a test that seeds a fresh cache between the fast path and the lock would pin both.
Should-fix 2: TestUpdateCheck_NoticeRequiresRecordedTimestamp never reaches the write
It repoints HEYGEN_CONFIG_DIR at a regular file before finish, so finish's fast-path readUpdateCache() already returns an empty cache and exits before the lock. I mutated finish to emit even when writeUpdateCache fails, and the suite still passed.
A version that exercises the branch:
- Keep the seeded dir and pre-create
update_check.json.lock. chmod 0500the dir, skipping on Windows and when root. Reads and the lock still work, andCreateTempfails.
The body says every guarded line was broken and watched fail. This one wasn't.
Nits
- Windows rename against an unlocked reader. Go's
os.Openon Windows shares only READ|WRITE, not DELETE (syscall_windows.go:396). SoMoveFileExfails while another invocation is inside its unlocked fast-pathreadUpdateCache. Every write path fails closed, so the cost is one lost worker result, which is retried after 1 h, or one skipped notice. ThewriteUpdateCachecomment ("an unlocked reader sees the old cache or the new one") is a Unix statement; a clause saying Windows loses the write instead would keep it true. - Reuse.
updateNoticeMessagerepeatsrunUpdateCheck's"heygen %s is available; you have %s"(update.go:177). One shared format would keepheygen update --checkand the notice from drifting. Everything else reuses what exists:validateCurrentVersion,updateChannel,isVersionGreater,releaseTaggedVersion,detectInstallMethod, theanalyticsEnabledgating pattern, and the config key plumbing. TheenvTruthyextraction fromnonInteractiveEnvFuncis a good consolidation.
Checked and sound
- The CDN pointer and
heygen update(GitHub via selfupdate) can't disagree the wrong way.release-stable.ymlruns GoReleaser (the GitHub release) before it writess3://heygen-public/cli/stable. So the notice never names a versionheygen updatecan't find. - CI, agent and opt-out gates. I verified end to end that
CI=truewrites no cache and starts no worker. Agents stay on by design.origin.Detectis attribution, not a gate, so not reusing it is right. - Cache. The file and the lock are
0600in a0700dir, which I checked on disk. A bad, oversized or wrong-schema file reads as absent. The attempt is recorded before the spawn. The kernel releases the advisory lock if a process dies. - End to end with a fast pointer:
- run 1 records the check;
- run 2 prints one JSON notice;
- run 3 is silent;
--humanprints aNote:line with stdout clean;- no
__update-checkprocess remains.
Tests
go build,go vetandgo test ./...pass locally on Go 1.25.13. CI tests are green on Linux, macOS and Windows.- Mutations: 15 of 20 caught. The five survivors:
- turning
Setsidoff; - deleting the locked re-check in
startUpdateCheck; - emitting before the write succeeds (should-fix 2);
- accepting the worker argument with extra args;
- dir mode
0755inwriteUpdateCache.lockUpdateCachealready made the dir0700, so this one is equivalent.
- turning
— Rames
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
caaa70a to
7559ee8
Compare
jrusso1020
left a comment
There was a problem hiding this comment.
Re-review at 7559ee8. Approving. Both of my round-one should-fixes are resolved. The rebase left the reviewed diff byte-identical: git diff eaddf06 caaa70a and git diff 02d9074 9773a27 match exactly.
The second clock read in finish
This is correct. Every stamp in the file is written by a process holding the same lock, from a clock it read while holding it:
LastAttemptinstartUpdateCheck;NotifiedAtinfinish;CheckedAtin the worker, whereupdateNow()runs atapply, after the lock.
So a read taken after this process gets the lock is never earlier than a peer's stamp on the same host. The one exception is a real step back of the wall clock, and treating a future stamp as elapsed exists for that case. The stamps survive JSON with nanoseconds, and After compares wall-clock time once one side has no monotonic reading, so this ordering is what the check sees.
The unlocked check before the lock still uses the earlier read, and that's fine. It can wrongly say "due", which the locked check then corrects. It can wrongly say "not due" only when a boundary falls inside that gap of a millisecond or less, and the next invocation then handles it.
Tests
- Full suite:
go test -count=1 ./...passes. - Mutations: 6 of 7 caught.
- Dropping either clock re-read fails
ConcurrentStampBeforeLockIsHonored, on itsworker spawnornoticecase. So does dropping either locked re-check. - Emitting the notice even when the write fails now fails
NoticeRequiresRecordedTimestamp. - Recording a stale
LastAttemptis caught. - The survivor is that
finishwritingNotifiedAt = now - 1hpasses, so nothing pins the stamped value. That gap is older than this commit, and an assert on the savedNotifiedAtwould close it. Optional.
- Dropping either clock re-read fails
- Read-only test: the
0500test runs on the Linux and macOS runners, which are not root. It skips only on Windows and as root. Creating the lock file first is what lets the lock succeed in the read-only dir. - Real processes: I built
caaa70aand7559ee8withversion=v0.9.0and ran 6 bursts of 40 parallelconfig listruns against a due cache. Both printed exactly one notice per burst. The race is narrow in practice becausefinishskips when the lock is busy. The deterministic test is what proves the fix, not the burst.
The nits are covered too: update --check and the notice now share updateAvailableMessage, the comment on the Windows rename failing closed is in, and the comment on the worker's lifetime cap is in.
— Rames
terencechotai2-commits
left a comment
There was a problem hiding this comment.
Re-review at 7559ee8: looks good, no findings. This resolves my earlier finding about the clock being read before the lock.
What changed since caaa70a9
- A range-diff shows both earlier commits are identical after the rebase. Only
7559ee8is new, touchingupdate.go,update_notice.goand the test. startUpdateCheckandfinishboth read the clock again after taking the lock. Every stamp written by an earlier lock holder was taken before that holder released the lock, so the fresh read is never behind any stamp in the cache. The "future stamp counts as elapsed" guard can no longer fire on another run's write.
The second clock read in finish (the part you asked about)
- The fast-path check uses the earlier read, but it only decides whether to take the lock.
- A false "due" is caught by the locked re-check.
- A false "not due" only happens when the notice became due in the microseconds between the two reads. The cost is that the notice waits for the next run, which is harmless.
Checks I ran
| check | old head caaa70a9 |
new head 7559ee8 |
|---|---|---|
| notices per 40-way warm burst | 2 in 1 of 10 bursts | exactly 1 in 20 of 20 bursts, plus 9 of 9 in an earlier run |
| fetches per warm burst (including the seed run) | 1 in all 10 | 1 in all 29 |
| worker fetches per cold 40-way burst (server delay 0.3 s) | 1 in all 10 | 1 in all 10 |
- Mutation check: I deleted each new clock read separately.
TestUpdateCheck_ConcurrentStampBeforeLockIsHonoredfails both times, so the test does guard both sides. go test ./cmd/heygen/andgo vetpass.- Only comments changed around the worker spawn and the stdio code, so I didn't re-run the hang repro.
Also checked: the shared updateAvailableMessage produces the same wording as before (heygen v0.2.0 is available; you have v0.1.0. Run heygen update to upgrade.). The notice still goes to stderr only.
— tai2
Scope
Surfaces: CLI | Module: Update / release channel
Part of PRINFRA-1328. Builds on #423 (merged), which adds the
Noticelevel this emits through.Summary
Nothing tells a human or an agent that their CLI is out of date:
heygen updateexists, but only helps someone who already knows to run it. A release build now checks the CDN's stable pointer at most once a day from a short-lived detached worker process, and when a newer release exists prints acli_update_availablenotice after a command finishes. The check never delays a command and never changes its exit code.How it works
The spine is that the command never waits for the check. The work is split across two processes:
startUpdateCheck(the CLI)heygen __update-checkdetached and does not wait for it.runUpdateCheckWorker(the child)finish(the CLI)So the notice usually appears on the run after a check completes (or on the same run, if the worker beat the command). Every due check completes, including after a 6 ms local command.
Three clocks live in a small cache (
~/.heygen/update_check.json):checked_at+latestlast_attempt+failuresnotified_atWhat never checks: anything that isn't a stable release build (dev builds, local builds), CI (
CI,GITHUB_ACTIONS,HEYGEN_NONINTERACTIVE), the opt-out (HEYGEN_NO_UPDATE_CHECK=1orheygen config set update_check false), and the skip list (__complete,completion,help,update,--version,--help,--request-schema,--response-schema).Design decisions
A detached worker, not an in-process goroutine. The first version raced a goroutine against the command and dropped it if unfinished, so a fast local command could never complete a check. PRINFRA-1328's "no subprocess" line traced back to a design review objecting to an unspecified child, not to children as such; HyperFrames' CLI already refreshes its update cache from a detached child. The worker is specified here: hidden
__update-checkargument dispatched at the top ofmain()(no telemetry notice, no analytics event), 3 s fetch timeout, waits up to 2 s for the lock since nobody waits on it, and its failure only costs one backoff interval because the attempt is recorded before it starts.The worker never holds anything the caller is reading. A child that inherits the caller's stdout, stderr, or another pipe keeps a caller that reads to EOF (
$(...), a pipe, an agent harness) waiting until the child exits. Its standard streams go to the null device, and on Unix every inherited descriptor above 2 is marked close-on-exec before spawning (Windows passes CreateProcess an explicit handle list). Doing this in the parent rather than closing descriptors at worker startup avoids touching descriptors the Go runtime may own; the close-on-exec flag only affects later children of this process. It starts in a new session (Unix) or a new, console-less process group (Windows), so a Ctrl-C aimed at the caller does not reach it, and it is reaped in the background so a long-running command such asvideo create --waitnever holds a zombie.The source is the CDN pointer, not GitHub. It is the file
install.shresolves "latest" from, so the notice can never name a release the installer would not serve. It also avoidsgithubReleaseToken(), which shells out togh auth token, and GitHub's 60 req/hr unauthenticated limit.The skip list reads raw
os.Args. The decision is made before Cobra parses anything, and Cobra registers__completeonly during execution.--headersis the root's only value-taking persistent flag, so its value is skipped when finding the subcommand.Off in CI, on for agents. A CI job gets a fresh HOME, so the cache never persists and every job's first command would check. Agent shells are deliberately not treated as CI: they are the audience.
The cache fails closed. If the attempt cannot be recorded, no worker starts, because nothing would stop the next run starting another. A notice is emitted only after its timestamp is written, or an unwritable config dir would repeat it on every command.
An OS advisory lock, not a lock file. Every cache read-modify-write holds
flock(Unix) orLockFileEx(Windows) onupdate_check.json.lockand re-reads both the cache and the clock under it. The cache re-read stops concurrent invocations and workers overwriting each other's results; the clock re-read stops a run whose earlier clock read trails a concurrent run's fresh stamp from mistaking it for a clock set back, which would print a second notice or start a second worker. The kernel releases the lock if a process dies, so there is no staleness timeout; a lock-file lease with stale-breaking was tried first and rejected in review because two processes can both break the same stale lock. The CLI never waits for the lock: if it is busy, that invocation skips its cache work.npm installs get a generic hint. Homebrew gets
brew upgrade heygen. Thenpminstall method is onlydetectInstallMethod'snode_modulesheuristic; nothing publishes this CLI to npm, so there is no command to name.Deferred: one atomic-write helper. The cache write and the credentials store (
internal/auth/credentials_file.go) both do temp-file + rename. Consolidating them means changing the credential store inside a feature PR, so it is left for a follow-up.Testing
21 tests in
cmd/heygen/update_notice_test.go, one per invariant: the skip list, the CI and opt-out gates, stable-only builds, check freshness and backoff boundaries, notice throttling, the worker's outcome accounting and its wait for a busy lock, a worker never starting when its attempt could not be recorded, unusable caches, fail-closed writes, owner-only mode, the homebrew hint, pointer validation, and the lock (busy from either side, a leftover lock file blocking nothing, a concurrent run's stamp landing between this run's first clock read and its lock). Two process-lifecycle tests: the test re-runs its own binary as a helper that detaches a 10 s system command (sleep, orpingon Windows, since Windows cannot delete a running test binary) and exits, and the caller's stdout, stderr and an extra non-close-on-exec pipe must all reach EOF while that child is still running; and (Linux) a finished child leaves no zombie under a live parent. Plus a config test for theupdate_checkkey. Guarded lines were deliberately broken and their tests watched fail. Review found two that survived (emitting a notice when its write fails, and the locked re-checks); both now have tests that fail without them. The remaining known survivors areSetsid(reasoned, not tested) and accepting the worker argument with extra arguments. Lint is clean for Linux, macOS and Windows, and the new tests pass repeatedly under-race.End to end, a binary stamped
v0.8.1against the live CDN pointer (v0.9.0): a 6 msconfig listcaptured with$(...)returned at once; ~50 ms later the worker had cachedv0.9.0; the next run printed the notice and the one after was silent; no worker process remained; with an unreachable proxy the worker recorded one failure. On the same final binary: four concurrent invocations produced exactly one notice,--humanrendered aNote:line with stdout clean, and--request-schema,__complete,HEYGEN_NO_UPDATE_CHECK=1andCI=truewrote no cache and started no worker.🤖 Generated with Claude Code