Skip to content

update: notify when a newer stable release exists - #424

Merged
somanshreddy merged 3 commits into
mainfrom
10-07-update_staleness_notice
Oct 7, 2026
Merged

somanshreddy merged 3 commits into
mainfrom
10-07-update_staleness_notice

Conversation

@somanshreddy

@somanshreddy somanshreddy commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

Scope

Surfaces: CLI | Module: Update / release channel

Part of PRINFRA-1328. Builds on #423 (merged), which adds the Notice level this emits through.

Summary

Nothing tells a human or an agent that their CLI is out of date: heygen update exists, 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 a cli_update_available notice 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:

Who When What it does
startUpdateCheck (the CLI) before the command runs Decides whether a check is due. If so, records the attempt under the cache lock, then starts heygen __update-check detached and does not wait for it.
runUpdateCheckWorker (the child) concurrently, for ~50 ms Fetches the pointer, then writes the outcome to the cache under the lock.
finish (the CLI) after the command, before exit Reads the cache; if a notice is due, records it under the lock and emits it.

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):

Field Meaning Rule
checked_at + latest last successful check and what it found fresh for 24 h; no worker while fresh
last_attempt + failures last spawn, and consecutive failures 1 h after an attempt that never reported; after failures 2 h, 4 h, ... capped at 24 h
notified_at last notice shown at most one notice per 24 h

What 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=1 or heygen 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-check argument dispatched at the top of main() (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 as video create --wait never holds a zombie.

The source is the CDN pointer, not GitHub. It is the file install.sh resolves "latest" from, so the notice can never name a release the installer would not serve. It also avoids githubReleaseToken(), which shells out to gh 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 __complete only during execution. --headers is 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) or LockFileEx (Windows) on update_check.json.lock and 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. The npm install method is only detectInstallMethod's node_modules heuristic; 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, or ping on 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 the update_check key. 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 are Setsid (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.1 against the live CDN pointer (v0.9.0): a 6 ms config list captured with $(...) returned at once; ~50 ms later the worker had cached v0.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, --human rendered a Note: line with stdout clean, and --request-schema, __complete, HEYGEN_NO_UPDATE_CHECK=1 and CI=true wrote no cache and started no worker.

🤖 Generated with Claude Code

@somanshreddy
somanshreddy force-pushed the 10-07-update_staleness_notice branch from 37788b2 to caaa70a Compare October 7, 2026 06:34

@terencechotai2-commits terencechotai2-commits left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/exec connects them to /dev/null.
  • Every descriptor above 2 is marked FD_CLOEXEC before the fork. That matters because Go's forkExec doesn't close inherited non-CLOEXEC descriptors on its own.
  • The lock file, opened by Go with O_CLOEXEC, is not inherited.
  • Setsid on unix. DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP on 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=1 or update_check = false in config, no cache was written and no worker spawned. With CI=false or CI=0 the check stays on. --version, --help, help, __complete, completion and update are 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. --human printed Note: 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 set CI, 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=0 also disables the check, because any non-empty value counts. That matches HEYGEN_NO_ANALYTICS, so it's consistent; just noting it.

— tai2

return nil
}
n := &updateNotifier{current: current}
now := updateNow()

@terencechotai2-commits terencechotai2-commits Oct 7, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Process A acquires the lock, records NotifiedAt (or LastAttempt) as A's now, and releases.
  2. Process B sampled its now slightly earlier. It gets the lock next and sees NotifiedAt.After(now).
  3. The clock-set-back guard in noticeDue / checkDue treats 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@terencechotai2-commits

Copy link
Copy Markdown

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 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.0 against 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/fd lists every open descriptor there. TestStartDetached_DoesNotHoldCallerStreams passes an extra non-close-on-exec pipe through ExtraFiles, and it is green on macos-latest. The release targets are only linux, darwin and windows (.goreleaser.yaml), so the BSD fdescfs caveat doesn't apply.
  • Windows. In Go 1.25, syscall/exec_windows.go:370-374 passes CreateProcess a PROC_THREAD_ATTRIBUTE_HANDLE_LIST holding only the child's three std handles, which are NUL here. So no caller handle can leak, and a no-op closeInheritedOnExec is correct. DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP gives the worker no console and keeps it out of a caller's Ctrl-C.
  • Exec leaking extra files. ExtraFiles is 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. Setsid and 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 (PowerShell Start-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 Setsid off 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 NotifiedAt of updateTestNow + 1ms emits a second cli_update_available notice;
  • a cached LastAttempt of +1ms spawns 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:

  1. Keep the seeded dir and pre-create update_check.json.lock.
  2. chmod 0500 the dir, skipping on Windows and when root. Reads and the lock still work, and CreateTemp fails.

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.Open on Windows shares only READ|WRITE, not DELETE (syscall_windows.go:396). So MoveFileEx fails while another invocation is inside its unlocked fast-path readUpdateCache. Every write path fails closed, so the cost is one lost worker result, which is retried after 1 h, or one skipped notice. The writeUpdateCache comment ("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. updateNoticeMessage repeats runUpdateCheck's "heygen %s is available; you have %s" (update.go:177). One shared format would keep heygen update --check and the notice from drifting. Everything else reuses what exists: validateCurrentVersion, updateChannel, isVersionGreater, releaseTaggedVersion, detectInstallMethod, the analyticsEnabled gating pattern, and the config key plumbing. The envTruthy extraction from nonInteractiveEnvFunc is a good consolidation.

Checked and sound

  • The CDN pointer and heygen update (GitHub via selfupdate) can't disagree the wrong way. release-stable.yml runs GoReleaser (the GitHub release) before it writes s3://heygen-public/cli/stable. So the notice never names a version heygen update can't find.
  • CI, agent and opt-out gates. I verified end to end that CI=true writes no cache and starts no worker. Agents stay on by design. origin.Detect is attribution, not a gate, so not reusing it is right.
  • Cache. The file and the lock are 0600 in a 0700 dir, 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;
    • --human prints a Note: line with stdout clean;
    • no __update-check process remains.

Tests

  • go build, go vet and go 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 Setsid off;
    • deleting the locked re-check in startUpdateCheck;
    • emitting before the write succeeds (should-fix 2);
    • accepting the worker argument with extra args;
    • dir mode 0755 in writeUpdateCache. lockUpdateCache already made the dir 0700, so this one is equivalent.

— Rames

@somanshreddy
somanshreddy changed the base branch from 09-18-notice_output_level to main October 7, 2026 07:10
@somanshreddy
somanshreddy force-pushed the 10-07-update_staleness_notice branch from caaa70a to 7559ee8 Compare October 7, 2026 07:17

@jrusso1020 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • LastAttempt in startUpdateCheck;
  • NotifiedAt in finish;
  • CheckedAt in the worker, where updateNow() runs at apply, 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 its worker spawn or notice case. So does dropping either locked re-check.
    • Emitting the notice even when the write fails now fails NoticeRequiresRecordedTimestamp.
    • Recording a stale LastAttempt is caught.
    • The survivor is that finish writing NotifiedAt = now - 1h passes, so nothing pins the stamped value. That gap is older than this commit, and an assert on the saved NotifiedAt would close it. Optional.
  • Read-only test: the 0500 test 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 caaa70a and 7559ee8 with version=v0.9.0 and ran 6 bursts of 40 parallel config list runs against a due cache. Both printed exactly one notice per burst. The race is narrow in practice because finish skips 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 terencechotai2-commits left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 7559ee8 is new, touching update.go, update_notice.go and the test.
  • startUpdateCheck and finish both 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_ConcurrentStampBeforeLockIsHonored fails both times, so the test does guard both sides.
  • go test ./cmd/heygen/ and go vet pass.
  • 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

@somanshreddy
somanshreddy merged commit f5ed0fc into main Oct 7, 2026
9 checks passed
@somanshreddy
somanshreddy deleted the 10-07-update_staleness_notice branch October 7, 2026 07:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants