runner

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EnvOperationID binds a Job result to one controller operation claim.
	EnvOperationID = "PTAH_OPERATION_ID"
	// EnvRequestedReference is the mutable OCI reference supplied by the user.
	EnvRequestedReference = "PTAH_REQUESTED_REFERENCE"
	// EnvResolvedReference is the earlier immutable OCI resolution.
	EnvResolvedReference = "PTAH_RESOLVED_REFERENCE"
	// EnvVerificationPolicy is the mounted verification policy path.
	EnvVerificationPolicy = "PTAH_VERIFICATION_POLICY"
	// EnvExpectedArtifactType is the exact allowed OCI artifact type.
	EnvExpectedArtifactType = "PTAH_EXPECTED_ARTIFACT_TYPE"
	// EnvPlanDir is the projected directory containing ordered plan chunks.
	EnvPlanDir = "PTAH_PLAN_DIR"
	// EnvExpectedPlanContentDigest binds apply to exact reconstructed bytes.
	EnvExpectedPlanContentDigest = "PTAH_EXPECTED_PLAN_CONTENT_DIGEST"
	// EnvExpectedTargetIdentityDigest binds apply to the credential-free target
	// route identity observed before the plan was created and approved.
	EnvExpectedTargetIdentityDigest = "PTAH_EXPECTED_TARGET_IDENTITY_DIGEST"
	// EnvCoordinationDigest binds every database operation to a user-declared
	// physical database realm without exposing its plaintext coordination key.
	EnvCoordinationDigest = "PTAH_COORDINATION_DIGEST"
	// EnvExpectedCoordinationDigest binds Apply to the realm approved in its
	// immutable plan independently from the operation claim.
	EnvExpectedCoordinationDigest = "PTAH_EXPECTED_COORDINATION_DIGEST"
	// EnvExpectedMigrationSequence is the ordered sequence a migration Apply's
	// approved plan carries, as JSON. The runner digests it again, refuses it
	// unless it matches EnvExpectedMigrationSequenceDigest, and hands it to
	// `migrations up --expect-sequence`.
	EnvExpectedMigrationSequence = "PTAH_EXPECTED_MIGRATION_SEQUENCE"
	// EnvExpectedMigrationSequenceDigest binds a migration Apply to the exact
	// ordered sequence its approved plan carries.
	EnvExpectedMigrationSequenceDigest = "PTAH_EXPECTED_MIGRATION_SEQUENCE_DIGEST"
	// EnvExpectedMigrationHistoryFingerprint binds it to the reading of the
	// revision table that plan was computed against.
	EnvExpectedMigrationHistoryFingerprint = "PTAH_EXPECTED_MIGRATION_HISTORY_FINGERPRINT"
	// EnvDispatchNotAfter is the absolute last instant at which an Apply Pod may
	// dispatch its mutating child, even if an orphaned Pod was scheduled late.
	EnvDispatchNotAfter = "PTAH_DISPATCH_NOT_AFTER"
	// EnvExecutionNotAfter is the absolute deadline enforced on the mutating
	// child process after dispatch.
	EnvExecutionNotAfter = "PTAH_EXECUTION_NOT_AFTER"
	// EnvTerminationGracePeriod is the Pod's terminationGracePeriodSeconds, in
	// whole seconds. The builder writes the same value into the Pod spec and
	// here, and the runner derives from it how long a child it stopped may take
	// (ChildStopDelay).
	EnvTerminationGracePeriod = "PTAH_TERMINATION_GRACE_PERIOD_SECONDS"
	// EnvDatabaseURL carries the target database credential to the child only.
	EnvDatabaseURL = "PTAH_DB_URL"
	// EnvDevelopmentDatabaseURL carries an optional development database credential.
	EnvDevelopmentDatabaseURL = "PTAH_DEV_URL"
	// EnvOCIPassword carries a registry password to the child only.
	EnvOCIPassword = "PTAH_OCI_PASSWORD"
	// EnvOCIToken carries a registry identity token to the child only.
	EnvOCIToken = "PTAH_OCI_TOKEN"
	// EnvSchemaFile supplies the desired schema to drift and plan operations.
	EnvSchemaFile = "PTAH_SCHEMA_FILE"
	// EnvExpectedDatabaseEngine selects the supported fingerprint-probe dialect
	// without deriving it from a credential-bearing database URL.
	EnvExpectedDatabaseEngine = "PTAH_EXPECTED_DATABASE_ENGINE"
	// EnvMigrationsDir is the already-materialized migration directory a
	// migration operation reads.
	//
	// It is a local path rather than an OCI reference on purpose. Ptah accepts
	// `--migrations-dir oci://...` and fetches the artifact itself, which would
	// put the registry credentials in the same process as the database ones. A
	// fetch container holds the registry credentials and writes what it fetched
	// into a shared volume; the process that runs SQL reads that volume and
	// never reaches a registry.
	EnvMigrationsDir = "PTAH_MIGRATIONS_DIR"

	// EnvTransactionMode is the mode the resource asked Ptah to wrap the run
	// in. Empty means the resource asked for nothing and the flag is left off,
	// so Ptah chooses.
	EnvTransactionMode = "PTAH_TRANSACTION_MODE"

	// EnvPlanSealPublicKey is the manager's ephemeral public key a Plan Job
	// seals its plan payload to, base64-encoded (see internal/planseal). Only
	// a Plan operation reads it; the runner refuses before starting its
	// executor if it is missing or malformed.
	EnvPlanSealPublicKey = "PTAH_PLAN_SEAL_PUBLIC_KEY"
	// EnvSealedPlanJobName is this Job's deterministic name, known before the
	// Job exists because it is computed from the claim rather than assigned
	// by the API server. The runner binds it into the sealed plan payload
	// alongside the operation ID, so a payload sealed for one Job cannot be
	// substituted for another's at harvest, even a retried attempt of the
	// same operation under a fresh name.
	EnvSealedPlanJobName = "PTAH_SEALED_PLAN_JOB_NAME"
)
View Source
const (

	// EnvOCIAuthMode records whether the Job projects an Environment or
	// DockerConfigJSON registry credential. It is runner-only policy input.
	EnvOCIAuthMode = "PTAH_OPERATOR_OCI_AUTH_MODE"
	// EnvOCIAuthRegistryGrant carries the fixed registry key selected from the
	// credential Secret in either supported mode. It is never passed to Ptah.
	EnvOCIAuthRegistryGrant = "PTAH_OPERATOR_OCI_AUTH_REGISTRY_GRANT"
	// EnvOCIAllowPlainHTTPGrant carries the credential owner's explicit
	// cleartext-transport grant. The only accepted value is exactly "true".
	EnvOCIAllowPlainHTTPGrant = "PTAH_OPERATOR_OCI_ALLOW_PLAIN_HTTP"
	// EnvOCIHasCA binds custom trust configuration to the same validation used
	// by runner operations and the pre-fetch guard.
	EnvOCIHasCA = "PTAH_OPERATOR_OCI_HAS_CA"
	// EnvOCICASourceFile is the runner-only path to the mutable ConfigMap
	// projection. Ptah receives only a verified immutable snapshot path.
	EnvOCICASourceFile = "PTAH_OPERATOR_OCI_CA_SOURCE_FILE"
	// EnvOCICASHA256Grant carries the fixed caSHA256 key from the same Secret
	// that owns registry credentials. It is never passed to Ptah.
	EnvOCICASHA256Grant = "PTAH_OPERATOR_OCI_CA_SHA256_GRANT"
)
View Source
const (
	// ProtocolVersion is what binds the runner into a plan and its approval.
	// The runner image is built from the operator's own source and ships with
	// every manager release, so its digest is recorded and not bound: a patch
	// release of the operator keeps every pending approval. This number is
	// what stands for the runner instead, and it must change whenever the
	// runner's side of the contract does -- the arguments and environment it
	// accepts, any check it enforces inside the Pod before or around the
	// executor, and the result frame it returns. A change to runner
	// enforcement that keeps this number lets an approval granted under the
	// old checks run under the new ones.
	//
	// hack/verifyrunnerprotocol, under make verify-source, holds this number
	// to the source the runner is built from: it refuses a source change that
	// keeps the number, unless support/runner-protocol.json declares why the
	// contract stayed the same. Every Job names this number in
	// EnvRunnerProtocolVersion, and a runner of another protocol refuses it.
	//
	// Version 1 is the protocol the first tagged release speaks, the Plan
	// payload seal included: a Plan Job refuses to start its executor without
	// a well-formed manager public key (EnvPlanSealPublicKey), and
	// Result.Stdout carries the plan sealed to it. The versions before it
	// counted commits nobody installed, and were reset to 1 ahead of that tag.
	ProtocolVersion = 1

	// JSON escaping can expand a bounded plan payload. This shared cap includes
	// the worst-case expansion plus fixed result-envelope headroom.
	DefaultMaxFrameBytes int64 = plancontract.MaxResultPayloadBytes
)
View Source
const (

	// TerminationMessagePath is where the runner writes its summary. It is the
	// path Kubernetes uses when a container names none; the workload builders
	// name it anyway, so the runner and the Pod spec cannot disagree about it.
	TerminationMessagePath = "/dev/termination-log"

	// MaxSummaryBytes bounds the summary line, marker included.
	//
	// The kubelet keeps at most 4 KiB of a termination message and 12 KiB for
	// the whole Pod, divided evenly among its containers. An operation Pod has
	// up to four -- the runner installer, the source guard, the fetch, and the
	// executor -- so the executor's share can be 3 KiB. The runtime may put its
	// own message in front, and a summary cut short is refused rather than
	// read, so the bound leaves a kilobyte of that share unused.
	MaxSummaryBytes = 2 << 10
)

The termination summary is a second, much smaller copy of what a result frame says, written where the kubelet keeps it after the container's log is gone.

A frame exists only in the container log on the node. Container garbage collection, node loss, or a log that never received the frame's last bytes leave the controller with an Apply it cannot account for. The kubelet copies a container's termination message into Pod status when the container exits, which the controller already reads, and which needs no credential in the Pod.

It carries only what a decision needs and nothing a frame is careful about: no plan, no native output, no error message, no SQL. It is bound to the frame it summarizes by that frame's SHA-256, so a log that holds a different frame is caught, and it says nothing a frame would not.

View Source
const CodeRunnerProtocolMismatch = "runner_protocol_mismatch"

CodeRunnerProtocolMismatch is the error code of that refusal. It is the one code a manager reads from a runner of any protocol version: see ProtocolMismatchError.

View Source
const DefaultMaxPlanBytes int64 = plancontract.MaxExecutableBytes
View Source
const (
	DefaultMaxResultBytes int64 = plancontract.MaxExecutableBytes
)
View Source
const DefaultTerminationGracePeriod = 30 * time.Second

DefaultTerminationGracePeriod is how long an operation Pod is given between SIGTERM and SIGKILL, unless a claim recorded a grace of its own.

It is one number with three readers. The workload builders write it into every operation Pod's terminationGracePeriodSeconds, the schema controller records it on an Apply claim and dates the end of that Apply's execution horizon by it, and the runner derives from it how long a child it asked to stop may take. A mutating Pod is also told its grace through EnvTerminationGracePeriod, so the runner never has to assume that the value a claim recorded is this one.

View Source
const EnvRunnerProtocolVersion = "PTAH_RUNNER_PROTOCOL_VERSION"

EnvRunnerProtocolVersion is the runner protocol the manager that built the Job speaks. The builder writes runner.ProtocolVersion into every runner container, the one that installs nothing: the guard that authorizes OCI access and the one that starts the executor.

The runner is installed from execution.runnerImage, which the chart takes from whoever installs, and nothing else ties that image to the manager. A runner that speaks another protocol enforces another contract, and a plan and its approval bind the protocol, not the image. So the runner compares the two before it does anything else, and refuses a Job that names another protocol, or none, before the executor starts.

View Source
const MaxResultLogBytes = DefaultMaxFrameBytes +
	2*maxInterleavedFrameBytes +
	int64(len(frameHeader)+len(frameFooter)) + maxFrameHeaderFieldBytes

MaxResultLogBytes is the shortest tail of an executor log that still holds every frame a reader of the whole log could have found in it.

A frame is a header line, one payload line and a footer. The parser tolerates maxInterleavedFrameBytes of other output between the header and the payload, and the same again between the payload and the end of the log -- past that it stops looking and says so. So a findable frame begins no further from the end of the log than its own largest size plus twice that tolerance, and a reader that keeps this much of the tail refuses exactly what a reader of the whole log refuses.

It is a floor as much as a bound: keeping less would turn a result the executor really wrote into one nobody can read, which is worse than the cost of keeping it.

View Source
const MaxTerminationGracePeriod = 300 * time.Second

MaxTerminationGracePeriod is the longest grace a claim may record, which is the bound the API puts on the field that records it.

View Source
const RedactionMarker = "[REDACTED]"

Variables

View Source
var (
	ErrFrameNotFound  = errors.New("ptah runner result frame not found")
	ErrMalformedFrame = errors.New("malformed ptah runner result frame")
	ErrFrameTooLarge  = errors.New("ptah runner result frame exceeds the configured limit")
	// ErrIncompleteFrame marks a frame the log ends inside. Every rejection
	// wrapping it is also ErrMalformedFrame, and its message is unchanged; what
	// it adds is that the bytes may simply not have arrived yet (#154).
	ErrIncompleteFrame = errors.New("ptah runner result frame has not finished arriving")
)
View Source
var ErrRunnerProtocolMismatch = errors.New("the runner speaks another protocol than the Job expects")

ErrRunnerProtocolMismatch reports a runner that refused a Job because the Job expected another runner protocol.

View Source
var ErrSummaryNotFound = errors.New("the termination message carries no runner summary")

ErrSummaryNotFound reports a termination message that carries no runner summary at all: a container that did not write one, or a runtime message alone. It is absence, not a refusal.

Functions

func CheckProtocolBinding

func CheckProtocolBinding(environment []string) error

CheckProtocolBinding refuses an environment that does not name this runner's protocol version.

func ChildStopDelay

func ChildStopDelay(grace time.Duration) time.Duration

ChildStopDelay is how long a child may take to stop after the runner sent it SIGTERM, for a Pod given grace between SIGTERM and SIGKILL.

The runner is PID 1 in its container, so the kubelet's SIGTERM reaches the runner and not the child. The runner passes it on and waits this long; a child still running then is killed. What is left of the grace after that is the runner's own: decoding what the child wrote, writing the termination summary, and writing the result frame. A third of the grace is kept for that, which is ten seconds of the default and far more than a frame takes.

The same delay applies when the child's own execution deadline passes, and it is why that is safe: the schema controller does not read the database before executionNotAfter plus the recorded grace, and a child that has to be dead by executionNotAfter plus two thirds of that grace is dead before then.

func EncodeSummary

func EncodeSummary(result Result) ([]byte, error)

EncodeSummary returns the bounded termination summary of the canonical JSON payload, without constructing or emitting a diagnostic log frame. FrameDigest retains its wire name and hashes the same payload as durable delivery. This is execution evidence only: it does not claim the receiver persisted the result.

func MarshalFrame

func MarshalFrame(result Result) ([]byte, error)

MarshalFrame encodes a length- and digest-bound frame. The byte length and SHA-256 cover exactly the JSON payload bytes between the header and footer.

func MayStillArrive

func MayStillArrive(err error) bool

MayStillArrive reports whether a parse failure could be the log being read before the runner's output reached it, rather than output that is wrong.

The runner writes its frame in one write as its last output, but the container runtime copies that output into the log asynchronously, and a terminated container does not promise the copy has finished. A read in that window ends inside the frame or before it. Every other rejection describes bytes that are present and wrong, and reading them again changes nothing.

func PrepareOCISourceAccess

func PrepareOCISourceAccess(reference string, environment []string, tempDir string) ([]string, func(), error)

PrepareOCISourceAccess validates registry authority and custom trust bytes, then replaces a mutable CA projection with a private per-operation snapshot. The returned cleanup must be called when validation succeeds.

func SnapshotOCISourceAccess

func SnapshotOCISourceAccess(reference string, environment []string, destination string) error

SnapshotOCISourceAccess validates registry authority and custom trust bytes, then copies the exact validated CA bytes to an exclusive destination. It is used by the credential-free Observe/Plan init guard before any network child.

func TargetIdentityDigest

func TargetIdentityDigest(rawDatabaseURL string) (string, error)

TargetIdentityDigest hashes a canonical credential-free route identity used to reject target redirects between observation and Apply. Cross-resource mutation serialization uses the separately declared coordination realm.

func ValidateOCISourceAccess

func ValidateOCISourceAccess(reference string, environment []string) error

ValidateOCISourceAccess validates every Secret-owned registry capability for a source without a custom CA. CA callers must use PrepareOCISourceAccess or SnapshotOCISourceAccess so validation and use stay bound to the same bytes.

func ValidateResultFor

func ValidateResultFor(result Result, operation Operation, operationID string) error

ValidateResultFor applies the result contract to an already decoded document. It requires an explicit operation identity and performs no log parsing or serialization. Transport authentication and plan-byte decoding are separate checks the caller must perform.

func WriteFrame

func WriteFrame(w io.Writer, result Result) error

func WriteTerminationSummary

func WriteTerminationSummary(path string, summary []byte) error

WriteTerminationSummary writes a summary to the termination message file.

The file is opened, never created. The kubelet mounts it into every container, so a path that does not exist is a process running outside a Pod, and writing a new file there would be writing somewhere nobody reads.

Types

type CommandSpec

type CommandSpec struct {
	Path string
	Args []string
	Env  []string
}

func BuildCommand

func BuildCommand(ptahBinary string, operation Operation, inputs Inputs) (CommandSpec, error)

BuildCommand constructs only fixed commands. It never uses a shell.

type Config

type Config struct {
	// DurableResult returns plaintext Plan bytes for authenticated TLS delivery.
	// The caller must validate delivery configuration before Run and must never
	// write this result to diagnostic logs, including when delivery fails.
	DurableResult  bool
	Operation      Operation
	PtahBinary     string
	MaxResultBytes int64
	MaxPlanBytes   int64
	Environment    []string
	Diagnostics    io.Writer
	Executor       Executor
	TempDir        string
	Clock          func() time.Time
}

type DriftFindingSummary

type DriftFindingSummary struct {
	Category string `json:"category"`
	Count    int32  `json:"count"`
	Severity string `json:"severity"`
}

DriftFindingSummary is the only per-category drift detail permitted across the runner boundary. Category names are a fixed machine vocabulary; raw object names, SQL, schema literals, and diff payloads are never included.

ObservedDrift is the report's own verdict and does not imply a summary: a difference the report has no category for, such as a grant, is drift with no summaries, a zero count and a safe highest severity.

type EncodedResult

type EncodedResult struct {
	Frame []byte
	// Summary is nil when the result cannot be summarized, and SummaryErr says
	// why. The frame never depends on it: the summary is a copy of part of the
	// frame, and losing the copy must never cost the original.
	Summary    []byte
	SummaryErr error
}

EncodedResult is a result frame and the termination summary bound to it.

func EncodeResult

func EncodeResult(result Result) (EncodedResult, error)

EncodeResult encodes the result frame and the termination summary bound to it.

Both come from the one result, and the summary names the digest of the frame returned beside it, so the two cannot describe different runs. A result that cannot be framed is an error, as it is for MarshalFrame. Every result the runner frames can be summarized: each rule a summary is held to restates one its frame already met, and every field it carries is bounded, which TestTheLargestSummaryFitsItsBound measures against MaxSummaryBytes.

type Executor

type Executor interface {
	Execute(ctx context.Context, spec CommandSpec, stdout, stderr io.Writer) (int, error)
}

type Inputs

type Inputs struct {
	OperationID                string
	RequestedReference         string
	ResolvedReference          string
	VerificationPolicyPath     string
	ExpectedArtifactType       string
	PlanDir                    string
	ExpectedPlanContentDigest  string
	ExpectedTargetDigest       string
	CoordinationDigest         string
	ExpectedCoordinationDigest string
	ExpectedSequence           string
	ExpectedSequenceDigest     string
	ExpectedHistoryFingerprint string
	DispatchNotAfter           string
	ExecutionNotAfter          string
	ExpectedDatabaseEngine     string
	PlanPath                   string
	MigrationsDir              string
	TransactionMode            string
	// PlanSealPublicKey is the base64-encoded manager public key a Plan
	// operation seals its plan payload to before writing the frame.
	PlanSealPublicKey string
	// SealedPlanJobName is this Plan Job's deterministic name, bound inside
	// the sealed plan payload alongside the operation ID.
	SealedPlanJobName string
	// ExpectedSequencePath is the file the runner wrote the approved sequence
	// to for `migrations up --expect-sequence`. The runner sets it; nothing
	// reads it from the environment.
	ExpectedSequencePath string
	// PlanOutputPath is where `schema plan --output` saves the plan it
	// computes. The runner sets it to a file in a directory of its own, and
	// nothing reads it from the environment.
	PlanOutputPath string
}

Inputs are the runner-specific environment values used to construct one of the fixed Ptah commands. Normal Ptah environment variables remain in Env.

func InputsFromEnvironment

func InputsFromEnvironment(environment []string) Inputs

type MigrationSummary

type MigrationSummary struct {
	Outcome      string `json:"outcome"`
	AppliedCount int    `json:"appliedCount"`
	FirstApplied int64  `json:"firstApplied,omitempty"`
	LastApplied  int64  `json:"lastApplied,omitempty"`
}

MigrationSummary is what a migration Apply's report said, reduced to what fits: the outcome, and the applied versions as a count and the first and last of them in the order Ptah applied them.

type OSExecutor

type OSExecutor struct {
	StopDelay time.Duration
}

OSExecutor runs a child process and stops it the way the kubelet stops a container: SIGTERM first, and SIGKILL only if the child is still running StopDelay later.

Ptah cancels its own work on the first SIGTERM and writes what it did before it exits, so a migration stopped between two files can say which files it applied. SIGKILL, which is what exec.CommandContext sends by default, ends the child where it stands and leaves nothing to read. A zero StopDelay keeps that default, because a SIGTERM with no bound on what follows would let a child that ignores it outlive every deadline the runner enforces.

func (OSExecutor) Execute

func (e OSExecutor) Execute(ctx context.Context, spec CommandSpec, stdout, stderr io.Writer) (int, error)

type Operation

type Operation string

Operation is one of the fixed operations understood by the runner.

const (
	OperationResolve Operation = "resolve"
	OperationVerify  Operation = "verify"
	OperationObserve Operation = "observe"
	OperationPlan    Operation = "plan"
	OperationApply   Operation = "apply"
	// OperationMigrationHistory reads the database's own migration history
	// against a migration artifact, and changes nothing.
	OperationMigrationHistory Operation = "migration-history"
	// OperationMigrationApply runs the pending migrations of a migration
	// artifact.
	OperationMigrationApply Operation = "migration-apply"
)

func (Operation) Mutating

func (o Operation) Mutating() bool

Mutating reports whether an operation may change the database.

A runner that predates an operation refuses it by name, which is what keeps an old executor from being asked to run migrations it cannot account for.

func (Operation) Valid

func (o Operation) Valid() bool

type ParseOptions

type ParseOptions struct {
	MaxFrameBytes       int64
	ExpectedOperation   Operation
	ExpectedOperationID string
}

ParseOptions optionally binds a parsed frame to the Job contract that created it. A frame is always held to ProtocolVersion.

type PlanOutcome

type PlanOutcome string

PlanOutcome distinguishes an executable immutable plan from an exact read-only proof that the managed scope has no changes. It is explicit so an empty or truncated plan payload can never be mistaken for convergence.

const (
	PlanOutcomeChanges   PlanOutcome = "Changes"
	PlanOutcomeNoChanges PlanOutcome = "NoChanges"
)

func (PlanOutcome) Valid

func (o PlanOutcome) Valid() bool

type ProtocolMismatchError

type ProtocolMismatchError struct {
	// RunnerVersion is the protocol the refusing runner speaks.
	RunnerVersion int
	// Message is the runner's own account of the refusal.
	Message string
}

ProtocolMismatchError is the refusal a runner of another protocol version framed. A frame is held to the reader's own ProtocolVersion, so this is the one document read across versions, and it is read only in one exact shape:

{"protocolVersion":N,"operation":...,"operationId":...,"childExitCode":-1,
 "stdout":"","error":{"code":"runner_protocol_mismatch","message":...}}

with no other key. That shape says the runner stopped before it started anything; a frame from another version that says more is not read at all, because what it says is written in a contract this reader does not hold. Every protocol version has to keep writing the refusal in exactly this shape, which TestProtocolRefusalDocumentIsPinned holds.

func (*ProtocolMismatchError) Error

func (e *ProtocolMismatchError) Error() string

func (*ProtocolMismatchError) Unwrap

func (e *ProtocolMismatchError) Unwrap() error

type Redactor

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

func NewRedactor

func NewRedactor(environment []string) Redactor

func (Redactor) Redact

func (r Redactor) Redact(value string) string

func (Redactor) RedactCaptured

func (r Redactor) RedactCaptured(value string, truncated bool) string

RedactCaptured also removes a trailing prefix of a protected value when a bounded capture ended in the middle of that value.

type Result

type Result struct {
	ProtocolVersion int       `json:"protocolVersion"`
	Operation       Operation `json:"operation"`
	OperationID     string    `json:"operationId"`
	// ChildExitCode is -1 when the runner refused the operation before child dispatch.
	ChildExitCode            int                   `json:"childExitCode"`
	Stdout                   string                `json:"stdout"`
	CoordinationDigest       string                `json:"coordinationDigest,omitempty"`
	TargetIdentityDigest     string                `json:"targetIdentityDigest,omitempty"`
	VerificationPolicyDigest string                `json:"verificationPolicyDigest,omitempty"`
	DriftReportDigest        string                `json:"driftReportDigest,omitempty"`
	ObservedDialect          string                `json:"observedDialect,omitempty"`
	ObservedDrift            bool                  `json:"observedDrift,omitempty"`
	HighestDriftSeverity     string                `json:"highestDriftSeverity,omitempty"`
	DriftFindingCount        int32                 `json:"driftFindingCount,omitempty"`
	DriftFindings            []DriftFindingSummary `json:"driftFindings,omitempty"`
	ObservedArtifactType     string                `json:"observedArtifactType,omitempty"`
	ResolvedDigest           string                `json:"resolvedDigest,omitempty"`
	ResolvedReference        string                `json:"resolvedReference,omitempty"`
	ResolvedMediaType        string                `json:"resolvedMediaType,omitempty"`
	ResolvedSize             int64                 `json:"resolvedSize,omitempty"`
	VerificationRequirements []string              `json:"verificationRequirements,omitempty"`
	PlanContentDigest        string                `json:"planContentDigest,omitempty"`
	PlanOutcome              PlanOutcome           `json:"planOutcome,omitempty"`
	MutationStarted          bool                  `json:"mutationStarted,omitempty"`
	Uncertain                bool                  `json:"uncertain,omitempty"`
	// MigrationHistory is the history a migration-history operation read, and
	// MigrationRun the evidence a migration-apply operation left. Both are the
	// documents Ptah produced, validated before they were carried here: the
	// controller decides from the database's own account rather than from this
	// process's exit status.
	MigrationHistory *dataplane.MigrationStatusReport `json:"migrationHistory,omitempty"`
	MigrationRun     *dataplane.MigrationRunReport    `json:"migrationRun,omitempty"`
	Error            *ResultError                     `json:"error,omitempty"`
	Truncation       *TruncationMetadata              `json:"truncation,omitempty"`
}

Result is the complete credential-free result emitted by ptah-runner.

func ParseResult

func ParseResult(logs []byte) (Result, error)

func ParseResultFor

func ParseResultFor(logs []byte, expectedOperation Operation, expectedOperationID string) (Result, error)

ParseResultFor extracts a frame and verifies its operation binding.

func ParseResultWithLimit

func ParseResultWithLimit(logs []byte, maxFrameBytes int64) (Result, error)

func ParseResultWithOptions

func ParseResultWithOptions(logs []byte, options ParseOptions) (Result, error)

ParseResultWithOptions scans mixed Pod logs for complete valid frames. It ignores marker-like diagnostic text and returns the last valid frame.

When no frame survives, the error says why the last candidate was rejected. The rejections are different failures with different answers -- a log read before the frame finished arriving, a build that wrote a frame this one will not accept, a payload that does not match its own digest -- and reporting all of them as one sentence leaves the reader to guess which happened. The reasons name structure and never payload text, so a frame carrying a credential cannot disclose it here.

func Run

func Run(ctx context.Context, config Config) Result

Run executes one fixed operation and always returns a frameable result. Child failures are represented in Result rather than returned as Go errors.

type ResultError

type ResultError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

ResultError describes an operation-level failure without relying on Job process exit semantics. Message is always sanitized before framing.

type Summary

type Summary struct {
	ProtocolVersion int       `json:"protocolVersion"`
	Operation       Operation `json:"operation"`
	OperationID     string    `json:"operationId"`
	// FrameDigest is the SHA-256 of the frame payload, the digest the frame's
	// own header declares.
	FrameDigest     string `json:"frameDigest"`
	MutationStarted bool   `json:"mutationStarted,omitempty"`
	Uncertain       bool   `json:"uncertain,omitempty"`
	// ErrorCode is the frame's error code. The message is left out: it is
	// sanitized for the frame, and a summary has no need of it.
	ErrorCode            string            `json:"errorCode,omitempty"`
	CoordinationDigest   string            `json:"coordinationDigest,omitempty"`
	TargetIdentityDigest string            `json:"targetIdentityDigest,omitempty"`
	Migration            *MigrationSummary `json:"migration,omitempty"`
}

Summary is the termination summary of one result frame.

func ParseSummaryFor

func ParseSummaryFor(message string, operation Operation, operationID string) (Summary, error)

ParseSummaryFor reads the summary out of a container's termination message and binds it to the operation that claimed the Job.

The message may carry the container runtime's own text in front, which the kubelet joins to the file's content with a colon, so the summary is found by its marker rather than taken from the start. It has to run to the end of the message, be the only summary there, and account for itself exactly as a frame must; anything else is refused, because a summary cut short or edited is one that could say what the run did not.

func (Summary) StandsInFor

func (s Summary) StandsInFor(logs []byte, parseErr error) error

StandsInFor reports whether this summary may stand in for the frame the log was expected to hold, and why not when it may not.

Only a frame that is missing may be replaced: a log with no frame in it, or one that ends inside the frame. A frame that is present and was refused -- the wrong digest, the wrong operation, a payload this build does not accept -- is an answer, and a summary of it cannot be a better one. And a log whose frame headers declare a digest other than the one this summary is bound to holds a different result, so the two are not read together at all.

type TruncationMetadata

type TruncationMetadata struct {
	Stdout             bool  `json:"stdout,omitempty"`
	StdoutBytesDropped int64 `json:"stdoutBytesDropped,omitempty"`
	Stderr             bool  `json:"stderr,omitempty"`
	StderrBytesDropped int64 `json:"stderrBytesDropped,omitempty"`
}

TruncationMetadata records output that was drained but intentionally not retained. The child is never back-pressured by these limits.

Jump to

Keyboard shortcuts

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