* feat(roles): issueops.Heartbeater role on the dolt, embedded and uow legs
Adds issueops.Heartbeater.Heartbeat(HeartbeatRequest{Actor, IssueID}) ->
HeartbeatResult{IssueID, Holder, HeartbeatAt, LeaseExpiresAt, Rearmed},
the lease refresh behind `bd heartbeat`, as its own role with its own
accessor.
- One body: internal/storage/issueops.ExecuteHeartbeatInTx validates
(*HeartbeatFieldError for a blank/over-long actor or empty id), refuses
a wisp, then runs RenewLeaseInTx, which is HeartbeatIssueInTx's body
reporting the renewal. HeartbeatIssueInTx is now a wrapper, so the legacy
HeartbeatIssue legs answer the same text and sentinels.
- The refresh is fenced on the holder AND on the live claim: after the
holder-fenced UPDATE, a read in the same transaction requires the issue
to be in_progress under the holder (the `update leases set` prefix and
the one IF() the Postgres dialect rewrites are unchanged; a Postgres port
should expect more serialization retries from that read). A refusal deletes the caller's orphaned lease
row, and the legs commit that refusal.
- A refresh writes only the lease row: no row_lock, version, updated_at,
event, journal entry, Dolt commit or hook. A re-arm (a live hand-doled
claim with no lease row the caller holds) is recorded as a mutation:
row_lock reminted, updated_at stamped, a lease_rearmed event, a journal
entry, a version, a Dolt commit (LeaseRearmVersionCommit) and on_update.
The remint makes a re-arm collide with a racing release or close instead
of leaving an orphaned lease on an open or closed issue (a pre-existing
race on every Dolt route). Rearmed is true only when a row was created:
a same-second refresh (0 changed rows on embedded Dolt) or a holder
spelled differently refreshes the existing row in place and keeps its
granted_at/granted_node. Reported times are rounded to whole seconds,
the stored values; the binds stay unrounded so a same-second refresh is
never a 0-row UPDATE on Dolt.
- Typed refusals: an absent id is ErrNotFound; a foreign holder is
*LeaseConflictError{Holder} wrapping ErrAlreadyClaimed; a wisp
(Ephemeral) or no live claim is *LeaseConflictError wrapping the new
ErrLeaseNotHeld, which also matches ErrNotClaimable.
- Legs: DoltStore and EmbeddedDoltStore through the issue-operation
funnel (DOLT_ADD of the named tables, then DOLT_COMMIT -m, after the SQL
commit); uow.NewHeartbeater through the new uow.RunTxScoped: a refresh or
a refusal commits with the plain SQL COMMIT (no working-set scan, no Dolt
commit, nothing another writer left uncommitted is swept), and a re-arm
commits through the new ScopedCommitter (DOLT_ADD of exactly its tables,
DOLT_COMMIT -m, never -Am). The legacy HeartbeatIssue doors commit a
re-arm the same way and keep a refusal's orphan delete, and the
proxied-server `bd heartbeat` route runs the role's body with the same
scoped commit.
- Census: storage.Storage gains Heartbeater(); HookFiringStore wraps it
(fires on_update for a re-arm only, RoleFiresHooks knows it), telemetry
wraps it, httpapi.timedProvider, uow.notifyingProvider (records a re-arm)
and externaldeps.uowProvider build it; the journal and version guards
list the heartbeat family as entry points; the httpclient unsupported
shell is regenerated and Heartbeater sits on its unsupported allowlist
until the wire lands.
Conformance: RunHeartbeater* (18 cases) on dolt, embedded dolt and uow:
refresh post-state with the stored times pinned to the result; no
row_lock/current_revision/updated_at/events/journal/issue_versions/
version-control/hook change; a guarded write with the pre-heartbeat
revision still lands; foreign holder refused against an aged lease;
refused after close/release/reclaim/status move; wisp refused; hand-doled
claim re-armed as a mutation; same-second heartbeat is not a re-arm;
orphaned leases on released, closed and reassigned issues refused and
deleted; a refresh and a refusal against a dirty working set make no
commit and leave the other writer's change uncommitted, and a re-arm
commits only its own tables; absent id; request rules; no request mutation. The http leg is
waived until the wire lands.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(httpapi): POST /v0/beads/issues/{id}:heartbeat behind issues.heartbeat
Publishes issueops.Heartbeater on bd serve as heartbeatIssue, the served
lease refresh behind `bd heartbeat`.
- Spec: the operation, HeartbeatIssueRequest {actor} and
HeartbeatIssueResponse {id, holder, heartbeat_at, lease_expires_at,
rearmed}; no `revision` (a refresh writes nothing to the row) and no
expected_version (the fence is the holder and the live claim).
issues.heartbeat joins the capability vocabulary and lease_not_held
(409) the Problem.code list; `reason: ephemeral` qualifies it for a
wisp. apigen and the wire-shape golden are regenerated; the golden diff
is additive only, so wire_revision stays 2.
- Server: route row on the custom-method dispatcher, handleHeartbeat in
heartbeat.go (claim's actor rules via bodyActor, unknown member and
query refusals), Config.Heartbeater as a required role (sourceRoles,
roleSourceNames, the per-request uow.HeartbeaterSource accessor).
failHeartbeat maps *LeaseConflictError typed fields: a foreign holder
is the claim's conflict shape (already_claimed + assignee +
issue_status); no live claim, a wisp included, is the new
lease_not_held (+ issue_status, + reason: ephemeral for a wisp), matched
before the generic arms so ErrLeaseNotHeld's ErrNotClaimable never
surfaces as not_claimable. Its detail names the one state the refusing
transaction found (closed, open and not claimed, an ephemeral wisp, ...).
- bd serve wires the role from its peeled store (serveRoleSource gains
Heartbeater); the serve stub stores, the corpus and e2e harnesses, the
served harness and the encode oracle bind it.
- Wire client vocabulary: OpHeartbeatIssue/issues.heartbeat and
MethodHeartbeat are CLASSIFIED (the capability set-equality gate),
ReasonEphemeral is pinned to the server's, and lease_not_held rebuilds
*LeaseConflictError{Status, Ephemeral} wrapping ErrLeaseNotHeld in the
native words (the code-table set-equality gate). No accessor yet.
Tests: heartbeat_test.go (request mapping and projection, edge refusals,
every role refusal with its code, members and state-specific detail, the
code row, the capability). The served-http Heartbeater leg
(served_heartbeater_test.go, 18 cases) runs the contract against a real
bd serve through a test-local dial over the store's own dispatch, and the
http-leg waivers are deleted.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(http): bd heartbeat over http through httpclient.Heartbeater
The client leg of the served lease refresh, and `bd heartbeat` on the
role for every route.
- httpclient.Store.Heartbeater (heartbeater.go) dials POST
/v0/beads/issues/{id}:heartbeat through Store.dispatch, so
issues.heartbeat is preflighted: an older server is refused BEFORE the
dial with *wire.CapabilityError naming the token (unwraps to
*storage.ErrUnsupported{Capability: "issues.heartbeat"}); it never falls
back to a re-claim or a metadata stamp.
- The role's request rules are restated before the dial
(validateHeartbeatRequest, pinned to
storeops.ValidateHeartbeatRequest): blank/over-long actor, empty id, each
a *HeartbeatFieldError.
- Problem mapping: already_claimed (which the shared table rebuilds as the
claim's ClaimConflictError) becomes *issueops.LeaseConflictError naming
the holder and wrapping ErrAlreadyClaimed, in the native words ("issue
already claimed by <holder>"); lease_not_held already arrives as
LeaseConflictError (Ephemeral from `reason`); not_found is ErrNotFound;
invalid_argument on `actor` is the role's field error.
- Idempotent: true, the one write this client marks replayable (a repeat
only moves the expiry later; a replay after a reclaim fails the fence).
- Legacy Store.HeartbeatIssue rides the role. Both leave the generated
shell and completeness_test's unsupported allowlist.
- `bd heartbeat` takes Heartbeater() from the resolved store on the direct
routes (dolt, embedded, http) and from the provider's HeartbeaterSource
on the proxied route (exact id resolution in a read unit of work, then
the role); runHeartbeatProxiedServer and heartbeat_proxied_server.go are
deleted. Success output and exit codes are unchanged; refusal text
changes per route (see CHANGELOG).
Tests: heartbeater_test.go (stub server: preflight refusal naming the
token with no POST, request/answer projection, each refusal's typed
mapping including the wisp's reason, the 503 replay, pre-dial validation,
validator parity, the legacy door). served_heartbeater_test.go runs the
18-case contract through env.subject.Heartbeater(), with
HookedHeartbeater wired off a HookFiringStore. TestE2E_HeartbeatOverHTTP:
real bd against an in-process serve: holder ok with revision and
updated_at unchanged and a guarded write with the pre-heartbeat revision
landing; a non-holder refused against an aged lease that stays untouched;
closed, wisp and unclaimed refused, each naming its own state; an older
server's handshake refused naming issues.heartbeat with no write. Corpus
shapes gc-heartbeat, -non-holder, -closed, -wisp pending until
reference_server.json advertises the token. CHANGELOG entry for the whole
track, including the orphaned-lease race fix.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* build(bazel): auto-sync BUILD files
Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/38875641041
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.
* fix(heartbeat): roll back a no-issue refusal; restate refresh vs re-arm
Review fixes for #7600 (adopt-pr apply-fixes, iterations 1-2).
Legacy HeartbeatIssue doors commit a refusal only when it read the issue.
The dolt and embedded HeartbeatIssue callbacks committed every
LeaseRenewalRefusal, including Found=false (the issue read failed). That
refusal deletes nothing, but it can follow a fast-path UPDATE that
already extended an orphan lease row's expiry, so committing it kept the
extension. issueops.LeaseRenewalRefusalCommits now gates the commit on
Found, the rule the Heartbeater role's HeartbeatRefusalCommits applies.
New tests on both legs pin both arms: a no-issue orphan's expiry is
unchanged, and a released issue's orphan is deleted.
Refresh vs re-arm contract docs. Comments, Long help, the OpenAPI spec
and the generated apigen still said every heartbeat writes only the
lease row, makes no Dolt commit and fires no hook. A re-arm is recorded
as a mutation: it remints the revision, records an event and a version
entry, commits once (LeaseRearmVersionCommit) and fires on_update
through the wrapping hook decorator. Restated in domain, uow, issueops,
storage.go (why RoleFiresHooks answers true, so bd serve takes the
heartbeater off a peeled store), cmd/bd heartbeat and serve, httpapi,
httpclient, the spec (apigen regenerated), and the conformance and
contract-test docs.
Minor review findings:
- The 409 already_claimed and lease_not_held details now end "nothing
on the issue was written": the refusal may have deleted and committed
the caller's orphan lease row.
- docs/multi-agent/federation.md and the CHANGELOG entry describe the
spelling-mismatch heartbeat: the row is refreshed in place and keeps
granted_at and granted_node; only a re-arm stamps this node. The
embedded spelling test pins both columns, and the lease.go comments
say "refreshed in place" instead of "re-arms".
- The refusal's orphan delete judges the holder under actorMatches, as
the in-place refresh does (iteration 2). It matched holder = ? on the
actor as sent, so a dead claim's orphan held under another spelling
of the caller (gastown.mayor, heartbeat as gastown__mayor) survived
the refusal until TTL. The refused closure now reads the row's holder
and deletes that stored holder only when actorMatches(holder, actor).
Both TestHeartbeatIssueCommitsARefusalOnlyWhenItReadTheIssue twins
gain a cross-spelling arm (row deleted) and a control: another
identity's row (gastown.dog-3) survives.
Not changed: `bd heartbeat --json` still omits `rearmed`, since adding
it changes a CLI JSON contract (follow-up). The federation.md paragraph
post-dates the v1.2.2 docs pin, so documenting this main-only behaviour
there is a maintainer call under
engdocs/decisions/2026-07-17-docs-release-pin.md section 1.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(uow): run the scoped re-arm's Dolt commit after the SQL commit
The proxied-server heartbeat commits a re-arm with doltServerTx.CommitScoped,
which ran DOLT_ADD per table and DOLT_COMMIT('-m') INSIDE the open
transaction, before the SQL COMMIT. DOLT_ADD stages whole tables from the
session's transaction root, so that Dolt commit was built from the re-arm's
start snapshot: an issues row another session changed while the re-arm was
open (a write still only in the working set, as in batch mode or before that
writer's own Dolt commit) was staged at its old value, and HEAD disagreed
with the rows every reader sees. This is the LatentLabsSpace/NEXUS#92
ordering the DoltStore funnel (runIssueOperationTxWithMessage) already
avoids, and the review's major finding on this PR.
CommitScoped now commits the SQL transaction first, then stages exactly the
named tables (plus the versioned-history tables) and makes the Dolt commit on
the same pinned connection, the uow twin of doltAddAndCommitPostTx:
- a serialization failure of the SQL COMMIT is still returned, so
RunTxScoped replays the unit of work;
- the Dolt commit runs detached on its own budget and replays only conflicts
that leave nothing behind: serialization failures and Dolt's 1105
"@autocommit transaction rolled back" (new isDoltAutocommitRollbackError,
mirroring the DoltStore classifier of the same name);
- nothing staged, or "nothing to commit", is not an error: a concurrent
writer's Dolt commit already took the row. A "nothing to commit" past the
staged check is logged, as the funnel logs it, so the missing audit line
is explicable;
- any other failure is logged, never returned. The data is committed, and
returning it would make RunTxScoped replay a committed re-arm, which would
then report a refresh. The session is poisoned rather than pooled, since
its state is unknown. uow records no metrics, so that log line is the
drop's only signal; bd.db.post_tx_commit_dropped counts only the funnel's.
Statements go through schema.DrainCall, retiring the local drainCall fork
(review nit).
Tests: five sqlmock tests pin the order (SQL COMMIT before any DOLT_ADD),
the swallow-and-poison path, the 1105 retry, the returned serialization
failure and the empty-commit tolerance; each fails against the previous
CommitScoped. TestIsDoltAutocommitRollbackError carries the DoltStore
classifier's table over to the uow copy, plus the prefix boundary; dropping
the prefix branch, the prefix's period, the 1105 check or the type check
each fails a case. TestHeartbeaterRearmKeepsAConcurrentWrite is the
real-Dolt regression: a change to another issues row made while the
re-arm's transaction is open must be at HEAD after the re-arm's Dolt
commit. Its working-set-only writer fails on the old ordering (dolt
2.1.8); the writer that Dolt-commits its own change passes on both and is
kept as coverage.
Review follow-ups folded in (comments, a file move and a test; the
absorption log line above is the only behaviour change among them):
- the freshRowLock invariant and its row_lock_guard_test.go mirror name the
re-arm as the one deliberate remint without a lifecycle-field change,
load-bearing for the release/close collision;
- httpclient: "a write is never retried" (wire/client.go, stall_retry.go)
and "only a read's answer is yes" (dispatch.go) now allow for the
Idempotent heartbeat, and httpHeartbeater and issueops.HeartbeatResult
document that a replayed heartbeat can report Rearmed false after a
committed re-arm, with the guarded write's revision check as the backstop;
- the proxied route moves back to cmd/bd/heartbeat_proxied_server.go, the
file family cmd/bd/AGENTS.md prescribes;
- the ScopedCommitter and RunTxScoped docs no longer say every other
writer's uncommitted change stays out of the commit: a staged table is
committed whole, so such a change to a named table rides in the re-arm's
commit, as it does in the funnel, and only other tables keep theirs;
- commitStagedTables says its drop is log-only, the absorption is logged,
and the uow classifier gets its table test (see Tests).
Not folded in: the base-owned IssueUseCase.Heartbeat /
IssueSQLRepository.HeartbeatIssue door, dead in production since the
proxied route moved to the Heartbeater role. Its one caller is the
notifying hook-parity test (uow/notifying_test.go), and moving that case
onto the Heartbeater means re-deriving its RenewLease hook semantics, so it
is left for a follow-up.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
125 lines
4.1 KiB
Go
125 lines
4.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
var heartbeatCmd = &cobra.Command{
|
|
Use: "heartbeat <id>",
|
|
Aliases: []string{"hb"},
|
|
GroupID: "issues",
|
|
Short: "Refresh the lease on an issue you hold in_progress",
|
|
Long: `Refresh the lease on an issue you currently hold in_progress.
|
|
|
|
A claim carries a lease that expires after a TTL. A worker keeps its claim alive
|
|
by heartbeating faster than the TTL; once it stops (because it died), the lease
|
|
goes stale and 'bd reclaim' reverts the issue to ready so another worker can pick
|
|
it up. Heartbeat pushes lease_expires_at forward and stamps heartbeat_at = now.
|
|
|
|
Only the current owner may heartbeat. If the lease has already been reclaimed or
|
|
the issue closed, heartbeat fails so the worker learns to stop.
|
|
|
|
Leases live in an ephemeral, node-local table: a heartbeat that refreshes your
|
|
lease writes no Dolt commit and no history, so any cadence comfortably below
|
|
the TTL is fine. Only a re-arm (the first heartbeat of a claim that has no
|
|
lease, such as one set by a plain update) is recorded as a change to the issue
|
|
and committed, once. Leases are only enforceable on the node that granted them;
|
|
cross-machine claim visibility rides the issue's status and assignee, which do
|
|
commit.
|
|
|
|
Examples:
|
|
bd heartbeat bd-123
|
|
bd hb bd-123`,
|
|
Args: cobra.ExactArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
CheckReadonly("heartbeat")
|
|
|
|
evt := metrics.NewCommandEvent("heartbeat")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
ctx := rootCtx
|
|
id := args[0]
|
|
|
|
// One role on every route: the store's own
|
|
// Heartbeater accessor on the direct routes — dolt, embedded dolt and
|
|
// a registered HTTP backend, where it dials issues.heartbeat and an
|
|
// older server is refused before the dial naming the token — and the
|
|
// proxied-server provider's on the proxied one. On every leg a refresh
|
|
// writes ONLY the lease row (no revision remint, no history, no Dolt
|
|
// commit); a re-arm is recorded as a mutation and committed once.
|
|
if usesProxiedServer() {
|
|
return runHeartbeatProxied(ctx, id)
|
|
}
|
|
|
|
result, err := resolveAndGetIssueForMutation(ctx, store, id)
|
|
if err != nil {
|
|
if result != nil {
|
|
result.Close()
|
|
}
|
|
return HandleErrorRespectJSON("resolving %s: %v", id, err)
|
|
}
|
|
if result == nil || result.Issue == nil {
|
|
if result != nil {
|
|
result.Close()
|
|
}
|
|
return HandleErrorRespectJSON("issue %s not found", id)
|
|
}
|
|
defer result.Close()
|
|
|
|
issueStore := result.Store
|
|
heartbeater, err := issueStore.Heartbeater()
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("heartbeat %s: %v", result.ResolvedID, err)
|
|
}
|
|
if _, err := heartbeater.Heartbeat(ctx, issueops.HeartbeatRequest{
|
|
Actor: currentActor(),
|
|
IssueID: result.ResolvedID,
|
|
}); err != nil {
|
|
return HandleErrorRespectJSON("heartbeat %s: %v", result.ResolvedID, err)
|
|
}
|
|
|
|
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
|
|
Command: "heartbeat",
|
|
IssueIDs: []string{result.ResolvedID},
|
|
}); err != nil {
|
|
return HandleErrorRespectJSON("failed to commit: %v", err)
|
|
}
|
|
|
|
SetLastTouchedID(result.ResolvedID)
|
|
|
|
return renderHeartbeatSuccess(result.ResolvedID, result.Issue.Title)
|
|
},
|
|
}
|
|
|
|
// renderHeartbeatSuccess prints the success shape every storage route shares —
|
|
// the direct path and the proxied-server path (runHeartbeatProxied) call
|
|
// exactly this code, so the --json contract workers parse
|
|
// ({"id","status":"heartbeat","owner"}) cannot drift between modes.
|
|
func renderHeartbeatSuccess(id, title string) error {
|
|
if jsonOutput {
|
|
return outputJSON(map[string]string{
|
|
"id": id,
|
|
"status": "heartbeat",
|
|
"owner": currentActor(),
|
|
})
|
|
}
|
|
fmt.Printf("%s Heartbeat %s (lease refreshed)\n", ui.RenderPass("✓"), formatFeedbackID(id, title))
|
|
return nil
|
|
}
|
|
|
|
func init() {
|
|
heartbeatCmd.ValidArgsFunction = issueIDCompletion
|
|
rootCmd.AddCommand(heartbeatCmd)
|
|
}
|