command

package
v0.38.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: BSD-2-Clause Imports: 33 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	DefaultParkRedriveDelay    = 30 * time.Second
	DefaultParkRedriveInterval = 30 * time.Second
)

Default park re-drive timings. The delay is the pause between parking a command and its first re-drive attempt: an outage short enough to clear on its own is then absorbed by one or two attempts instead of hammering a vault-api that is already overloaded. The interval is the cadence of the whole sweep.

View Source
const CompleteTaskCommandOperation base.CommandOperation = task.CompleteCommandOperation

CompleteTaskCommandOperation is the CQRS command operation name for task completion.

View Source
const DefaultReadbackDeadline = 90 * time.Second

DefaultReadbackDeadline is how long a write is given to become visible before the readback calls it a mismatch.

It is deliberately larger than git-rest's commit window: git-rest buffers writes and commits them on a ~30 s cadence (measured 2026-11-16 on nuke dev — commits at 00:40:05, 00:40:35, 00:41:05, 00:41:35, 00:42:05), so the record does not reach the store until the next flush. A deadline shorter than that window would report a mismatch on every ordinary write, which is worse than no detector: a signal that always fires is not a signal. 90 s is three commit windows — enough for a slow flush, far below the seven-hour gap this detector exists to catch.

View Source
const DefaultReadbackInterval = 5 * time.Second

DefaultReadbackInterval is how often pending expectations are checked. It is smaller than the deadline so an expectation is never evaluated late enough to hide the actual landing time.

View Source
const DefaultReadbackRef = "origin/HEAD"

DefaultReadbackRef is the git ref the readback reads.

It is the branch a consumer sees, not the local HEAD: git-rest commits and then pushes, so a commit that failed to push is in HEAD while no consumer can read it. Reading origin/HEAD asks the question the task asks — did the record reach the history others read — and it names the remote's DEFAULT branch, which is `origin/main` on some vaults and `origin/master` on others. Naming either branch literally is wrong for the other half of the fleet: measured 2026-11-19, the previous `origin/main` default made every readback on the `master` vaults (personal, trading, seibert-personal) fail with `500 read_failed`, because the ref does not resolve — so a write that had landed logged `readback: cannot verify` and read as a lost one. `origin/HEAD` is set by `git clone` and resolves to the default branch of whichever vault the controller serves, so one default is correct for every vault.

View Source
const IncrementFrontmatterCommandOperation base.CommandOperation = task.IncrementFrontmatterCommandOperation

IncrementFrontmatterCommandOperation is the CQRS command operation name for atomic field increment.

View Source
const TaskResultCommandOperation base.CommandOperation = "update"

TaskResultCommandOperation is the CQRS command operation name for task result updates.

View Source
const UpdateFrontmatterCommandOperation base.CommandOperation = task.UpdateFrontmatterCommandOperation

UpdateFrontmatterCommandOperation is the CQRS command operation name for partial frontmatter update.

Variables

This section is empty.

Functions

func NewCompleteTaskExecutor added in v0.4.0

func NewCompleteTaskExecutor(
	client vaultapi.Client,
	vaultName string,
	currentDateTime libtime.CurrentDateTimeGetter,
	m metrics.Metrics,
) cdb.CommandObjectExecutorTx

NewCompleteTaskExecutor creates a cdb.CommandObjectExecutorTx that transitions a vault task to status: completed, phase: done with a # Resolution body section carrying the recovery SHA. The watcher publishes this on a build red→green transition (spec 076).

Resolution is by task_identifier (matching the CreateCommand's deterministic UUID5). Idempotent: a task that already carries a # Resolution block is a no-op (second completion does not append a duplicate block, matching the build-fix-close-obsolete-tasks skill's existing guard). vaultName is the controller's VAULT_NAME; a command whose non-empty TargetVault differs is cross-vault traffic and is skipped before the task read.

func NewCreateTaskExecutor

func NewCreateTaskExecutor(
	client vaultapi.Client,
	taskDir string,
	vaultName string,
	currentDateTime libtime.CurrentDateTimeGetter,
	k int,
	resolver result.TaskPathResolver,
	verifier WriteVerifier,
) cdb.CommandObjectExecutorTx

NewCreateTaskExecutor creates a cdb.CommandObjectExecutorTx that materializes a new vault task file for the given task_identifier. If cmd.Title passes validation the file is written at tasks/{title}.md; otherwise it falls back to tasks/{task_identifier}.md. A file that already exists at the resolved path causes ErrTaskAlreadyExists (a benign Failure on the result topic — no overwrite, no git write) UNLESS the existing file's status is terminal ("completed"/"aborted"), in which case a fresh non-terminal task is materialized at that path. Frontmatter must include "assignee" and "status"; missing fields return a wrapped validation error. A command whose TargetVault is empty or malformed is refused with a validation error — it is never resolved to the legacy default, because that fallback deadlocks a task between the non-owning controller and the legacy-default one, and a malformed value is dropped as cross-vault traffic just as silently. The guard runs before ShouldProcess, so it fires on every controller that consumes the command; one such create therefore emits one Failure result per controller. Commands whose TargetVault is non-empty and does not match vaultName are skipped without side effects (no git write, no error, no result event). resolver is the identifier→path index; a nil resolver records nothing and is a test-only value.

func NewExpiredCommandBatchHandler added in v0.19.0

func NewExpiredCommandBatchHandler(
	skip func(*sarama.ConsumerMessage) bool,
	observer ExpiredCommandObserver,
	handler libkafka.MessageHandlerBatch,
) libkafka.MessageHandlerBatch

NewExpiredCommandBatchHandler returns a batch handler that drops the messages skip reports and reports each of them to observer, then passes the remaining messages, in their original order, to handler in a single call.

It replaces libkafka.NewMessageHandlerBatchFilter rather than wrapping it, because that filter takes only the predicate and the handler and therefore has nowhere to report a drop. The partition-and-forward behaviour is otherwise identical, including the context check and the early return when every message in the batch was dropped.

skip must keep the contract libkafka states for it — pure, free of side effects, no state carried across calls — because the returned handler is shared by one consumer goroutine per partition. The observation deliberately does NOT live inside skip: a side effect there would run on every message of every partition concurrently and would couple the predicate's verdict to whatever the observer does. The wrapper observes after the verdict, per dropped message.

A dropped message is JSON-decoded a second time here, to hand the observer the command rather than only the raw bytes. That decode is paid only for dropped messages, which are rare, and it cannot fail in practice: skip returns true only after it decoded the same bytes successfully. The failure branch is kept so that a future predicate with different rules cannot silently swallow the observation.

func NewExpiredCommandSkip added in v0.18.4

func NewExpiredCommandSkip(
	commandExpireDuration time.Duration,
	currentDateTime libtime.CurrentDateTimeGetter,
) func(*sarama.ConsumerMessage) bool

NewExpiredCommandSkip returns a predicate reporting whether msg carries a command whose RequestTime is older than commandExpireDuration. True means the message is dropped; false means it is passed on.

The predicate exists to be composed outside cdb.CreateCommandMessageHandlerBatch. The handler already discards an expired command, but it does so from inside the batch transaction that NewMessageHandlerBatchTxUpdate opens, so the discard costs a bbolt write transaction and its fsync. Composed outside, the same command is dropped before the batch reaches the transaction.

The drop is logged at V(2) with the same wording the handler used, so moving the decision ahead of the transaction does not also silence it — an operator asking why a command never ran still gets the answer. That log is the predicate's only side effect: it carries no state, and glog is safe to call from the per-partition consumer goroutines that share this predicate.

A message that is not valid JSON is kept, so the handler reports the parse error exactly as it would without this filter. A payload that parses but carries no RequestTime is not kept: it unmarshals with a zero RequestTime, the comparison reads that as long expired, and the message is dropped — the same verdict the handler reaches, one step earlier.

A kept message is JSON-decoded twice, here and again inside cdb.NewCommandObjectMessageHandlerTx. That is deliberate: the saving is a whole batch transaction, and the decode is small beside it. Do not "optimise" the second decode away without removing this one too.

func NewIncrementFrontmatterExecutor

func NewIncrementFrontmatterExecutor(
	client vaultapi.Client,
	vaultName string,
	currentDateTime libtime.CurrentDateTimeGetter,
	m metrics.Metrics,
) cdb.CommandObjectExecutorTx

NewIncrementFrontmatterExecutor creates a cdb.CommandObjectExecutorTx that atomically reads the task file, increments the named frontmatter field by delta, and commits. When trigger_count reaches the trigger cap — an explicit max_triggers OR a ref-bearing task (the same predicate the executor's checkTriggerBudget refuses on) — the assignee is cleared (captured into previous_assignee) and a ## Trigger Cap Escalation body section is recorded, so an exhausted task lands where a human can find it instead of parking silently with a live assignee. A plain recurring task with neither max_triggers nor a ref is never capped: its routing assignee survives re-dispatch accumulation. vaultName is the controller's VAULT_NAME; a command whose non-empty TargetVault differs is cross-vault traffic and is skipped before the task read.

func NewTaskResultExecutor

func NewTaskResultExecutor(
	writer result.ResultWriter,
	retryGate PlanningRetryGate,
	vaultName string,
) cdb.CommandObjectExecutorTx

NewTaskResultExecutor creates a cdb.CommandObjectExecutorTx for update commands. Uses cdb.CommandObjectExecutorTxFunc adapter — same pattern as trading command handlers. vaultName is the controller's VAULT_NAME; a result whose target_vault frontmatter (stamped at task create, echoed by the agent) does not match is cross-vault traffic and is skipped before the write scan (no write, no not_found count, no result event).

func NewTransientAwareExecutorTx added in v0.37.0

func NewTransientAwareExecutorTx(
	inner cdb.CommandObjectExecutorTx,
	park CommandPark,
	currentDateTime libtime.CurrentDateTimeGetter,
) cdb.CommandObjectExecutorTx

NewTransientAwareExecutorTx wraps one command executor so a command the vault could not decide is PARKED and re-driven instead of being committed past and lost.

The wrapper delegates everything except one case. A command that failed transiently is written to the park inside the handler's own transaction and is then reported as SKIPPED: cdb's own result-sender wrapper turns ErrCommandObjectSkipped into "no result, no error", the batch transaction commits, and ParkRedriver re-executes the command later. If the park write itself fails the command cannot be re-driven, so the error is returned instead and the initiator receives a Failure result — see the branch below. Every other outcome reaches the library's wrapper unchanged, so a success, a permanent failure and a deliberate skip behave exactly as they did before.

Why a park rather than a propagated error, which is what cqrs documents (docs/command-consumer.md:144: a transient failure "should return a normal error so the framework retries"): inside this chain a propagated error cannot work. cdb's result-sender wrapper converts ANY handler error into a published Failure result and returns nil (cqrs/cdb/cdb_command-object-executor-tx-result-sender.go:59), which is exactly the loss this change exists to fix — the batch commits and the offset advances past the command (kafka/kafka_consumer-offset.go:489-494), as it did for three release tasks on 2026-11-24. Letting the error past that wrapper means composing the chain by hand, and then the error rolls back the WHOLE batch: with COMMAND_BATCH_SIZE at 100 and RetryConsumer re-entering every 5 s, one flapping command replays up to 99 already-executed commands for the length of the outage — duplicate result messages and duplicate vault writes, including the delta-applying increment. Parking commits the batch and retries only the command that failed.

The park is committed by the same transaction as the handler work, but the offset is written immediately AFTER that transaction commits (kafka_offset_store.go). A crash in that gap leaves the command parked AND the message re-readable, so it is executed twice at worst; a duplicate create is answered with ErrTaskAlreadyExists rather than a second file, and the redriver clears that case as decided.

Only operations that are safe to repeat may be wrapped with this: a create is (an identifier that already exists is answered with ErrTaskAlreadyExists rather than a second file), a delta-applying increment is not.

func NewUpdateFrontmatterExecutor

func NewUpdateFrontmatterExecutor(
	client vaultapi.Client,
	vaultName string,
	currentDateTime libtime.CurrentDateTimeGetter,
	m metrics.Metrics,
	humans result.HumanAssignees,
	verifier WriteVerifier,
) cdb.CommandObjectExecutorTx

NewUpdateFrontmatterExecutor creates a cdb.CommandObjectExecutorTx that reads the task through the typed vault API by identifier, PATCHes only the frontmatter fields the command names (plus the doctrines), and PUTs the body when the command carries a body section or the trigger cap escalates. All other frontmatter keys are left untouched — the field level PATCH is what guarantees that, so no whole-file merge happens and none of the task's frontmatter is rewritten.

It is explicitly NOT atomic: PATCH and PUT are two requests and the typed surface has no combined primitive, so a failure between them leaves the body updated and the frontmatter stale. See applyUpdate for the window and why the retry is safe.

⚠️ This executor is the ONLY write a capped task receives. A task at the trigger cap is refused by the executor's checkTriggerBudget, so it never spawns, never produces a WriteResult, and never gets an IncrementFrontmatterCommand — the two sites the trigger-cap fix originally guarded. What it does get is this executor's once-a-minute restore-assignee write from the reconcile loop. Without the cap check here the escalation is unreachable for exactly the population it exists for (observed live on dev 2026-10-28, task 3a6501ec: the spawn charge reached trigger_count 3 through an update-frontmatter command and escalated nothing).

vaultName is the controller's VAULT_NAME; a command whose non-empty TargetVault differs is cross-vault traffic and is skipped before the task lookup (no write, no counter, no result event).

Types

type CommandPark added in v0.36.0

type CommandPark interface {
	// Park writes the command inside the caller's transaction, so the park commits
	// with the handler work that failed. Re-parking the same requestID replaces the
	// entry and refreshes ParkedAt.
	Park(
		ctx context.Context,
		tx libkv.Tx,
		command base.Command,
		parkedAt libtime.DateTime,
		taskIdentifier string,
	) error
	// List returns every parked command. Order is the bucket's key order, not park
	// time; a caller reads each entry's own ParkedAt.
	//
	// It opens its own read transaction, so it must not be called while a write
	// transaction on the same database is open — bbolt allows one writer, and a
	// nested transaction on the same DB can block until it times out.
	List(ctx context.Context) ([]ParkedCommand, error)
	// Delete removes one parked command, by key. It opens its own write
	// transaction, with the same restriction as List.
	Delete(ctx context.Context, key string) error
}

CommandPark stores commands whose execution failed transiently, so they can be re-driven instead of lost.

It lives in the same BoltDB as the consumer offsets. That does not make the park and the offset one write — the consumer marks the offset in a separate transaction immediately after the handler's — so a crash in the gap leaves the command parked AND the message re-readable. The command is then executed twice at worst, which is why only repeat-safe operations are parked.

⚠️ The database directory (DATA_DIR) must therefore be persistent: a park that dies with the pod is a command lost exactly as it was before this type existed.

func NewCommandPark added in v0.36.0

func NewCommandPark(db libkv.DB) CommandPark

NewCommandPark returns a CommandPark backed by db.

type ExpiredCommandObserver added in v0.19.0

type ExpiredCommandObserver interface {
	ObserveExpired(ctx context.Context, command base.Command, msg *sarama.ConsumerMessage)
}

ExpiredCommandObserver is told about every command the expiry predicate drops.

It exists because a dropped command is otherwise invisible: the predicate reports a bool, so nothing downstream can name what was lost. An observer turns the drop into a record carrying the command's own identifiers, which is what makes "a published create never reached the controller" answerable from the controller's own logs and metrics.

func NewLoggingExpiredCommandObserver added in v0.19.0

func NewLoggingExpiredCommandObserver(m metrics.Metrics) ExpiredCommandObserver

NewLoggingExpiredCommandObserver returns an ExpiredCommandObserver that logs and counts drops.

type LoggingExpiredCommandObserver added in v0.19.0

type LoggingExpiredCommandObserver struct {
	// contains filtered or unexported fields
}

LoggingExpiredCommandObserver logs every dropped command unconditionally and counts it.

The log is unconditional rather than V(n)-gated: a dropped command is the event this whole change exists to expose, and a gated line is exactly what made the drop unobservable before — the library logged it at Warning only when its sampler fired, and never named the command.

It deliberately writes no result object. An expired command is usually a create-task whose task file does not exist yet, so a result write would land as not_found noise on the ResultsWrittenTotal counter that AgentControllerResultNotFound alerts on. The log line and the counter are the record; making the command loud is this change's scope, not re-routing it.

func (*LoggingExpiredCommandObserver) ObserveExpired added in v0.19.0

func (o *LoggingExpiredCommandObserver) ObserveExpired(
	_ context.Context,
	command base.Command,
	msg *sarama.ConsumerMessage,
)

ObserveExpired logs the dropped command and increments CommandExpiredTotal for its operation.

type ParkRedriver added in v0.37.0

type ParkRedriver interface {
	// Run blocks until ctx is cancelled, sweeping once per interval.
	Run(ctx context.Context) error
	// RedriveOnce performs a single sweep. Exposed so tests do not manage tickers.
	RedriveOnce(ctx context.Context) error
}

ParkRedriver re-executes commands parked by NewTransientAwareExecutorTx and removes them once they are decided.

A parked command is re-driven at most every interval and only after the park is redriveDelay old, so a vault-api outage produces one attempt per interval rather than a retry storm. A command still undecided when the park is expireDuration old is dropped with an unconditional Error line and a CommandExpiredTotal increment — the same visible terminus the expiry filter gives an unprocessed message, so a command the controller could not execute is never lost silently.

func NewParkRedriver added in v0.37.0

func NewParkRedriver(
	park CommandPark,
	executor cdb.CommandObjectExecutorTx,
	schemaID cdb.SchemaID,
	resultObjectSender cdb.ResultObjectSender,
	expireDuration time.Duration,
	redriveDelay time.Duration,
	interval time.Duration,
	currentDateTime libtime.CurrentDateTimeGetter,
	m metrics.Metrics,
) ParkRedriver

NewParkRedriver builds the re-drive loop for one executor. Only operations whose execution is safe to repeat are parked by the executor wrapper, so this loop does not need to know which operation it is driving.

type ParkedCommand added in v0.36.0

type ParkedCommand struct {
	// Key is the bucket key, which is the command's requestID.
	Key string `json:"key"`
	// Command is the command as it was received, so a re-drive executes the same
	// request. It round-trips through JSON, so a numeric Data value comes back as
	// a float64 — adequate for the identifying fields, which are strings.
	Command base.Command `json:"command"`
	// ParkedAt is when the command was parked. A re-park of the same requestID
	// replaces it, so this is the most recent park, not the first. The re-drive
	// delay is measured from it; the drop window is measured from the command's own
	// RequestTime, so a re-park cannot extend a command's life.
	ParkedAt libtime.DateTime `json:"parkedAt"`
	// TaskIdentifier is the task the command addresses, kept beside the payload
	// so a drop can name it without decoding the command again.
	TaskIdentifier string `json:"taskIdentifier,omitempty"`
}

ParkedCommand is one command parked because the vault-api could not answer.

It holds the command itself rather than a reference to a Kafka message: the command topic's retention is shorter than an outage can be, and the offset is committed as soon as the command is parked (that commit is what stops a transient failure from replaying the whole batch), so the message is not guaranteed to be re-readable.

type PlanningRetryGate

type PlanningRetryGate interface {
	Handle(ctx context.Context, req lib.Task) (handled bool, err error)
}

PlanningRetryGate decides whether a failed pr-review planning result should be retried controller-side. Handle inspects the incoming result and the on-disk task state and, when the retry gate matches, performs the retry write (counter bump + ## Progress append + phase reset + fresh task_identifier) and returns handled=true. When the gate does not match (non-pr-review, non-planning, success/skipped, no failure marker, or counter already at cap in this prompt), it returns handled=false and the caller falls through to the default WriteResult path.

func NewPlanningRetryGate

func NewPlanningRetryGate(
	client vaultapi.Client,
	taskDir string,
	vaultName string,
	currentDateTime libtime.CurrentDateTimeGetter,
	prCommenter prcomment.PRCommenter,
	m metrics.Metrics,
	humans result.HumanAssignees,
) PlanningRetryGate

NewPlanningRetryGate constructs the gate. vaultName is the controller's VAULT_NAME, used to heal legacy task files that lack a target_vault stamp. taskDir is only used to render the human-facing PR comment, which names the task by a path-shaped string; the write itself addresses the task by identifier.

type ReadbackExpectation added in v0.33.0

type ReadbackExpectation struct {
	// TaskIdentifier is the record the command addressed.
	TaskIdentifier string
	// Operation is the command operation, used as the metric label.
	Operation string
	// BeforeHash is the recordHash fingerprint of the WHOLE record (frontmatter
	// and body) as it stood before the write. Empty means the record did not
	// exist (or was terminal) before the write, so ANY readable record counts as
	// landed.
	BeforeHash string
	// Deadline is when the expectation is evaluated. Nothing is dropped earlier:
	// a record that lands before the deadline simply passes when it is read.
	Deadline time.Time
}

ReadbackExpectation is one write awaiting verification: the record it addressed, the operation that reported success, and the content as it stood BEFORE the write.

BeforeHash is the point of the type. The question the readback asks is not "does the record hold what I wrote" — a later write may legitimately have replaced it — but "did the record MOVE at all". A fingerprint of the pre-write record answers that question, and it is what makes the check robust to supersede: the healthcheck probe's whole lifecycle (reopen → in_progress → done) can complete inside one commit window, so the intermediate state this command wrote is often never committed, while the record plainly moved.

type WriteVerifier added in v0.33.0

type WriteVerifier interface {
	// Expect records that a write reported success and must be verified.
	Expect(ctx context.Context, expectation ReadbackExpectation)
	// Run verifies due expectations until ctx is cancelled.
	Run(ctx context.Context) error
}

WriteVerifier re-reads a record after a command has reported success and reports a mismatch when the record did not move.

It exists because a command's success result is emitted when the write is ACCEPTED, not when it lands. git-rest buffers the write and commits on a cadence, so a consumer that trusts the result is, for up to one commit window, reading a write that is not yet in the store. The verification cannot run inline: the commit trails the acknowledgement by up to 30 s, so a synchronous readback would either fail every ordinary write or block the command consumer for a commit window. It is therefore deferred, and the counter is what makes the gap observable.

func NewWriteVerifier added in v0.33.0

func NewWriteVerifier(
	client vaultapi.Client,
	m metrics.Metrics,
	clock libtime.CurrentDateTimeGetter,
	interval time.Duration,
	deadline time.Duration,
	ref string,
) WriteVerifier

NewWriteVerifier returns a WriteVerifier backed by the typed vault API.

A nil clock uses the wall clock; a zero interval or deadline takes the package default, and so does an empty ref. All four are injectable so a test can drive the loop without sleeping.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL