Help us shape the future of Go! Take the 2026 Go Developer Survey

durable

package
v1.9.3 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package durable defines the transactional persistence contract for execution history and tasks. The coordinator validates workflow commands before using it.

Index

Constants

View Source
const (
	BuildAccepting                                 = "accepting"
	BuildRetiring                                  = "retiring"
	BuildRetired                                   = "retired"
	OperationRegisterBuild      LifecycleOperation = "build.register"
	OperationBeginRetirement    LifecycleOperation = "build.retirement.begin"
	OperationFinalizeRetirement LifecycleOperation = "build.retirement.finalize"
	OperationAbortRetirement    LifecycleOperation = "build.retirement.abort"
)
View Source
const (
	ChildDeliveryResult                ChildDeliveryKind = "result"
	ChildDeliveryClose                 ChildDeliveryKind = "close"
	ChildDeliveryCancel                ChildDeliveryKind = "cancel"
	ChildDeliveryCancelAck             ChildDeliveryKind = "cancel_ack"
	ChildDeliveryApplied                                 = "applied"
	ChildDeliveryIgnoredClosed                           = "ignored_closed"
	ChildDeliveryIgnoredExpired                          = "ignored_expired"
	EventChildCompleted                                  = "workflow.child_completed"
	EventChildCancellationAcknowledged                   = "workflow.child_cancellation_acknowledged"
	EventWorkflowTerminated                              = "workflow.terminated"
)
View Source
const (
	EventWorkflowContinued = "workflow.continued_as_new"
	EventRunStarted        = "workflow.run_started"
	EventSignalCarried     = "workflow.signal_carried"
	EventSignalConsumed    = "workflow.signal_consumed"
)
View Source
const (
	QueryRetentionSchemaVersion                      = 1
	QueryRuntimeActive                               = "active"
	QueryRuntimeRemoving                             = "removing"
	QueryRuntimeRemoved                              = "removed"
	OperationRegisterQueryRuntime LifecycleOperation = "query_runtime.register"
	OperationVerifyQueryRuntime   LifecycleOperation = "query_runtime.verify"
	OperationBeginQueryRemoval    LifecycleOperation = "query_runtime.remove"
	OperationFinishQueryRemoval   LifecycleOperation = "query_runtime.finish"
	OperationAbortQueryRemoval    LifecycleOperation = "query_runtime.abort"
)
View Source
const (
	EventWorkflowRetrySuppressed = "workflow.retry_suppressed"
	EventWorkflowRetryScheduled  = "workflow.retry_scheduled"
	FailureWorkflowRunTimeout    = "workflow_run_timeout"
)
View Source
const AuditWriterProtocol = 1
View Source
const DeliveryPublisherProtocol = 1

DeliveryPublisherProtocol is independent of the audit writer protocol. Version 1 understands permanent conflict disposition and verifies sink receipts.

View Source
const DeliverySchemaVersion = 1
View Source
const EventCancellationRequested = "workflow.cancellation_requested"

EventCancellationRequested records accepted workflow cancellation independently of task fencing, cleanup and terminal state.

View Source
const EventSignalReceived = "workflow.signal_received"

EventSignalReceived records an accepted signal independently of consumption.

View Source
const EventWorkflowTimedOut = "workflow.timed_out"
View Source
const MaxDeliveryBatch = 100
View Source
const MaxDeliveryIdentifierBytes = 256

MaxDeliveryIdentifierBytes bounds catalog ownership and delivery identifiers.

View Source
const MaxIdentifierBytes = 512

MaxIdentifierBytes is the persisted execution and task identifier byte limit.

View Source
const MaxReadCursorBytes = (8*maxReadPositionJSON + 5) / 6

MaxReadCursorBytes bounds the encoded execution and task position.

View Source
const MaxReadPage = 100
View Source
const QueryRemovalCommitReceiptLimit = 17408

QueryRemovalCommitReceiptLimit includes the request and authenticated receipt wrapper.

View Source
const QueryRemovalGuardSchemaVersion = 1

QueryRemovalGuardSchemaVersion identifies the complete native guard capability.

View Source
const QueryRemovalMaterialLimit = 524288

QueryRemovalMaterialLimit bounds the complete persisted material, including evidence.

View Source
const RetirementSchemaVersion = 1
View Source
const RetirementWriterProtocol = 1
View Source
const WorkerDrainSchemaVersion = 1
View Source
const WorkflowTaskDeferralPolicyVersion = 1

Variables

View Source
var (
	ErrInvalid = errors.New("durable: invalid request")
	// ErrBuildMismatch retains ErrInvalid compatibility for trusted store callers.
	ErrBuildMismatch     = fmt.Errorf("%w: execution build mismatch", ErrInvalid)
	ErrNotFound          = errors.New("durable: execution not found")
	ErrExists            = errors.New("durable: identity already exists")
	ErrRequestConflict   = errors.New("durable: request ID reused with different content")
	ErrRevisionConflict  = errors.New("durable: execution revision changed")
	ErrLeaseLost         = errors.New("durable: task lease lost")
	ErrTaskConflict      = errors.New("durable: task observation changed")
	ErrExecutionDeadline = errors.New("durable: execution deadline expired")
	ErrTaskDeadline      = errors.New("durable: task deadline expired")
	ErrClosed            = errors.New("durable: execution closed")
)

Store errors let the coordinator distinguish conflicts from transport failures.

View Source
var ErrAdmissionChanged = errors.New("durable: target admission changed")
View Source
var ErrAmbiguousRun = errors.New("durable: latest run is unknown for migrated history")

ErrAmbiguousRun means a migrated workflow has several closed runs but no saved latest identity. Query an explicit run until a new start establishes latest.

View Source
var ErrBuildAdmission = errors.New("durable: build admission refused")
View Source
var ErrLifecycleBusy = errors.New("durable: namespace coordination busy")
View Source
var ErrQueryFence = errors.New("durable: query removal fence changed or expired")
View Source
var ErrQueryRemovalGuard = errors.New("durable: query removal guard refused")

ErrQueryRemovalGuard means a protected association or current proof cannot change.

View Source
var ErrQueryRetention = errors.New("durable: verified query retention unavailable")
View Source
var ErrRetirementBlocked = errors.New("durable: build retirement blocked")
View Source
var ErrWriterCompatibility = errors.New("durable: incompatible retirement writer")

Functions

func AdmissionEpoch

func AdmissionEpoch(build BuildAdmission, source *Execution, kind, command string) (int64, error)

AdmissionEpoch derives eligibility from a persisted immediate predecessor or parent. Callers cannot acquire inherited eligibility by choosing a request ID.

func Advance

func Advance(current Execution, task Task, r CommitRequest, now time.Time) (Execution, Receipt, error)

Advance validates the revision and lease, then computes a transition's state. The backend must hold its mutation lock and persist the result atomically with events, tasks and the receipt. It separately checks that the task is unfinished.

func CheckExecutionDeadline

func CheckExecutionDeadline(e Execution, now time.Time) error

CheckExecutionDeadline rejects progress at or after the persisted deadline. Callers check lifecycle and exact receipts separately before enforcing expiry.

func CheckExecutionTimeoutLease

func CheckExecutionTimeoutLease(task ExecutionTimeoutTask, r ExecutionTimeoutRequest, now time.Time) error

CheckExecutionTimeoutLease rejects expired or superseded timeout ownership.

func CheckLease

func CheckLease(task Task, token TaskToken, now time.Time) error

CheckLease verifies grant identity and expiry using the store's current time. Advance and ApplyHeartbeat additionally verify an asynchronous grant's secret.

func CheckQueryRemoval

func CheckQueryRemoval(candidate QueryRuntimeBinding, f QueryRemovalFence, build BuildAdmission, retained int64, bindings []QueryRuntimeBinding, now time.Time) error

CheckQueryRemoval checks current permission, not just an accepted reservation.

func CheckReceiptIntent

func CheckReceiptIntent(stored, requested string) error

CheckReceiptIntent rejects mismatched proofs and older receipts without intent. Callers validate the requested digest before loading the stored receipt.

func CheckTaskCondition

func CheckTaskCondition(task Task, condition TaskCondition, now time.Time) error

CheckTaskCondition evaluates a locked task against a caller's observation.

func DeliveryIdentifier

func DeliveryIdentifier(v string) bool

DeliveryIdentifier bounds catalog and metadata identifiers and rejects control characters. Hosts must supply identifiers, never claims, credentials or errors.

func Fingerprint

func Fingerprint(operation string, request any) (string, error)

Fingerprint binds a receipt to the exact typed request, including its operation.

func HashAsyncSecret

func HashAsyncSecret(secret string) (string, error)

HashAsyncSecret hashes a canonical hexadecimal encoding of a 32-byte secret. Generate the secret with a cryptographic random source before handing it off.

func LifecycleAction

func LifecycleAction(operation LifecycleOperation) string

LifecycleAction is the closed authorization and Chronicle action mapping.

func LifecycleSourceID

func LifecycleSourceID(namespace string, operation LifecycleOperation, requestID string) string

LifecycleSourceID keeps namespace commands outside execution receipt domains.

func NewQueryRejection

func NewQueryRejection(cause error, d QueryRejectionDiagnostic) error

NewQueryRejection preserves the original error class and bounds all metadata.

func PrepareExecutionTimeout

func PrepareExecutionTimeout(current Execution, now time.Time) (Execution, Event, Receipt, error)

PrepareExecutionTimeout computes terminal history after the store checks its grant.

func PrepareWorkflowTaskDeferral

func PrepareWorkflowTaskDeferral(e Execution, task Task, r WorkflowTaskDeferralRequest, target BuildAdmission, previous WorkflowTaskDeferral, now time.Time) (Task, WorkflowTaskDeferral, error)

PrepareWorkflowTaskDeferral uses locked store facts and never changes history.

func QueryRemovalCompatibleBuild

func QueryRemovalCompatibleBuild(prior, next BuildAdmission) bool

QueryRemovalCompatibleBuild permits only unchanged catalogs or final retirement.

func QueryRemovalSize

func QueryRemovalSize(v any, limit int) error

QueryRemovalSize enforces actual compact JSON bytes, including HTML escaping.

func QueryRemovalToken

func QueryRemovalToken(s string) bool

QueryRemovalToken preserves a canonical ASCII representation for new opaque IDs.

func ReceiptSourceID

func ReceiptSourceID(parts ...string) string

ReceiptSourceID is unambiguous even when a child delivery ID contains a colon.

func ResolveExecutionDeadlines

func ResolveExecutionDeadlines(r StartRequest, now time.Time) (run, execution time.Time, resultErr error)

ResolveExecutionDeadlines resolves optional timeouts from the store's creation clock.

func SameWorkflowRetryPolicy

func SameWorkflowRetryPolicy(a, b *WorkflowRetryPolicy) bool

SameWorkflowRetryPolicy compares already normalized policy snapshots.

func TaskTimeAfter

func TaskTimeAfter(base time.Time, delay time.Duration) (time.Time, error)

TaskTimeAfter rounds a relative deadline up, never before the requested delay.

func Timestamp

func Timestamp(t time.Time) time.Time

Timestamp normalizes persisted time to PostgreSQL's microsecond precision.

func ValidateBuildID

func ValidateBuildID(build string) error

ValidateBuildID retains the execution contract's existing identifier limits.

func ValidateBuildRead

func ValidateBuildRead(namespace, build string) error

ValidateBuildRead applies persisted identifier limits, not catalog limits.

func ValidateChildCancellationSource

func ValidateChildCancellationSource(task Task, cancellations []ChildCancellationSpec) error

ValidateChildCancellationSource requires an ordinary workflow decision.

func ValidateChildSource

func ValidateChildSource(task Task, children []ChildStartSpec) error

ValidateChildSource binds child routing to an ordinary parent workflow grant.

func ValidateDeliveryRenewal

func ValidateDeliveryRenewal(t DeliveryToken, d time.Duration) error

ValidateDeliveryRenewal bounds lease extensions consistently across backends.

func ValidateLease

func ValidateLease(ttl time.Duration) error

ValidateLease bounds ownership grants and rejects sub-microsecond durations.

func ValidateQueryRemovalFacts

func ValidateQueryRemovalFacts(r QueryRemovalRevalidationRequest, begin LifecycleReceipt, candidate QueryRuntimeBinding, build BuildAdmission, survivor QueryRuntimeBinding, retained int64, now time.Time) error

ValidateQueryRemovalFacts checks exact native rows at the post-lock clock.

func ValidateQueryRemovalFinalization

func ValidateQueryRemovalFinalization(q LifecycleReceiptLookup, receipt LifecycleReceipt, build BuildAdmission) error

ValidateQueryRemovalFinalization checks the exact native finalization association.

func ValidateRunMetadata

func ValidateRunMetadata(e Execution) error

ValidateRunMetadata checks local lineage and deadline consistency. The store separately verifies predecessor/successor rows and atomic relationship changes.

func ValidateTaskID

func ValidateTaskID(id string) error

ValidateTaskID checks a task identity before any store access.

func ValidateTaskSpec

func ValidateTaskSpec(task TaskSpec) error

ValidateTaskSpec rejects ambiguous availability and invalid relative durations.

func WithAuditMetadata

func WithAuditMetadata(ctx context.Context, m AuditMetadata) context.Context

func WorkflowRetryDelay

func WorkflowRetryDelay(policy *WorkflowRetryPolicy, attempt int64, failureType string, nonRetryable bool) (time.Duration, error)

WorkflowRetryDelay returns zero when this failure is final. The store resolves the returned duration against its clock and persists successor availability.

Types

type AbortQueryRemovalRequest

type AbortQueryRemovalRequest struct {
	VerifyQueryRuntimeRequest
	Fence      QueryRemovalFence
	Settlement QueryRemovalSettlement
}

func (AbortQueryRemovalRequest) Validate

func (r AbortQueryRemovalRequest) Validate() error

type AuditMetadata

type AuditMetadata struct {
	ActorKind     string
	ActorID       string
	RequestID     string
	CorrelationID string
	DecisionID    string
	PolicyVersion string
	ReasonCode    string
}

AuditMetadata contains trusted, verified facts only. Scope is always supplied by the persisted namespace catalog. The carrier is not an authentication API.

func AuditMetadataFromContext

func AuditMetadataFromContext(ctx context.Context) AuditMetadata

func (AuditMetadata) Validate

func (m AuditMetadata) Validate() error

type BeginQueryRemovalRequest

type BeginQueryRemovalRequest struct {
	QueryRuntimeTarget
	RequestID       string
	ExpectedVersion int64
}

func (BeginQueryRemovalRequest) Validate

func (r BeginQueryRemovalRequest) Validate() error

type BuildAdmission

type BuildAdmission struct {
	QueryIdentity BuildQueryIdentity
	BuildTarget
	State       string
	Epoch       int64
	Version     int64
	CutoffEpoch int64
	ChangedAt   time.Time
}

BuildAdmission records admission and optional trusted query identity. Historical enrollment leaves QueryIdentity empty until explicit evidence arrives.

func RegisterBuildIdentity

func RegisterBuildIdentity(current BuildAdmission, exists bool, r RegisterBuildRequest, now time.Time) (BuildAdmission, error)

RegisterBuildIdentity fills an absent historical identity once, without changing admission state or fabricating artifact facts during enrollment.

func TransitionBuild

func TransitionBuild(current BuildAdmission, r BuildRetirementRequest, operation LifecycleOperation, blockers BuildBlockers, now time.Time) (BuildAdmission, error)

type BuildAdmissionError

type BuildAdmissionError struct {
	BuildID         string
	State           string
	RetirementEpoch int64
	ReferenceKind   string
	CommandID       string
}

func (*BuildAdmissionError) Error

func (e *BuildAdmissionError) Error() string

func (*BuildAdmissionError) Unwrap

func (e *BuildAdmissionError) Unwrap() error

type BuildBlockers

type BuildBlockers struct {
	OpenExecutions         int64
	PendingTasks           int64
	AsyncCallbacks         int64
	DelayedRuns            int64
	PendingChildDeliveries int64
	ChildObligations       int64
}

func (BuildBlockers) Empty

func (b BuildBlockers) Empty() bool

type BuildFacts

type BuildFacts struct{ Executions, Running, PendingTasks int64 }

type BuildLifecycleFacts

type BuildLifecycleFacts struct {
	QueryRetention     QueryRetentionFacts
	Admission          BuildAdmission
	Blockers           BuildBlockers
	ObservationVersion ObservationVersion
}

type BuildQueryIdentity

type BuildQueryIdentity struct {
	ArtifactDigest           string
	ConfigurationDigest      string
	ConfigurationVersion     string
	EnrollmentEvidenceDigest string
	ProbePolicyID            string
	ProbePolicyVersion       int64
	VerifierID               string
	MaximumProofValidity     time.Duration
}

BuildQueryIdentity is supplied by trusted artifact enrollment, never inferred from a build label. A zero value means historical identity remains unknown.

func (BuildQueryIdentity) Validate

func (i BuildQueryIdentity) Validate() error

type BuildRetirementRequest

type BuildRetirementRequest struct {
	BuildTarget
	RequestID       string
	ExpectedVersion int64
	ExpectedEpoch   int64
}

func (BuildRetirementRequest) Validate

func (r BuildRetirementRequest) Validate() error

type BuildTarget

type BuildTarget struct {
	NamespaceTarget
	BuildID string
}

func (BuildTarget) Validate

func (t BuildTarget) Validate() error

type CancelExecutionReceipt

type CancelExecutionReceipt struct {
	Key
	Receipt
}

CancelExecutionReceipt confirms durable acceptance, not completed cancellation.

type CancelExecutionRequest

type CancelExecutionRequest struct {
	Key
	RequestID string `json:"request_id"`
	BuildID   string `json:"build_id"`
	Reason    string `json:"reason,omitempty"`
}

CancelExecutionRequest targets one run, or the current open run with empty RunID. Retry the complete original request to recover its original target. Request IDs are scoped by namespace/workflow within the cancellation API.

func (CancelExecutionRequest) Validate

func (r CancelExecutionRequest) Validate() error

Validate requires namespace/build and permits selecting the current open run.

type CarriedSignal

type CarriedSignal struct {
	Version  int       `json:"version"`
	Source   Key       `json:"source"`
	Sequence int64     `json:"sequence"`
	Time     time.Time `json:"time"`
	Signal   Signal    `json:"signal"`
}

CarriedSignal retains the first acceptance coordinates through every handoff.

func (CarriedSignal) Validate

func (c CarriedSignal) Validate(target Key) error

type ChildCancellationSpec

type ChildCancellationSpec struct {
	CommandID string `json:"command_id"`
	TargetID  string `json:"target_id"`
}

type ChildDelivery

type ChildDelivery struct {
	Source        Key               `json:"source"`
	ID            string            `json:"id"`
	Kind          ChildDeliveryKind `json:"kind"`
	Target        Key               `json:"target"`
	TargetBuildID string            `json:"target_build_id"`
	TargetQueue   string            `json:"target_queue"`
	Message       ChildMessage      `json:"message"`
	CreatedAt     time.Time         `json:"created_at"`
	AvailableAt   time.Time         `json:"available_at"`
	Owner         string            `json:"owner"`
	Epoch         int64             `json:"epoch"`
	Attempt       int64             `json:"attempt"`
	LeaseUntil    time.Time         `json:"lease_until"`
	Done          bool              `json:"done"`
	Disposition   string            `json:"disposition,omitempty"`
}

ChildDelivery is retained independently of its source execution's lifecycle. Claims route by the target build and may be reclaimed after lease expiry.

func PrepareChildDeliveries

func PrepareChildDeliveries(b ChildDeliveryBatch, now time.Time) ([]ChildDelivery, error)

PrepareChildDeliveries computes messages without mutating either execution.

func (ChildDelivery) CancellationAcknowledgment

func (d ChildDelivery) CancellationAcknowledgment(build, queue, disposition string, now time.Time) (ChildDelivery, error)

CancellationAcknowledgment returns a separate child-to-parent delivery.

func (ChildDelivery) CancellationRequest

func (d ChildDelivery) CancellationRequest() CancelExecutionRequest

CancellationRequest binds generated cancellation to the existing receipt scope.

func (ChildDelivery) CheckLease

func (d ChildDelivery) CheckLease(r ChildDeliveryRequest, now time.Time) error

CheckLease rejects stale delivery grants using the store's clock.

func (ChildDelivery) Clone

func (d ChildDelivery) Clone() ChildDelivery

Clone copies message bytes at the persistence boundary.

func (ChildDelivery) Validate

func (d ChildDelivery) Validate() error

Validate checks immutable routing and message shape before insertion or use.

type ChildDeliveryBatch

type ChildDeliveryBatch struct {
	Next          Execution
	Request       CommitRequest
	Children      []ChildExecution
	Parent        *ChildExecution
	ParentBuildID string
}

ChildDeliveryBatch describes the relationships visible before a decision. New children participate in explicit cancellation only, not the bulk fence.

type ChildDeliveryClaimRequest

type ChildDeliveryClaimRequest struct {
	Namespace, BuildID, Owner string
	LeaseDuration             time.Duration
}

func (ChildDeliveryClaimRequest) Validate

func (r ChildDeliveryClaimRequest) Validate() error

type ChildDeliveryKind

type ChildDeliveryKind string

ChildDeliveryKind identifies a lifecycle message between linked executions.

type ChildDeliveryReceipt

type ChildDeliveryReceipt struct {
	Target Key `json:"target"`
	Receipt
	Disposition string `json:"disposition"`
}

ChildDeliveryReceipt remains valid after either execution closes.

type ChildDeliveryRequest

type ChildDeliveryRequest struct {
	Source     Key    `json:"source"`
	DeliveryID string `json:"delivery_id"`
	RequestID  string `json:"request_id"`
	Owner      string `json:"owner"`
	Epoch      int64  `json:"epoch"`
}

func (ChildDeliveryRequest) Validate

func (r ChildDeliveryRequest) Validate() error

type ChildExecution

type ChildExecution struct {
	Parent     Key `json:"parent"`
	CurrentKey Key `json:"current_key"`
	ChildStartSpec
	State     State     `json:"state"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

ChildExecution combines the saved relationship with the child's current state.

type ChildMessage

type ChildMessage struct {
	Version        int               `json:"version"`
	CommandID      string            `json:"command_id"`
	CancellationID string            `json:"cancellation_id,omitempty"`
	Parent         Key               `json:"parent"`
	Child          Key               `json:"child"`
	Policy         ParentClosePolicy `json:"policy"`
	State          State             `json:"state,omitempty"`
	Output         []byte            `json:"output,omitempty"`
	CloseEvent     EventInput        `json:"close_event"`
	Disposition    string            `json:"disposition,omitempty"`
	FinalRun       *RunMetadata      `json:"final_run,omitempty"`
}

ChildMessage preserves the original relationship and terminal outcome. An acknowledgment's Disposition describes acceptance, never child completion.

type ChildStartError

type ChildStartError struct {
	CommandID string
	Err       error
}

ChildStartError identifies the child that prevented an atomic parent decision. Coordinators may record a deterministic start failure for a definitive conflict.

func (*ChildStartError) Error

func (e *ChildStartError) Error() string

func (*ChildStartError) Unwrap

func (e *ChildStartError) Unwrap() error

type ChildStartSpec

type ChildStartSpec struct {
	CommandID         string            `json:"command_id"`
	Start             StartRequest      `json:"start"`
	ParentQueue       string            `json:"parent_queue"`
	ParentClosePolicy ParentClosePolicy `json:"parent_close_policy"`
}

ChildStartSpec creates a new child with an immutable parent relationship. ParentQueue must match the source workflow task's queue.

func (ChildStartSpec) Validate

func (c ChildStartSpec) Validate(parent Key) error

Validate rejects cross-namespace children, invalid routing and oversized input.

type ChildStarted

type ChildStarted struct {
	Version           int               `json:"version"`
	CommandID         string            `json:"command_id"`
	Child             Key               `json:"child"`
	WorkflowType      string            `json:"workflow_type"`
	BuildID           string            `json:"build_id"`
	Queue             string            `json:"queue"`
	ParentClosePolicy ParentClosePolicy `json:"parent_close_policy"`
}

ChildStarted is appended to the parent history atomically with child creation.

type ClaimRequest

type ClaimRequest struct {
	// BuildID restricts claims to a pinned build. Empty permits any build.
	BuildID       string
	Namespace     string
	Queue         string
	Kind          TaskKind
	Owner         string
	LeaseDuration time.Duration
}

ClaimRequest polls a single namespace, task kind and queue.

func (ClaimRequest) Validate

func (r ClaimRequest) Validate() error

Validate checks task routing and the requested lease duration.

type CommitRequest

type CommitRequest struct {
	Key
	RequestID        string                  `json:"request_id"`
	ExpectedRevision int64                   `json:"expected_revision"`
	Token            TaskToken               `json:"token"`
	Events           []EventInput            `json:"events"`
	Tasks            []TaskSpec              `json:"tasks,omitempty"`
	Children         []ChildStartSpec        `json:"children,omitempty"`
	CancelChildren   []ChildCancellationSpec `json:"cancel_children,omitempty"`
	Continuation     *ContinueSpec           `json:"continuation,omitempty"`
	State            State                   `json:"state,omitempty"`
	Output           []byte                  `json:"output,omitempty"`
	TaskUpdate       *TaskUpdate             `json:"task_update,omitempty"`
	Conditions       []TaskCondition         `json:"conditions,omitempty"`
	CancelTasks      []string                `json:"cancel_tasks,omitempty"`
	// CancelPendingTasks fences existing pending tasks before creating Tasks.
	// The source must complete; new cleanup work remains runnable.
	CancelPendingTasks bool `json:"cancel_pending_tasks,omitempty"`
	// AsyncSecret is required only for an asynchronous grant. Receipts store its
	// request fingerprint, never this secret. Do not log callback requests.
	AsyncSecret string `json:"async_secret,omitempty"`
	// IntentDigest binds the complete client request, independently of derived
	// revision/task observations. Only the trusted coordinator may construct it.
	// Keep it private; LookupReceipt uses it as a recovery proof.
	IntentDigest string `json:"intent_digest,omitempty"`
}

CommitRequest atomically advances an execution and updates its claimed task. A nil TaskUpdate finishes the task; Keep and Retry retain its identity. Empty State retains the current state. Closing a run cancels all pending work and cannot schedule more tasks. RequestID is unique across mutations of a run.

func (CommitRequest) Validate

func (r CommitRequest) Validate() error

Validate checks a transition before any writes occur.

type CompatibilityFacts

type CompatibilityFacts struct {
	// QueryRemovalGuardSchemaVersion describes native enforcement, not host trust readiness.
	QueryRemovalGuardSchemaVersion int `json:",omitempty"`
	WorkerDrainSchemaVersion       int `json:",omitempty"`
	// QueryRetentionSchemaVersion describes current store capability only. It is
	// not proof that a host artifact or controller is query-retention qualified.
	QueryRetentionSchemaVersion int `json:",omitempty"`
	NamespaceTarget
	Enrolled       bool
	SchemaVersion  int
	WriterProtocol int
	Version        int64
	EnrolledAt     time.Time
	ObservedAt     time.Time
}

type ContinuationBatch

type ContinuationBatch struct {
	RetrySuppressed bool
	Spec            ContinueSpec
	RetryEvent      *EventInput
	Execution       Execution
	History         []Event
	Terminal        EventInput
}

ContinuationBatch is staged completely before either run becomes visible.

func PrepareContinuation

func PrepareContinuation(current Execution, task Task, r CommitRequest, history []Event, now time.Time) (*ContinuationBatch, error)

PrepareContinuation builds a successor and carries accepted, unconsumed signals. The store owns the identity/run locks, uniqueness checks and atomic installation.

func PrepareTransitionSuccessor

func PrepareTransitionSuccessor(current Execution, task Task, r CommitRequest, history []Event, now time.Time) (*ContinuationBatch, error)

PrepareTransitionSuccessor stages continuation or an opt-in workflow retry. The caller has validated its ordinary grant, revision and execution deadline.

func PrepareWorkflowRetry

func PrepareWorkflowRetry(current Execution, state State, inputs []EventInput, history []Event, queue string, now time.Time) (*ContinuationBatch, error)

PrepareWorkflowRetry stages a successor from a saved policy and authoritative store time. Timeout processors call it without loading a workflow handler.

type ContinueSpec

type ContinueSpec struct {
	RunID        string        `json:"run_id"`
	WorkflowType string        `json:"workflow_type"`
	BuildID      string        `json:"build_id"`
	Queue        string        `json:"queue"`
	Input        []byte        `json:"input,omitempty"`
	RunTimeout   time.Duration `json:"run_timeout,omitempty"`
}

ContinueSpec contains resolved successor options. ExecutionDeadlineAt is inherited.

func (ContinueSpec) Validate

func (s ContinueSpec) Validate() error

type ContinuedRun

type ContinuedRun struct {
	Version int          `json:"version"`
	Next    ContinueSpec `json:"next"`
}

ContinuedRun is the source run's store-generated terminal event.

type DeferralReferenceKind

type DeferralReferenceKind string
const (
	DeferralChild        DeferralReferenceKind = "child"
	DeferralContinuation DeferralReferenceKind = "continuation"
)

type DeferralTargetState

type DeferralTargetState string
const (
	DeferralUnregistered DeferralTargetState = "unregistered"
	DeferralRetiring     DeferralTargetState = "retiring"
	DeferralRetired      DeferralTargetState = "retired"
)

type Delivery

type Delivery struct {
	ID             string
	Destination    Destination
	SchemaVersion  int
	InstallationID string
	Namespace      string
	AppID          string
	TenantID       string
	WorkflowID     string
	RunID          string
	SourceKind     string
	SourceID       string
	Sequence       int64
	OccurredAt     time.Time
	Action         string
	Outcome        string
	Target         string
	Metadata       AuditMetadata
	Fingerprint    string
}

Delivery contains no execution payload, progress, secret or arbitrary map.

func NewDelivery

func NewDelivery(n NamespaceRecord, destination Destination, s DeliverySource) (Delivery, error)

func (Delivery) Verify

func (d Delivery) Verify() error

type DeliveryClaim

type DeliveryClaim struct {
	DeliveryScope
	Owner         string
	Limit         int
	LeaseDuration time.Duration
}

func (DeliveryClaim) Validate

func (r DeliveryClaim) Validate() error

type DeliveryCompatibilityStore

type DeliveryCompatibilityStore interface {
	CheckDeliveryCompatibility(context.Context, int) error
}

DeliveryCompatibilityStore rejects unsupported publisher/schema combinations before a publisher starts. Database fences also reject pre-protocol artifacts.

type DeliveryRecord

type DeliveryRecord struct {
	Delivery      Delivery
	Owner         string
	Epoch         int64
	LeaseUntil    time.Time
	Attempts      int64
	NextAttemptAt time.Time
	AcceptedAt    time.Time
	DeliveredAt   time.Time
	Receipt       SinkReceipt
	ErrorCategory string
}

func (DeliveryRecord) Blocked

func (r DeliveryRecord) Blocked() bool

Blocked reports a confirmed sink content conflict. Repair requires a separate protected operation; automatic claims never clear this disposition.

func (DeliveryRecord) Token

func (r DeliveryRecord) Token() DeliveryToken

type DeliveryRetry

type DeliveryRetry struct {
	Token    DeliveryToken
	Delay    time.Duration
	Category string
}

func (DeliveryRetry) Validate

func (r DeliveryRetry) Validate() error

type DeliveryScope

type DeliveryScope struct {
	InstallationID string
	Destination    Destination
}

func (DeliveryScope) Validate

func (s DeliveryScope) Validate() error

type DeliverySource

type DeliverySource struct {
	Key        Key
	Kind       string
	ID         string
	Sequence   int64
	OccurredAt time.Time
	Action     string
	Outcome    string
	Target     string
	Metadata   AuditMetadata
}

DeliverySource is supplied by a store mutation, or by a captured security attempt. SourceKind separates event, receipt and security identity domains.

func EventDeliverySource

func EventDeliverySource(ctx context.Context, key Key, event Event) DeliverySource

func LifecycleDeliverySource

func LifecycleDeliverySource(ctx context.Context, receipt LifecycleReceipt) DeliverySource

func QueryRemovalDeliverySource

func QueryRemovalDeliverySource(ctx context.Context, namespace, kind, id string, at time.Time) DeliverySource

QueryRemovalDeliverySource binds one native command to its transactional audit intent.

type DeliveryStatus

type DeliveryStatus struct {
	Blocked          int64
	Pending          int64
	OldestAcceptedAt time.Time
	Records          []DeliveryRecord
}

type DeliveryStatusRequest

type DeliveryStatusRequest struct {
	DeliveryScope
	After string
	Limit int
}

func (DeliveryStatusRequest) Validate

func (r DeliveryStatusRequest) Validate() error

type DeliveryToken

type DeliveryToken struct {
	DeliveryScope
	ID    string
	Owner string
	Epoch int64
}

func (DeliveryToken) Validate

func (t DeliveryToken) Validate() error

type Destination

type Destination string
const (
	DestinationChronicle Destination = "chronicle"
	DestinationRelay     Destination = "relay"
)

type Event

type Event struct {
	EventInput
	Sequence int64     `json:"sequence"`
	Time     time.Time `json:"time"`
}

Event is an immutable history entry, ordered within one run.

type EventInput

type EventInput struct {
	Type    string `json:"type"`
	Payload []byte `json:"payload,omitempty"`
}

EventInput supplies an event's content. The store assigns sequence and time.

func AddWorkflowRetryEvent

func AddWorkflowRetryEvent(next *Execution, receipt *Receipt, inputs []EventInput, batch *ContinuationBatch) ([]EventInput, error)

AddWorkflowRetryEvent adjusts source coordinates and inserts the retry link immediately before its terminal event. Continuations use their existing append.

func ChildStartEvents

func ChildStartEvents(children []ChildStartSpec) ([]EventInput, error)

ChildStartEvents returns the store-generated events in request order.

type Execution

type Execution struct {
	Key
	WorkflowType        string    `json:"workflow_type"`
	BuildID             string    `json:"build_id"`
	AdmissionEpoch      int64     `json:"admission_epoch"`
	State               State     `json:"state"`
	Revision            int64     `json:"revision"`
	LastSequence        int64     `json:"last_sequence"`
	Input               []byte    `json:"input,omitempty"`
	Output              []byte    `json:"output,omitempty"`
	CreatedAt           time.Time `json:"created_at"`
	UpdatedAt           time.Time `json:"updated_at"`
	RunDeadlineAt       time.Time `json:"run_deadline_at,omitempty"`
	ExecutionDeadlineAt time.Time `json:"execution_deadline_at,omitempty"`
	// Each existing run is an independent root until an atomic handoff links it.
	FirstRunID     string               `json:"first_run_id"`
	PreviousRunID  string               `json:"previous_run_id,omitempty"`
	NextRunID      string               `json:"next_run_id,omitempty"`
	RunNumber      int64                `json:"run_number"`
	FirstStartedAt time.Time            `json:"first_started_at"`
	RunTimeout     time.Duration        `json:"run_timeout,omitempty"`
	RetryPolicy    *WorkflowRetryPolicy `json:"retry_policy,omitempty"`
	RetryAttempt   int64                `json:"retry_attempt"`
	RunAvailableAt time.Time            `json:"run_available_at"`
}

Execution is the current state projected alongside its ordered history.

func NewExecution

func NewExecution(r StartRequest, now time.Time) (Execution, error)

NewExecution constructs an independent root using the authoritative creation clock. Historical runs sharing a workflow ID are not implicitly one chain.

func (Execution) AvailableAt

func (e Execution) AvailableAt() time.Time

AvailableAt is the first permitted execution time, including retry backoff. Older snapshots without the field use their creation time.

func (Execution) Clone

func (e Execution) Clone() Execution

Clone isolates execution payloads and retry policy from stored state.

func (Execution) Deadline

func (e Execution) Deadline() (ExecutionTimeoutKind, time.Time)

Deadline returns the earliest limit; execution takes precedence on a tie.

func (Execution) WorkflowAttempt

func (e Execution) WorkflowAttempt() int64

WorkflowAttempt counts run attempts since the last explicit continuation.

type ExecutionCancellation

type ExecutionCancellation struct {
	Version   int    `json:"version"`
	RequestID string `json:"request_id"`
	Reason    string `json:"reason,omitempty"`
}

ExecutionCancellation is the versioned request retained in workflow history. The first accepted request supplies the reason used by cancellation cleanup.

func (ExecutionCancellation) Validate

func (r ExecutionCancellation) Validate() error

Validate bounds accepted data before persistence or replay.

type ExecutionList

type ExecutionList struct {
	Namespace    string `json:"namespace"`
	WorkflowID   string `json:"workflow_id,omitempty"`
	WorkflowType string `json:"workflow_type,omitempty"`
	BuildID      string `json:"build_id,omitempty"`
	State        State  `json:"state,omitempty"`
	Cursor       string `json:"cursor,omitempty"`
	Limit        int    `json:"limit"`
}

func (ExecutionList) Next

func (r ExecutionList) Next(e Execution) (string, error)

func (ExecutionList) Position

func (r ExecutionList) Position() (ReadPosition, error)

type ExecutionTarget

type ExecutionTarget struct {
	Key
	Selection RunSelection `json:"selection,omitempty"`
}

ExecutionTarget selects one snapshot. Current and latest require an empty RunID. Latest includes closed runs and follows successful creation, not timestamps.

func (ExecutionTarget) Validate

func (r ExecutionTarget) Validate() error

type ExecutionTermination

type ExecutionTermination struct {
	Version   int    `json:"version"`
	RequestID string `json:"request_id"`
	Reason    string `json:"reason,omitempty"`
}

ExecutionTermination records forced closure without claiming cooperation.

func (ExecutionTermination) Validate

func (r ExecutionTermination) Validate() error

type ExecutionTimeout

type ExecutionTimeout struct {
	Version    int                  `json:"version"`
	Kind       ExecutionTimeoutKind `json:"kind"`
	DeadlineAt time.Time            `json:"deadline_at"`
}

ExecutionTimeout records the immutable limit responsible for forced closure.

func (ExecutionTimeout) Validate

func (t ExecutionTimeout) Validate() error

Validate checks a timeout payload independently of a saved execution.

type ExecutionTimeoutClaimRequest

type ExecutionTimeoutClaimRequest struct {
	Namespace     string        `json:"namespace"`
	Owner         string        `json:"owner"`
	LeaseDuration time.Duration `json:"lease_duration"`
}

ExecutionTimeoutClaimRequest polls all expired builds in one namespace.

func (ExecutionTimeoutClaimRequest) Validate

func (r ExecutionTimeoutClaimRequest) Validate() error

type ExecutionTimeoutKind

type ExecutionTimeoutKind string

ExecutionTimeoutKind identifies which immutable workflow deadline won.

const (
	TimeoutRun       ExecutionTimeoutKind = "run"
	TimeoutExecution ExecutionTimeoutKind = "execution"
)

type ExecutionTimeoutRequest

type ExecutionTimeoutRequest struct {
	Key
	RequestID string `json:"request_id"`
	Owner     string `json:"owner"`
	Epoch     int64  `json:"epoch"`
}

ExecutionTimeoutRequest closes an expired execution under a live timeout grant.

func (ExecutionTimeoutRequest) Validate

func (r ExecutionTimeoutRequest) Validate() error

type ExecutionTimeoutTask

type ExecutionTimeoutTask struct {
	Key
	Kind       ExecutionTimeoutKind `json:"kind"`
	DeadlineAt time.Time            `json:"deadline_at"`
	Owner      string               `json:"owner"`
	Epoch      int64                `json:"epoch"`
	Attempt    int64                `json:"attempt"`
	LeaseUntil time.Time            `json:"lease_until"`
}

ExecutionTimeoutTask grants expiry processing independently of ordinary tasks.

type FinishQueryRemovalRequest

type FinishQueryRemovalRequest struct {
	Fence     QueryRemovalFence
	RequestID string
}

func (FinishQueryRemovalRequest) Validate

func (r FinishQueryRemovalRequest) Validate() error

type HeartbeatConfig

type HeartbeatConfig struct {
	Timeout time.Duration `json:"timeout"`
}

HeartbeatConfig enables activity progress. Zero Timeout disables only the progress deadline. Activation captures the task's attempt/overall deadline.

type HeartbeatRequest

type HeartbeatRequest struct {
	Key
	RequestID     string        `json:"request_id"`
	Token         TaskToken     `json:"token"`
	Sequence      int64         `json:"sequence"`
	Progress      []byte        `json:"progress,omitempty"`
	LeaseDuration time.Duration `json:"lease_duration"`
	// AsyncSecret proves ownership after handoff. Asynchronous heartbeats use
	// zero LeaseDuration because they have no worker lease to renew.
	AsyncSecret string `json:"async_secret,omitempty"`
}

HeartbeatRequest records one progress update under an enabled execution grant. Sequence starts at one per grant. Retry the identical request on uncertainty.

func (HeartbeatRequest) Validate

func (r HeartbeatRequest) Validate() error

Validate bounds heartbeat input before persistence.

type Key

type Key struct {
	Namespace  string `json:"namespace"`
	WorkflowID string `json:"workflow_id"`
	RunID      string `json:"run_id"`
}

Key identifies one run. Namespace is mandatory on every operation.

func (Key) Validate

func (k Key) Validate() error

Validate checks an execution identity before any database access.

type LegacyAttempt

type LegacyAttempt struct {
	Attempt   Delivery
	OutcomeID string
}

LegacyAttempt retains evidence before a nontransactional legacy command runs. An empty OutcomeID means the result is unconfirmed, including after restart.

type LegacyAttemptList

type LegacyAttemptList struct {
	InstallationID string
	Namespace      string
	After          string
	Limit          int
}

func (LegacyAttemptList) Validate

func (r LegacyAttemptList) Validate() error

type LegacyAuditStore

type LegacyAuditStore interface {
	BeginLegacyAttempt(context.Context, SecurityAudit) (LegacyAttempt, error)
	CompleteLegacyAttempt(context.Context, LegacyOutcome) error
	UnresolvedLegacyAttempts(context.Context, LegacyAttemptList) ([]LegacyAttempt, error)
}

LegacyAuditStore atomically pairs attempts/outcomes with their outbox intents. It does not make the intervening legacy mutation atomic with either write.

type LegacyOutcome

type LegacyOutcome struct {
	AttemptID string // the accepted attempt delivery ID
	Audit     SecurityAudit
}

func (LegacyOutcome) Validate

func (o LegacyOutcome) Validate(attempt, outcome Delivery) error

type LifecycleOperation

type LifecycleOperation string
const OperationEnrollRetirement LifecycleOperation = "namespace.retirement.enroll"
const OperationRequestWorkerDrain LifecycleOperation = "worker.drain.request"

type LifecycleReceipt

type LifecycleReceipt struct {
	WorkerDrain *WorkerDrainRequest `json:",omitempty"`
	NamespaceTarget
	Operation       LifecycleOperation
	RequestID       string
	RequestDigest   string
	CommandDigest   string
	ResponseVersion int
	AcceptedAt      time.Time
	DeliveryID      string
	Enrollment      *RetirementEnrollment
	QueryRuntime    *QueryRuntimeBinding
	QueryAbort      *QueryRemovalAbortEvidence `json:",omitempty"`
	Build           *BuildAdmission
}

LifecycleReceipt is the immutable accepted response, including derived facts. A receipt proves persistence, not a later process or infrastructure effect.

func (LifecycleReceipt) Clone

func (LifecycleReceipt) Match

Match validates stored evidence before allowing an exact accepted replay.

type LifecycleReceiptLookup

type LifecycleReceiptLookup struct {
	NamespaceTarget
	Operation     LifecycleOperation
	RequestID     string
	RequestDigest string
	CommandDigest string
}

func QueryRemovalFinalizationLookup

func QueryRemovalFinalizationLookup(r QueryRemovalRevalidationRequest, begin LifecycleReceipt, build BuildAdmission) (LifecycleReceiptLookup, bool, error)

QueryRemovalFinalizationLookup names the native receipt for a monotone finalization.

func (LifecycleReceiptLookup) Validate

func (r LifecycleReceiptLookup) Validate() error

type NamespaceConfig

type NamespaceConfig struct {
	InstallationID string
	Namespace      string
	AppID          string
	TenantID       string
	RequireAudit   bool
	RequireHooks   bool
	SchemaVersion  int
}

NamespaceConfig is immutable ownership within one physical store. Execution keys omit installation, so two installations cannot own the same namespace.

func (NamespaceConfig) Validate

func (c NamespaceConfig) Validate() error

type NamespaceList

type NamespaceList struct {
	InstallationID string
	After          string
	Limit          int
}

func (NamespaceList) Validate

func (r NamespaceList) Validate() error

type NamespaceRecord

type NamespaceRecord struct {
	NamespaceConfig
	CoverageStartedAt time.Time
	WriterProtocol    int
}

type NamespaceStore

type NamespaceStore interface {
	RegisterNamespace(context.Context, NamespaceConfig) (NamespaceRecord, error)
	GetNamespace(context.Context, string, string) (NamespaceRecord, error)
	ListNamespaces(context.Context, NamespaceList) ([]NamespaceRecord, error)
}

type NamespaceTarget

type NamespaceTarget struct {
	InstallationID string
	Namespace      string
}

NamespaceTarget binds a lifecycle operation to its persisted installation.

func (NamespaceTarget) Validate

func (t NamespaceTarget) Validate() error

type ObservationVersion

type ObservationVersion struct {
	CompatibilityVersion int64
	BuildVersion         int64
	ObservedAt           time.Time
}

ObservationVersion identifies catalog state only. Blocker counts can change at the same version; Finalize always computes them again under coordination.

type OutboxStore

type OutboxStore interface {
	AppendSecurityAudit(context.Context, SecurityAudit) (Delivery, error)
	ClaimDeliveries(context.Context, DeliveryClaim) ([]DeliveryRecord, error)
	RenewDelivery(context.Context, DeliveryToken, time.Duration) (time.Time, error)
	AcknowledgeDelivery(context.Context, DeliveryToken, SinkReceipt) error
	RetryDelivery(context.Context, DeliveryRetry) error
	BlockDelivery(context.Context, DeliveryToken) error
	DeliveryStatus(context.Context, DeliveryStatusRequest) (DeliveryStatus, error)
}

type ParentClosePolicy

type ParentClosePolicy string

ParentClosePolicy controls an open child when its parent closes.

const (
	ParentCloseTerminate     ParentClosePolicy = "terminate"
	ParentCloseRequestCancel ParentClosePolicy = "request_cancel"
	ParentCloseAbandon       ParentClosePolicy = "abandon"
	EventChildStarted                          = "workflow.child_started"
)

type QueryRejectionDiagnostic

type QueryRejectionDiagnostic struct {
	Stage           string             `json:"stage"`
	Reason          string             `json:"reason"`
	SQLState        string             `json:"sqlstate,omitempty"`
	Target          QueryRuntimeTarget `json:"target"`
	RequestID       string             `json:"request_id,omitempty"`
	Operation       LifecycleOperation `json:"operation,omitempty"`
	BindingState    string             `json:"binding_state,omitempty"`
	BindingVersion  int64              `json:"binding_version,omitempty"`
	VerifiedAt      time.Time          `json:"verified_at"`
	ValidUntil      time.Time          `json:"valid_until"`
	ObservedAt      time.Time          `json:"observed_at"`
	SettledAt       time.Time          `json:"settled_at"`
	IdentityMatches bool               `json:"identity_matches,omitempty"`
	Removed         bool               `json:"removed,omitempty"`
	AdmissionClosed bool               `json:"admission_closed,omitempty"`
	InFlight        int64              `json:"in_flight,omitempty"`
	UnknownClaims   int64              `json:"unknown_claims,omitempty"`
	ExpectedDigest  string             `json:"expected_digest,omitempty"`
	ActualDigest    string             `json:"actual_digest,omitempty"`
}

QueryRejectionDiagnostic is private instrumentation, never a command response. It contains values only, without query payloads or raw database messages.

func QueryRejectionDetails

func QueryRejectionDetails(err error) (QueryRejectionDiagnostic, bool)

QueryRejectionDetails returns a value copy suitable for trusted instrumentation.

type QueryRejectionError

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

func (*QueryRejectionError) Error

func (e *QueryRejectionError) Error() string

func (*QueryRejectionError) Unwrap

func (e *QueryRejectionError) Unwrap() error

type QueryRemovalAbortEvidence

type QueryRemovalAbortEvidence struct {
	Fence      QueryRemovalFence
	Settlement QueryRemovalSettlement
}

type QueryRemovalAbortVerifier

type QueryRemovalAbortVerifier interface {
	VerifyAbort(context.Context, QueryRuntimeBinding, QueryRemovalFence) (QueryRemovalSettlement, QueryRuntimeVerification, error)
}

QueryRemovalAbortVerifier is a trusted host boundary, never a remote request adapter. VerifyAbort settles this exact reservation in the host's operation ledger, then captures fresh existence and query evidence for its original identity. Issued deletion with an unknown outcome must return an error. Recover an accepted command receipt before invoking it again.

type QueryRemovalClosure

type QueryRemovalClosure struct {
	ExternalScope   QueryRemovalExternalScope
	CutoffReceiptID string
	CutoffDigest    string
	CoverageDigest  string
	Disposition     string
	TerminalDigest  string
	CutoffAt        time.Time
	TerminalAt      time.Time
	EvidenceDigest  string
	Attestation     string
}

QueryRemovalClosure proves permanent issuance cutoff and complete terminal coverage.

type QueryRemovalCommitLookup

type QueryRemovalCommitLookup struct{ QueryRemovalRevalidationLookup }

QueryRemovalCommitLookup identifies a saved commitment and its protected state.

type QueryRemovalCommitReceipt

type QueryRemovalCommitReceipt struct {
	Request       QueryRemovalCommitRequest
	RequestDigest string
	ReceiptDigest string
	AcceptedAt    time.Time
	DeliveryID    string
}

QueryRemovalCommitReceipt is a historical, nonissuing invocation association.

func (QueryRemovalCommitReceipt) Match

Match validates historical commit recovery before external verification.

func (*QueryRemovalCommitReceipt) Seal

func (r *QueryRemovalCommitReceipt) Seal() error

Seal authenticates a saved commit's entire typed request and response.

type QueryRemovalCommitRequest

type QueryRemovalCommitRequest struct {
	Guard                 QueryRemovalGuardReference
	RequestID             string
	CommandDigest         string
	ExpectedCurrentDigest string
	CurrentRequestID      string
	Permission            QueryRemovalPermission
}

QueryRemovalCommitRequest requires fresh current evidence for first acceptance.

func (QueryRemovalCommitRequest) Validate

func (r QueryRemovalCommitRequest) Validate() error

Validate checks a first bind's bounded typed external facts.

type QueryRemovalCommitStatus

type QueryRemovalCommitStatus struct {
	Receipt    QueryRemovalCommitReceipt
	Guard      QueryRemovalGuard
	Current    QueryRemovalCurrent
	ObservedAt time.Time
}

QueryRemovalCommitStatus reports observations without granting delegation.

type QueryRemovalCurrent

type QueryRemovalCurrent struct {
	GuardID        string
	RootDigest     string
	RequestID      string
	MaterialDigest string
	ObservedAt     time.Time
}

QueryRemovalCurrent is an exact pointer, never permission by itself.

type QueryRemovalDisposition

type QueryRemovalDisposition string

QueryRemovalDisposition describes a settled destructive operation. Unknown or in-flight deletion is deliberately absent from this closed set.

const (
	QueryRemovalNotIssued              QueryRemovalDisposition = "not_issued"
	QueryRemovalRejected               QueryRemovalDisposition = "rejected"
	QueryRemovalCancelled              QueryRemovalDisposition = "cancelled"
	QueryRemovalFenced                 QueryRemovalDisposition = "fenced"
	QueryRemovalSettledWithoutDeletion QueryRemovalDisposition = "settled_without_deletion"
)

type QueryRemovalEvidence

type QueryRemovalEvidence struct {
	BuildFinalizationRequestID     string
	BuildFinalizationRequestDigest string
	Disposition                    string
	CandidateProof                 QueryRuntimeVerification
	SurvivorProof                  QueryRuntimeVerification
	Process                        QueryRemovalProcess
	Positive                       QueryRemovalPositiveEffect
	ExcludedInstances              []string
	ObservedAt                     time.Time
	ValidUntil                     time.Time
	CandidateAttestation           string
	SurvivorAttestation            string
	ProcessAttestation             string
	ScopeAttestation               string
	PermissionAttestation          string
	ResultAttestation              string
	PreEffectAttestation           string
	AssociationAttestation         string
}

QueryRemovalEvidence is returned only by a configured trusted host verifier. Each attestation has its own independent 4096-byte allowance.

type QueryRemovalExternalScope

type QueryRemovalExternalScope struct {
	AuthorityID             string
	OperationScopeID        string
	AttemptID               string
	ProviderOperationID     string
	CoverageDigest          string
	ExcludedInstancesDigest string
	ProducerID              string
	ProfileID               string
	ProfileVersion          int64
	VerifierID              string
}

QueryRemovalExternalScope identifies one immutable external operation and producer.

func (QueryRemovalExternalScope) Validate

func (s QueryRemovalExternalScope) Validate() error

Validate admits bounded canonical native tokens and fixed digests.

type QueryRemovalFacts

type QueryRemovalFacts struct {
	Fence     QueryRemovalFence
	CheckedAt time.Time
}

type QueryRemovalFence

type QueryRemovalFence struct {
	Candidate             QueryRuntimeIdentity
	CandidateStateVersion int64
	Survivor              QueryRuntimeIdentity
	SurvivorStateVersion  int64
	SurvivorProof         QueryRuntimeVerification
	BuildEpoch            int64
	BuildVersion          int64
	BuildState            string
	RemovalEpoch          int64
	RequestID             string
	AcceptedAt            time.Time
	ValidUntil            time.Time
}

type QueryRemovalGuard

type QueryRemovalGuard struct {
	GuardID             string
	RootDigest          string
	OriginalDigest      string
	ExternalScopeDigest string
	CandidateDigest     string
	ProcessDigest       string
	InitialRequestID    string
	State               string
	CloseRequestID      string
	CloseDigest         string
}

QueryRemovalGuard is a compact immutable root with a monotone terminal state. Full identities are retained in the exact initial material row.

func QueryRemovalRoot

QueryRemovalRoot creates a compact root over the complete immutable association.

type QueryRemovalGuardCloseReceipt

type QueryRemovalGuardCloseReceipt struct {
	Request       QueryRemovalGuardCloseRequest
	RequestDigest string
	ReceiptDigest string
	AcceptedAt    time.Time
	DeliveryID    string
}

QueryRemovalGuardCloseReceipt retains closure despite expiry and later native mutations.

func (QueryRemovalGuardCloseReceipt) Match

Match validates historical close recovery without reissuing a cutoff.

func (*QueryRemovalGuardCloseReceipt) Seal

Seal authenticates a saved close's entire typed request and response.

type QueryRemovalGuardCloseRequest

type QueryRemovalGuardCloseRequest struct {
	Guard         QueryRemovalGuardReference
	RequestID     string
	CommandDigest string
	Closure       QueryRemovalClosure
}

QueryRemovalGuardCloseRequest permanently closes an exact guard.

func (QueryRemovalGuardCloseRequest) Validate

func (r QueryRemovalGuardCloseRequest) Validate() error

Validate checks affirmative permanent closure rather than timeout or absence.

type QueryRemovalGuardProbe

type QueryRemovalGuardProbe struct {
	Original          QueryRemovalOriginal
	ExternalScope     QueryRemovalExternalScope
	EvidenceReference string
	Survivor          QueryRuntimeTarget
	SurvivorVersion   int64
}

QueryRemovalGuardProbe carries opaque host record references, never remote evidence.

type QueryRemovalGuardReceipt

type QueryRemovalGuardReceipt struct {
	Commit *QueryRemovalCommitReceipt
	Close  *QueryRemovalGuardCloseReceipt
}

QueryRemovalGuardReceipt contains exactly one command receipt.

type QueryRemovalGuardReceiptLookup

type QueryRemovalGuardReceiptLookup struct {
	QueryRemovalRevalidationLookup
	Kind string
}

QueryRemovalGuardReceiptLookup reads exactly one finite command kind.

type QueryRemovalGuardReference

type QueryRemovalGuardReference struct {
	QueryRuntimeTarget
	OriginalDigest string
	GuardID        string
	RootDigest     string
}

QueryRemovalGuardReference binds every command to its immutable original and root.

func (QueryRemovalGuardReference) Match

Match checks a guard reference against authenticated initial material.

func (QueryRemovalGuardReference) Validate

func (r QueryRemovalGuardReference) Validate() error

Validate checks a compact exact original guard reference.

type QueryRemovalGuardVerifier

QueryRemovalGuardVerifier authenticates retained records outside native locks. Implementations must reject unsupported profiles and incomplete effect coverage.

type QueryRemovalOriginal

type QueryRemovalOriginal struct {
	QueryRuntimeTarget
	BeginRequestID        string
	BeginRequestDigest    string
	FenceDigest           string
	CandidateStateVersion int64
	RemovalEpoch          int64
}

QueryRemovalOriginal identifies an immutable accepted Begin reservation.

func (QueryRemovalOriginal) MatchOriginal

func (r QueryRemovalOriginal) MatchOriginal(receipt LifecycleReceipt) error

MatchOriginal resolves the exact historical Begin before checking current state.

func (QueryRemovalOriginal) Validate

func (r QueryRemovalOriginal) Validate() error

Validate checks the original reference without replacing its retained fence.

type QueryRemovalPermission

type QueryRemovalPermission struct {
	ExternalScope         QueryRemovalExternalScope
	PermissionID          string
	PermissionDigest      string
	CommandID             string
	StepDigest            string
	ResourceDigest        string
	IncarnationDigest     string
	RevalidationRequestID string
	RevalidationDigest    string
	AcceptedAt            time.Time
	EvidenceDigest        string
	Attestation           string
}

QueryRemovalPermission is authenticated external acceptance of one exact invocation.

type QueryRemovalPositiveEffect

type QueryRemovalPositiveEffect struct {
	PermissionID      string
	PermissionDigest  string
	ResultID          string
	ResultDigest      string
	CommandID         string
	ResourceID        string
	IncarnationID     string
	AssociationDigest string
	PreEffectDigest   string
	PreEffectAt       time.Time
	AcceptedAt        time.Time
	CompletedAt       time.Time
}

QueryRemovalPositiveEffect contains authenticated positive facts for one incarnation.

type QueryRemovalPreparedAbortVerifier

type QueryRemovalPreparedAbortVerifier interface {
	VerifyPreparedAbort(ctx context.Context, binding QueryRuntimeBinding, fence QueryRemovalFence, requestID, commandDigest string) (QueryRemovalSettlement, QueryRuntimeVerification, error)
}

QueryRemovalPreparedAbortVerifier binds retained host preparation to the exact incoming operator request. Hosts implementing it are never called through the legacy verifier for Abort, including when prepared verification refuses. commandDigest is the operator.query_runtime.abort.v1 fingerprint of the input.

type QueryRemovalProcess

type QueryRemovalProcess struct {
	HostID           string
	ProcessID        string
	DescriptorID     string
	DescriptorDigest string
	RegistrationID   string
	DrainRuntimeID   string
	DrainOperationID string
	DrainDeadline    time.Time
	Role             string
	Admission        string
	Claims           string
	DrainOutcome     string
	ObservedAt       time.Time
	ValidUntil       time.Time
}

QueryRemovalProcess binds the original startup, registration and drain tuple.

type QueryRemovalRevalidationLookup

type QueryRemovalRevalidationLookup struct {
	QueryRuntimeTarget
	RequestID     string
	CommandDigest string
	RequestDigest string
}

QueryRemovalRevalidationLookup recovers one immutable request, never fresh authority.

func (QueryRemovalRevalidationLookup) Validate

Validate checks the exact lookup association.

type QueryRemovalRevalidationMaterial

type QueryRemovalRevalidationMaterial struct {
	Request            QueryRemovalRevalidationRequest
	RequestDigest      string
	GuardID            string
	RootDigest         string
	Candidate          QueryRuntimeIdentity
	CandidateState     string
	CandidateVersion   int64
	RemovalEpoch       int64
	Build              BuildAdmission
	RetainedExecutions int64
	Survivor           QueryRuntimeIdentity
	SurvivorVersion    int64
	AcceptedAt         time.Time
	ValidUntil         time.Time
	DeliveryID         string
	MaterialDigest     string
}

QueryRemovalRevalidationMaterial retains the full authenticated acceptance facts.

func NewQueryRemovalMaterial

NewQueryRemovalMaterial builds the accepted facts after native validation.

func (QueryRemovalRevalidationMaterial) Clone

Clone copies the authenticated excluded set for callers and staging maps.

func (QueryRemovalRevalidationMaterial) Compact

Compact exports digests only; retained material remains the source of full facts.

func (QueryRemovalRevalidationMaterial) Match

Match checks immutable command or request recovery without refreshing its interval.

func (*QueryRemovalRevalidationMaterial) Seal

Seal computes the material commitment after transactional delivery identity is set.

func (QueryRemovalRevalidationMaterial) Validate

Validate verifies retained material before it participates in authority or replay.

type QueryRemovalRevalidationReceipt

type QueryRemovalRevalidationReceipt struct {
	Schema              string    `json:"schema"`
	GuardID             string    `json:"guard_id"`
	RootDigest          string    `json:"root_digest"`
	RequestID           string    `json:"request_id"`
	RequestDigest       string    `json:"request_digest"`
	MaterialDigest      string    `json:"material_digest"`
	OriginalDigest      string    `json:"original_digest"`
	ExternalScopeDigest string    `json:"external_scope_digest"`
	CandidateDigest     string    `json:"candidate_digest"`
	BuildDigest         string    `json:"build_digest"`
	SurvivorDigest      string    `json:"survivor_digest"`
	ProcessDigest       string    `json:"process_digest"`
	ExclusionDigest     string    `json:"exclusion_digest"`
	CoverageDigest      string    `json:"coverage_digest"`
	Disposition         string    `json:"disposition"`
	AcceptedAt          time.Time `json:"accepted_at"`
	ValidUntil          time.Time `json:"valid_until"`
}

QueryRemovalRevalidationReceipt is the bounded exported commitment to material.

type QueryRemovalRevalidationRequest

type QueryRemovalRevalidationRequest struct {
	Original              QueryRemovalOriginal
	ExternalScope         QueryRemovalExternalScope
	RequestID             string
	CommandDigest         string
	ExpectedCurrentDigest string
	Survivor              QueryRuntimeTarget
	SurvivorVersion       int64
	Evidence              QueryRemovalEvidence
}

QueryRemovalRevalidationRequest accepts fresh evidence for the same reservation.

func (QueryRemovalRevalidationRequest) Clone

Clone prevents caller mutations from changing admitted evidence.

func (QueryRemovalRevalidationRequest) Validate

Validate checks bounded input before any authority write.

type QueryRemovalRevalidationStore

QueryRemovalRevalidationStore is optional. Hosts without it must refuse this profile.

type QueryRemovalSettlement

type QueryRemovalSettlement struct {
	FenceDigest         string
	VerifierID          string
	EvidenceDigest      string
	Disposition         QueryRemovalDisposition
	ExternalOperationID string
	SettledAt           time.Time
}

QueryRemovalSettlement comes only from the trusted removal controller. Its operation identity is allocated before dispatch and need not be a provider ID. NotIssued requires atomic revocation of future issuance. Cancelled requires definitive operation settlement. Fenced requires prevention of issuance or a provider-enforced fence that prevents an outstanding deletion from completing. A lease expiry, cancelled client context or healthy probe is not settlement.

func (QueryRemovalSettlement) Validate

type QueryRetentionFacts

type QueryRetentionFacts struct {
	BuildTarget
	RetainedExecutions int64
	ActiveBindings     int64
	VerifiedBindings   int64
	ObservedAt         time.Time
}

func QueryRetention

func QueryRetention(build BuildAdmission, retained int64, bindings []QueryRuntimeBinding, now time.Time) QueryRetentionFacts

type QueryRuntimeBinding

type QueryRuntimeBinding struct {
	QueryRuntimeIdentity
	State        string
	Version      int64
	RemovalEpoch int64
	CreatedAt    time.Time
	ChangedAt    time.Time
	Verification QueryRuntimeVerification
	Removal      QueryRemovalFence
}

func AbortQueryRemoval

AbortQueryRemoval requires settled removal and fresh query proof under the same namespace coordination that excludes competing removal reservations.

func FinishQueryRemoval

FinishQueryRemoval records an external effect against its original reservation. It deliberately does not turn an expired reservation into new permission.

func ReserveQueryRemoval

func ReserveQueryRemoval(candidate QueryRuntimeBinding, r BeginQueryRemovalRequest, build BuildAdmission, retained int64, bindings []QueryRuntimeBinding, now time.Time) (QueryRuntimeBinding, error)

ReserveQueryRemoval selects an independent verified survivor under exclusive namespace coordination. Removing bindings never count as survivors.

func VerifyQueryBinding

VerifyQueryBinding conditionally records trusted host evidence after locks.

func (QueryRuntimeBinding) Validate

func (b QueryRuntimeBinding) Validate() error

type QueryRuntimeIdentity

type QueryRuntimeIdentity struct {
	QueryRuntimeTarget
	InstanceID      string
	IdentityVersion int64
	BuildIdentity   BuildQueryIdentity
}

func (QueryRuntimeIdentity) Validate

func (i QueryRuntimeIdentity) Validate() error

type QueryRuntimeList

type QueryRuntimeList struct {
	NamespaceTarget
	InstanceID string
	BuildID    string
	After      string
	Limit      int
}

func (QueryRuntimeList) Validate

func (r QueryRuntimeList) Validate() error

type QueryRuntimePage

type QueryRuntimePage struct {
	Items      []QueryRuntimeBinding
	Next       string
	ObservedAt time.Time
}

type QueryRuntimeStore

type QueryRuntimeStore interface {
	RegisterQueryRuntime(context.Context, RegisterQueryRuntimeRequest) (LifecycleReceipt, error)
	RecordQueryRuntimeVerification(context.Context, VerifyQueryRuntimeRequest) (LifecycleReceipt, error)
	InspectQueryRetention(context.Context, BuildTarget) (QueryRetentionFacts, error)
	ListQueryRuntimes(context.Context, QueryRuntimeList) (QueryRuntimePage, error)
	BeginQueryRuntimeRemoval(context.Context, BeginQueryRemovalRequest) (LifecycleReceipt, error)
	CheckQueryRuntimeRemoval(context.Context, QueryRemovalFence) (QueryRemovalFacts, error)
	FinishQueryRuntimeRemoval(context.Context, FinishQueryRemovalRequest) (LifecycleReceipt, error)
	AbortQueryRuntimeRemoval(context.Context, AbortQueryRemovalRequest) (LifecycleReceipt, error)
}

type QueryRuntimeTarget

type QueryRuntimeTarget struct {
	BuildTarget
	RuntimeID string
}

func (QueryRuntimeTarget) Validate

func (t QueryRuntimeTarget) Validate() error

type QueryRuntimeVerification

type QueryRuntimeVerification struct {
	Identity           QueryRuntimeIdentity
	ProofID            string
	VerifierID         string
	EvidenceDigest     string
	ProbePolicyID      string
	ProbePolicyVersion int64
	VerifiedAt         time.Time
	ValidUntil         time.Time
	AcceptedAt         time.Time
}

func (QueryRuntimeVerification) Validate

func (p QueryRuntimeVerification) Validate(identity QueryRuntimeIdentity, now time.Time) error

type ReadPosition

type ReadPosition struct {
	CreatedAt  time.Time `json:"created_at"`
	WorkflowID string    `json:"workflow_id"`
	ID         string    `json:"id"`
	Binding    string    `json:"binding"`
}

type ReadStore

type ReadStore interface {
	ListExecutions(context.Context, ExecutionList) ([]Execution, string, error)
	ListTasks(context.Context, TaskList) ([]Task, string, error)
	ReadDeliveryStatus(context.Context, ScopedDeliveryStatus) (DeliveryStatus, error)
	ReadBuildFacts(context.Context, string, string) (BuildFacts, error)
}

ReadStore is trusted persistence. Callers authorize the complete namespace predicate before reading it. Pages observe current rows, not a shared snapshot.

type Receipt

type Receipt struct {
	Revision      int64 `json:"revision"`
	FirstSequence int64 `json:"first_sequence"`
	LastSequence  int64 `json:"last_sequence"`
}

Receipt records the original result of an accepted request. It is returned unchanged on retries, even after subsequent transitions.

type ReceiptRequest

type ReceiptRequest struct {
	Key
	RequestID    string `json:"request_id"`
	IntentDigest string `json:"intent_digest"`
}

ReceiptRequest resolves an accepted client intent, even after its run closes. The coordinator must hash the complete client request, including operation, identity and credentials, before preparing a state-dependent transition. This is a trusted store operation, not a remote authorization boundary.

func (ReceiptRequest) Validate

func (r ReceiptRequest) Validate() error

Validate rejects malformed lookups without disclosing their proof.

type RegisterBuildRequest

type RegisterBuildRequest struct {
	Identity      *BuildQueryIdentity `json:",omitempty"`
	CommandDigest string              `json:",omitempty"`
	BuildTarget
	RequestID       string
	ExpectedVersion int64
}

func (RegisterBuildRequest) Validate

func (r RegisterBuildRequest) Validate() error

type RegisterQueryRuntimeRequest

type RegisterQueryRuntimeRequest struct {
	Identity      QueryRuntimeIdentity
	RequestID     string
	CommandDigest string
}

func (RegisterQueryRuntimeRequest) Validate

func (r RegisterQueryRuntimeRequest) Validate() error

type RetirementEnrollment

type RetirementEnrollment struct {
	Compatibility         CompatibilityFacts
	HistoricalBuildCount  int64
	HistoricalBuildDigest string
}

type RetirementEnrollmentRequest

type RetirementEnrollmentRequest struct {
	NamespaceTarget
	RequestID      string
	SchemaVersion  int
	WriterProtocol int
}

func (RetirementEnrollmentRequest) Validate

func (r RetirementEnrollmentRequest) Validate() error

type RetirementEnrollmentStore

type RetirementEnrollmentStore interface {
	InspectCompatibility(context.Context, NamespaceTarget) (CompatibilityFacts, error)
	EnrollRetirement(context.Context, RetirementEnrollmentRequest) (LifecycleReceipt, error)
	LookupLifecycleReceipt(context.Context, LifecycleReceiptLookup) (LifecycleReceipt, error)
}

RetirementEnrollmentStore is optional. Base Store implementations remain usable without enrolling a namespace in persisted deployment retirement.

type RunMetadata

type RunMetadata struct {
	RetryAttempt   int64     `json:"retry_attempt,omitempty"`
	RunAvailableAt time.Time `json:"run_available_at,omitzero"`
	Key
	FirstRunID          string        `json:"first_run_id"`
	PreviousRunID       string        `json:"previous_run_id,omitempty"`
	RunNumber           int64         `json:"run_number"`
	FirstStartedAt      time.Time     `json:"first_started_at"`
	CreatedAt           time.Time     `json:"created_at"`
	RunTimeout          time.Duration `json:"run_timeout,omitempty"`
	RunDeadlineAt       time.Time     `json:"run_deadline_at,omitempty"`
	ExecutionDeadlineAt time.Time     `json:"execution_deadline_at,omitempty"`
}

RunMetadata identifies one run within an immutable chain without its payloads.

func RunMetadataOf

func RunMetadataOf(e Execution) RunMetadata

RunMetadataOf copies the lineage used in successor and child-result history.

func (RunMetadata) Validate

func (r RunMetadata) Validate() error

type RunSelection

type RunSelection string

RunSelection distinguishes an explicit run from a workflow identity lookup.

const (
	RunExplicit RunSelection = ""
	RunCurrent  RunSelection = "current"
	RunLatest   RunSelection = "latest"
)

type RunStarted

type RunStarted struct {
	Version int         `json:"version"`
	Run     RunMetadata `json:"run"`
}

RunStarted records the successor's immutable lineage in its own history.

type ScopedDeliveryStatus

type ScopedDeliveryStatus struct {
	DeliveryStatusRequest
	Key
}

func (ScopedDeliveryStatus) Validate

func (r ScopedDeliveryStatus) Validate() error

type SecurityAudit

type SecurityAudit struct {
	InstallationID string
	Namespace      string
	WorkflowID     string
	RunID          string
	AttemptID      string
	OccurredAt     time.Time
	Action         string
	Outcome        string
	Target         string
	Metadata       AuditMetadata
}

func CaptureSecurityAudit

func CaptureSecurityAudit(installation, namespace, action, outcome, target string, metadata AuditMetadata) (SecurityAudit, error)

CaptureSecurityAudit allocates immutable server identity and time once. Retry the returned value unchanged after an unknown persistence outcome.

func (SecurityAudit) Delivery

func (a SecurityAudit) Delivery(n NamespaceRecord) (Delivery, error)

type Signal

type Signal struct {
	Version int    `json:"version"`
	ID      string `json:"id"`
	Name    string `json:"name"`
	Input   []byte `json:"input,omitempty"`
}

Signal is the versioned history payload for one accepted message.

func (Signal) Validate

func (s Signal) Validate() error

Validate bounds a message before it reaches storage or replay.

type SignalConsumption

type SignalConsumption struct {
	Version   int    `json:"version"`
	CommandID string `json:"command_id"`
	SignalID  string `json:"signal_id"`
}

SignalConsumption binds one accepted message to a stable receive command.

type SignalReceipt

type SignalReceipt struct {
	Key
	Receipt
	Started bool `json:"started"`
}

SignalReceipt returns the actual target and original acceptance coordinates. It does not assert that workflow code consumed or processed the signal.

type SignalRequest

type SignalRequest struct {
	Key
	RequestID string `json:"request_id"`
	BuildID   string `json:"build_id"`
	Name      string `json:"name"`
	Input     []byte `json:"input,omitempty"`
}

SignalRequest targets one run, or the current open run when RunID is empty. RequestID is unique across both signal APIs within a namespace/workflow ID. Repeat the whole original request after an unknown response.

func (SignalRequest) Validate

func (r SignalRequest) Validate() error

Validate allows an empty run selector but requires explicit namespace/build.

type SignalStartOutcome

type SignalStartOutcome struct {
	Receipt   SignalReceipt
	Recovered bool
}

SignalStartOutcome is trusted acceptance provenance. Recovered is determined under the same lock/transaction as receipt lookup and acceptance. It is not part of the persisted receipt, request fingerprint or public wire schema.

type SignalStartOutcomeStore

type SignalStartOutcomeStore interface {
	SignalWithStartOutcome(context.Context, SignalWithStartRequest) (SignalStartOutcome, error)
}

SignalStartOutcomeStore is required by remote signal-with-start adapters. A lookup performed before a separate mutation cannot implement this contract.

type SignalWithStartRequest

type SignalWithStartRequest struct {
	Start StartRequest `json:"start"`
	Name  string       `json:"name"`
	Input []byte       `json:"input,omitempty"`
}

SignalWithStartRequest accepts a signal on the open run or atomically creates Start.RunID first. Start.RequestID identifies this entire operation. An existing run preserves its type, input and queue, and must match Start.BuildID.

func (SignalWithStartRequest) Validate

func (r SignalWithStartRequest) Validate() error

Validate requires a complete proposed start identity, even when an open run wins.

type SinkReceipt

type SinkReceipt struct {
	MappingVersion  int
	SinkFingerprint string
	Evidence        string
	ID              string
	DeliveryID      string
	Destination     Destination
	SchemaVersion   int
	Fingerprint     string
}

func (SinkReceipt) Verify

func (r SinkReceipt) Verify(d Delivery) error

type StartRequest

type StartRequest struct {
	Key
	RequestID        string               `json:"request_id"`
	WorkflowType     string               `json:"workflow_type"`
	BuildID          string               `json:"build_id"`
	Queue            string               `json:"queue"`
	Input            []byte               `json:"input,omitempty"`
	RunTimeout       time.Duration        `json:"run_timeout,omitempty"`
	ExecutionTimeout time.Duration        `json:"execution_timeout,omitempty"`
	RetryPolicy      *WorkflowRetryPolicy `json:"retry_policy,omitempty"`
}

StartRequest creates a run, its first event and its initial workflow task. Reuse the entire request, including RunID, when retrying an unknown outcome.

func (StartRequest) Clone

func (r StartRequest) Clone() StartRequest

Clone isolates a retained start request from caller-owned memory.

func (StartRequest) Validate

func (r StartRequest) Validate() error

Validate checks the immutable start request.

type State

type State string

State is the persisted execution lifecycle.

const (
	StateRunning        State = "running"
	StateCompleted      State = "completed"
	StateFailed         State = "failed"
	StateCancelled      State = "cancelled"
	StateTerminated     State = "terminated"
	StateTimedOut       State = "timed_out"
	StateContinuedAsNew State = "continued_as_new"
)

Execution states. Only Running accepts new transitions.

type Store

type Store interface {
	StartExecution(context.Context, StartRequest) (Receipt, error)
	// Signal receipts are scoped by namespace/workflow across runs and survive
	// target closure. Acceptance records history and runnable work atomically.
	SignalExecution(context.Context, SignalRequest) (SignalReceipt, error)
	SignalWithStart(context.Context, SignalWithStartRequest) (SignalReceipt, error)
	// RequestCancelExecution records acceptance and a wakeup, not terminal state.
	RequestCancelExecution(context.Context, CancelExecutionRequest) (CancelExecutionReceipt, error)
	GetExecution(context.Context, Key) (Execution, error)
	// ResolveExecution fixes one snapshot without claiming tasks or writing history.
	ResolveExecution(context.Context, ExecutionTarget) (Execution, error)
	GetChildExecution(context.Context, Key, string) (ChildExecution, error)
	GetParentExecution(context.Context, Key) (ChildExecution, error)
	ListChildExecutions(context.Context, Key, string, int) ([]ChildExecution, error)
	ClaimChildDelivery(context.Context, ChildDeliveryClaimRequest) (*ChildDelivery, error)
	ApplyChildDelivery(context.Context, ChildDeliveryRequest) (ChildDeliveryReceipt, error)
	GetChildDelivery(context.Context, Key, string) (ChildDelivery, error)
	ListChildDeliveries(context.Context, Key, string, int) ([]ChildDelivery, error)
	// GetTask returns persisted state, including finished tasks, in one namespace.
	GetTask(context.Context, Key, string) (Task, error)
	// ReadHistory returns events after the exclusive cursor, in sequence order.
	// Limits must be between 1 and 1000. A missing run is ErrNotFound.
	ReadHistory(ctx context.Context, key Key, after int64, limit int) ([]Event, error)
	// ClaimTask returns nil when no eligible task exists. Reclaims increment epoch.
	ClaimTask(context.Context, ClaimRequest) (*Task, error)
	// ClaimTimeoutTask grants expired activity processing without consuming an execution attempt.
	ClaimTimeoutTask(context.Context, TimeoutClaimRequest) (*Task, error)
	// Execution expiry has independent ownership and needs no workflow build.
	ClaimExecutionTimeout(context.Context, ExecutionTimeoutClaimRequest) (*ExecutionTimeoutTask, error)
	ApplyExecutionTimeout(context.Context, ExecutionTimeoutRequest) (Receipt, error)
	RenewTask(context.Context, Key, TaskToken, time.Duration) (time.Time, error)
	// RecordHeartbeat changes task progress without appending workflow history.
	RecordHeartbeat(context.Context, HeartbeatRequest) (Receipt, error)
	CommitTransition(context.Context, CommitRequest) (Receipt, error)
	// LookupReceipt recovers a matching client intent without checking current
	// ownership or lifecycle. A missing receipt is false,nil; a missing run is
	// ErrNotFound. Errors return false and a zero receipt. A miss cannot rule out
	// an in-flight commit. Legacy receipts reject lookup with ErrRequestConflict.
	LookupReceipt(context.Context, ReceiptRequest) (Receipt, bool, error)
}

Store is an explicit backend capability. Implementations must provide atomic transitions and durable receipts; implementing the older workflow.Store does not satisfy this contract. Memory implements it only for tests and development.

Lease checks use the store's clock and reject expired grants before reclamation. A transport error can mean an unknown commit outcome. Retry the identical request to resolve that uncertainty through its receipt.

type Task

type Task struct {
	Key
	TaskSpec
	Owner      string        `json:"owner"`
	Epoch      int64         `json:"epoch"`
	Attempt    int64         `json:"attempt"`
	LeaseUntil time.Time     `json:"lease_until"`
	Version    int64         `json:"version"`
	DeadlineAt time.Time     `json:"deadline_at,omitempty"`
	Progress   []byte        `json:"progress,omitempty"`
	Done       bool          `json:"done"`
	LeaseKind  TaskLeaseKind `json:"lease_kind,omitempty"`
	// HeartbeatAt starts at attempt activation and advances on accepted progress.
	HeartbeatAt       time.Time     `json:"heartbeat_at,omitempty"`
	HeartbeatTimeout  time.Duration `json:"heartbeat_timeout,omitempty"`
	HeartbeatLimit    time.Time     `json:"heartbeat_limit,omitempty"`
	HeartbeatSequence int64         `json:"heartbeat_sequence,omitempty"`
	HeartbeatEpoch    int64         `json:"heartbeat_epoch,omitempty"`
	// AsyncKeyHash verifies callback secrets without exposing them in task JSON.
	AsyncKeyHash string `json:"-"`
}

Task is a persisted unit of work. Claims attach an ownership grant; its epoch fences earlier grants. Version protects task observations independently.

func ApplyHeartbeat

func ApplyHeartbeat(task Task, r HeartbeatRequest, now time.Time) (Task, error)

ApplyHeartbeat computes a task mutation under the backend's execution/task locks. The backend must check the immutable receipt before calling this.

func NewTask

func NewTask(key Key, spec TaskSpec, now time.Time) (Task, error)

NewTask resolves scheduling against the transition timestamp. Relative fields are cleared in the persisted projection; the immutable receipt retains them.

func UpdateTask

func UpdateTask(task Task, update *TaskUpdate, now time.Time) (Task, error)

UpdateTask computes source task state after its grant has been validated.

func (Task) Token

func (t Task) Token() TaskToken

Token returns a grant's identity. An asynchronous mutation also needs its secret.

type TaskAction

type TaskAction string

TaskAction determines whether a transition consumes or retains its source task.

const (
	TaskComplete TaskAction = "complete"
	TaskKeep     TaskAction = "keep"
	TaskRetry    TaskAction = "retry"
	TaskAwait    TaskAction = "await"
)

type TaskCondition

type TaskCondition struct {
	TaskID          string `json:"task_id"`
	Version         int64  `json:"version"`
	DeadlineElapsed bool   `json:"deadline_elapsed,omitempty"`
}

TaskCondition protects an observation of an unfinished task in the same run. DeadlineElapsed additionally requires a nonzero deadline at or before store time. Cancellation requires a condition for every target and cannot target the source.

type TaskKind

type TaskKind string

TaskKind separates workflow decisions, activities and timer processing.

const (
	TaskWorkflow TaskKind = "workflow"
	TaskActivity TaskKind = "activity"
	TaskTimer    TaskKind = "timer"
)

Task kinds use separate pollers even when they share a queue name.

type TaskLeaseKind

type TaskLeaseKind string

TaskLeaseKind distinguishes worker, asynchronous and timeout grants. The zero value is execution, preserving older task-token serialization.

const LeaseAsync TaskLeaseKind = "async"

LeaseAsync waits for an external result under the activity deadline.

const LeaseTimeout TaskLeaseKind = "timeout"

type TaskList

type TaskList struct {
	Key
	Kind   TaskKind `json:"kind,omitempty"`
	Cursor string   `json:"cursor,omitempty"`
	Limit  int      `json:"limit"`
}

func (TaskList) Next

func (r TaskList) Next(t Task) (string, error)

func (TaskList) Position

func (r TaskList) Position() (ReadPosition, error)

type TaskSpec

type TaskSpec struct {
	ID          string    `json:"id"`
	Kind        TaskKind  `json:"kind"`
	Queue       string    `json:"queue"`
	Payload     []byte    `json:"payload,omitempty"`
	AvailableAt time.Time `json:"available_at"`
	// Relative availability and deadline are resolved by the store on insertion.
	// AvailableAt and AvailableAfter are mutually exclusive. DeadlineAfter is
	// measured from the resolved availability, including a queued retry delay.
	AvailableAfter time.Duration `json:"available_after,omitempty"`
	DeadlineAfter  time.Duration `json:"deadline_after,omitempty"`
	// DeadlineLimit caps the resolved deadline, including when availability is later.
	DeadlineLimit *time.Time `json:"deadline_limit,omitempty"`
}

TaskSpec schedules work in the same transaction as its history events. IDs are unique for the lifetime of a run, including completed tasks. A zero AvailableAt means immediately; timers require an explicit deadline.

type TaskToken

type TaskToken struct {
	TaskID    string        `json:"task_id"`
	Owner     string        `json:"owner"`
	Epoch     int64         `json:"epoch"`
	LeaseKind TaskLeaseKind `json:"lease_kind,omitempty"`
}

TaskToken identifies a particular ownership grant, not just a worker.

func (TaskToken) Validate

func (t TaskToken) Validate() error

Validate checks a task token's shape; the store checks its ownership.

type TaskUpdate

type TaskUpdate struct {
	Action        TaskAction     `json:"action"`
	RetryAt       time.Time      `json:"retry_at,omitempty"`
	RetryAfter    time.Duration  `json:"retry_after,omitempty"`
	DeadlineAfter *time.Duration `json:"deadline_after,omitempty"`
	Progress      *[]byte        `json:"progress,omitempty"`
	// DeadlineLimit caps a newly calculated or retained deadline.
	DeadlineLimit *time.Time `json:"deadline_limit,omitempty"`
	// LeaseDuration renews a retained execution grant in the same transaction.
	LeaseDuration time.Duration `json:"lease_duration,omitempty"`
	// Heartbeat enables progress recording for this retained activity grant.
	Heartbeat *HeartbeatConfig `json:"heartbeat,omitempty"`
	// AsyncKeyHash transfers a live activity grant to asynchronous ownership.
	// Only TaskAwait accepts it; all other update fields must be absent.
	AsyncKeyHash string `json:"async_key_hash,omitempty"`
}

TaskUpdate modifies the source task atomically with its execution history. A nil update finishes the task. Retry clears its ownership grant immediately. A nil deadline/progress leaves that field unchanged. A zero pointed deadline explicitly clears it; a nonzero deadline is relative to store time (Keep) or the resolved retry availability (Retry).

type TimeoutClaimRequest

type TimeoutClaimRequest struct {
	Namespace     string
	BuildID       string
	Owner         string
	LeaseDuration time.Duration
}

TimeoutClaimRequest polls expired activities across queues in one namespace. BuildID is optional at the trusted store boundary; runtime workers require it.

func (TimeoutClaimRequest) Validate

func (r TimeoutClaimRequest) Validate() error

Validate checks timeout-coordinator routing and its independent lease.

type VerifyQueryRuntimeRequest

type VerifyQueryRuntimeRequest struct {
	QueryRuntimeTarget
	RequestID       string
	CommandDigest   string
	ExpectedVersion int64
	Verification    QueryRuntimeVerification
}

func (VerifyQueryRuntimeRequest) Validate

func (r VerifyQueryRuntimeRequest) Validate() error

type WorkerDrainRequest

type WorkerDrainRequest struct {
	WorkerProcessIdentity
	RequestID     string
	CommandDigest string
	OperationID   string
	Deadline      time.Time
}

WorkerDrainRequest persists acceptance before a trusted host invokes drain. Its receipt never establishes actual admission closure or handler quiescence.

func (WorkerDrainRequest) Validate

func (r WorkerDrainRequest) Validate() error

type WorkerDrainStore

type WorkerDrainStore interface {
	RequestWorkerDrain(context.Context, WorkerDrainRequest) (LifecycleReceipt, error)
}

type WorkerProcessIdentity

type WorkerProcessIdentity struct {
	BuildTarget
	Queue      string
	RuntimeID  string
	InstanceID string
}

WorkerProcessIdentity binds one process incarnation to its immutable routing. A restarted process needs a new RuntimeID even when InstanceID is reused.

func (WorkerProcessIdentity) Validate

func (i WorkerProcessIdentity) Validate() error

type WorkflowRetryPolicy

type WorkflowRetryPolicy struct {
	InitialInterval    time.Duration `json:"initial_interval"`
	MaximumInterval    time.Duration `json:"maximum_interval"`
	BackoffCoefficient float64       `json:"backoff_coefficient"`
	MaximumAttempts    int64         `json:"maximum_attempts"`
	NonRetryableTypes  []string      `json:"non_retryable_types,omitempty"`
}

WorkflowRetryPolicy opts a workflow into new runs after retryable failures. Nil and entirely zero policies disable retries. For a configured policy, zero fields use a 1s initial interval, coefficient 2, 100x maximum interval and unlimited attempts. MaximumAttempts includes the first run; 1 disables retries.

func NormalizeWorkflowRetryPolicy

func NormalizeWorkflowRetryPolicy(input *WorkflowRetryPolicy) (*WorkflowRetryPolicy, error)

NormalizeWorkflowRetryPolicy validates and copies explicitly configured retry options. It does not change the caller's policy or enable an absent policy.

func (*WorkflowRetryPolicy) Clone

Clone returns a policy whose failure-type list does not alias the original.

type WorkflowRetryScheduled

type WorkflowRetryScheduled struct {
	Version     int           `json:"version"`
	Next        RunMetadata   `json:"next"`
	Delay       time.Duration `json:"delay"`
	FailureType string        `json:"failure_type"`
}

WorkflowRetryScheduled binds the original failed/timed-out outcome to its successor. It precedes that terminal event, which remains the run's last event.

type WorkflowRetrySuppressed

type WorkflowRetrySuppressed struct {
	Version            int    `json:"version"`
	Reason             string `json:"reason"`
	SourceLastSequence int64  `json:"source_last_sequence"`
	FailureType        string `json:"failure_type"`
}

WorkflowRetrySuppressed records why a valid policy could not carry retained input into a bounded successor. The source keeps its original terminal outcome.

type WorkflowTaskDeferral

type WorkflowTaskDeferral struct {
	Key
	TaskID         string
	RequestID      string
	SourceEpoch    int64
	SourceRevision int64
	ReferenceKind  DeferralReferenceKind
	CommandID      string
	WorkflowTaskDeferralReceipt
	Active bool
}

func (WorkflowTaskDeferral) IsActive

func (d WorkflowTaskDeferral) IsActive(e Execution, task Task) bool

type WorkflowTaskDeferralReceipt

type WorkflowTaskDeferralReceipt struct {
	Receipt
	TaskVersion           int64
	DeferralCount         int64
	RecordedAt            time.Time
	RetryAt               time.Time
	Reason                string
	TargetBuildID         string
	TargetRetirementEpoch int64
	TargetState           DeferralTargetState
	PolicyVersion         int
}

type WorkflowTaskDeferralRequest

type WorkflowTaskDeferralRequest struct {
	Key
	RequestID             string
	Token                 TaskToken
	ExpectedRevision      int64
	TargetBuildID         string
	TargetRetirementEpoch int64
	TargetState           DeferralTargetState
	ReferenceKind         DeferralReferenceKind
	CommandID             string
}

func NewWorkflowTaskDeferralRequest

func NewWorkflowTaskDeferralRequest(task Task, revision int64, refusal *BuildAdmissionError) (WorkflowTaskDeferralRequest, error)

func (WorkflowTaskDeferralRequest) Validate

func (r WorkflowTaskDeferralRequest) Validate() error

type WorkflowTaskDeferralStore

type WorkflowTaskDeferralStore interface {
	DeferWorkflowTask(context.Context, WorkflowTaskDeferralRequest) (WorkflowTaskDeferralReceipt, error)
	GetWorkflowTaskDeferral(context.Context, Key, string) (WorkflowTaskDeferral, error)
}

Directories

Path Synopsis
Package delivery publishes accepted outbox intents independently of workflow workers.
Package delivery publishes accepted outbox intents independently of workflow workers.
ecosystem
Package ecosystem maps Dispatch envelopes to reliable ecosystem acceptance APIs.
Package ecosystem maps Dispatch envelopes to reliable ecosystem acceptance APIs.
Package durabletest checks the execution store's atomicity and lease contract.
Package durabletest checks the execution store's atomicity and lease contract.
Package runtime evaluates durable workflow decisions against recorded history.
Package runtime evaluates durable workflow decisions against recorded history.

Jump to

Keyboard shortcuts

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