progress

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 8 Imported by: 2 modules, 1 package

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

Documentation

Overview

Package progress defines the strategy-wide, machine-readable execution progress contract. One snapshot shape serves every operation: a concurrent index build's counters are read from the server's progress view, the copy-and-swap row copy's and checksum pass's counters come from the engine's own WorkSource, and each operation leaves the others' counters at zero.

Index

Constants

View Source
const FormatVersion = 6

FormatVersion identifies the snapshot contract. A consumer must reject a snapshot whose format_version it does not recognize rather than guess at field semantics. Adding a phase or operation value is a contract change and bumps this version, even when no field is added or renamed. Adding a field also bumps this version so strict consumers can detect the new shape.

Variables

View Source
var (
	// ErrNoActiveBuild is returned by CancelBuild when the tracker has no
	// concurrent index build in flight.
	ErrNoActiveBuild = errors.New("no concurrent index build is active")
	// ErrBuildNotRunning is returned by CancelBuild when the tracker has a
	// build but the server positively shows no statement running on its
	// backend: the build statement has not reached the server yet, or the
	// backend has already gone. PostgreSQL drops a cancel signal delivered
	// to an idle backend, so signalling now would silently do nothing; the
	// caller retries, or waits for the blocking executor call to return.
	ErrBuildNotRunning = errors.New("the concurrent index build's statement is not running on the server")
	// ErrBuildUnobservable is returned by CancelBuild when the server does
	// not expose the build backend's state — activity tracking is off, or
	// the backend is hidden from the tracker's role — so the tracker cannot
	// tell a running build from an idle backend. A signal sent blind could
	// be dropped on an idle backend while the caller reads nil as a cancel
	// that reached the build, so none is sent. The build is still
	// stoppable: an operator whose role can see the backend cancels it
	// directly, or the caller ends the context the build runs under.
	ErrBuildUnobservable = errors.New("the server does not expose the concurrent index build backend's state")
	// ErrCancelNotDispatched is returned by CancelBuild when the caller's
	// context ended before the cancel signal was sent — while CancelBuild
	// waited for an in-flight progress poll or another cancel to release
	// the reserved session, or in the instant it took the session. It is
	// returned wrapped together with the caller's context error, so
	// errors.Is matches both; test for this sentinel before testing for
	// the context error. A context error without it came back after the
	// signal was sent, and the signal may have reached the build. The
	// other sentinels CancelBuild returns also mean nothing was delivered;
	// see CancelBuild for the full outcome table.
	ErrCancelNotDispatched = errors.New("the cancel signal was not sent")
	// ErrProgressNotRead is returned by Progress when the caller's context
	// ended before the read was issued — while it waited for another poll
	// or a handoff fence to release the poll gate, or in the instant it took
	// the gate. It is returned wrapped together with the caller's context
	// error, so errors.Is matches both; test for this sentinel before
	// testing for the context error. A context error without it came from
	// the read itself: a concurrent build's read runs detached from the
	// caller's context, so its deadline error means the reserved verdict
	// session stopped answering, not that the caller timed out.
	ErrProgressNotRead = errors.New("the progress read was not issued")
)

Functions

This section is empty.

Types

type Clock

type Clock interface {
	Now() time.Time
}

Clock supplies time to progress state so core executors remain deterministic.

type Detail

type Detail struct {
	Operation Operation `json:"operation,omitempty"`
	// Statement is the canonical, qualified SQL the executor is running for
	// the current step, never a rendered or prettified form. Terminal snapshots
	// retain it so observers can identify the statement that produced the outcome.
	Statement        string `json:"statement,omitempty"`
	ServerPhase      string `json:"server_phase,omitempty"`
	Active           bool   `json:"active"`
	Attempt          int    `json:"attempt,omitempty"`
	Work             *Work  `json:"work,omitempty"`
	CurrentLockerPID uint32 `json:"current_locker_pid,omitempty"`
}

Detail describes the operation currently executing.

type Operation

type Operation string

Operation is the current operation's execution class.

const (
	// OperationAdmitting is the pre-execution window in which a sequence's
	// steps are still being validated; no statement has run yet.
	OperationAdmitting Operation = "admitting"
	// OperationOptimistic is one bounded direct native attempt.
	OperationOptimistic Operation = "optimistic"
	// OperationBrief is a brief transactional sequence step.
	OperationBrief Operation = "brief"
	// OperationValidate is a constraint-validation scan.
	OperationValidate Operation = "validate-constraint"
	// OperationConcurrentIndex is a concurrent index build.
	OperationConcurrentIndex Operation = "concurrent-index-build"
	// OperationCopy is the copy-and-swap row copy from the source table into
	// its shadow.
	OperationCopy Operation = "copy"
	// OperationChecksum is the copy-and-swap checksum pass comparing the
	// source table with its shadow chunk by chunk, and repairing differing
	// chunks when its policy says so.
	OperationChecksum Operation = "checksum"
	// OperationCatchUp is the copy-and-swap catch-up applying the changes
	// decoded from the source table's WAL to its shadow.
	OperationCatchUp Operation = "catch-up"
)

type Phase

type Phase string

Phase is the overall execution phase.

const (
	// PhasePending means execution has not started.
	PhasePending Phase = "pending"
	// PhaseRunning means execution is active.
	PhaseRunning Phase = "running"
	// PhaseFinished means execution completed successfully.
	PhaseFinished Phase = "finished"
	// PhaseFailed means execution reached a terminal failure.
	PhaseFailed Phase = "failed"
)

type Snapshot

type Snapshot struct {
	FormatVersion int           `json:"format_version"`
	Phase         Phase         `json:"phase"`
	Step          int           `json:"step,omitempty"`
	TotalSteps    int           `json:"total_steps,omitempty"`
	Elapsed       time.Duration `json:"elapsed_ns"`
	StepElapsed   time.Duration `json:"step_elapsed_ns"`
	Detail        Detail        `json:"detail"`
}

Snapshot is one immutable progress observation. For a terminal phase the elapsed values are frozen at the instant Finish recorded, so a late poll reports the execution's duration, not the observation's age.

type Tracker

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

Tracker is a concurrency-safe progress source. The caller owns it; it has no goroutines. Progress performs the one read needed for an active index build, or the one WorkSource call for an engine-measured step. A WorkSource call lives as long as the caller's context; an index build's read is bounded on its own, so a caller's context ending never reaches the reserved session.

Two guards split the tracker's concerns: mu guards the state fields and is held only for memory access, so the executor's own updates never wait for a database read; the poll gate serializes observers, so the reserved session — a single pgx connection that is not safe for concurrent use — only ever carries one progress query at a time, and a WorkSource sees one poll at a time. The gate is a one-slot channel rather than a mutex so that Progress and CancelBuild, the takers with a caller waiting on an answer, can stop waiting when that caller's context ends.

Four state changes take the poll gate, because each ends a poll target's ownership of the step's work and must not do so under a poll still in flight: StopConcurrentBuild and SetWorkSource release the build's session, which the executor calls before that session can return to the pool, so an observation or cancel signal in flight completes against a backend the build still owns; StopWorkSource and SetConcurrentBuild release the source, which the engine calls before the state the source reads goes away. Each takes the gate before mu, the one order every taker uses. Start, StartStep and Finish also clear those fields, but as resets under mu alone — by the time they run the step has already passed through its fence, and a reset that waited behind an observation would make polling a gate on execution.

A Tracker comes from NewTracker, which creates the gate; the zero value has no gate and must not be used.

func NewTracker

func NewTracker(clock Clock) (*Tracker, error)

NewTracker constructs an idle tracker using clock.

func (*Tracker) CancelBuild added in v0.3.0

func (t *Tracker) CancelBuild(ctx context.Context) error

CancelBuild asks PostgreSQL to cancel the active concurrent build's statement, from the tracker's reserved session. The tracker is the only party that knows whether the build is still live, so the cancel is issued here rather than by handing out the backend PID: it serializes against StopConcurrentBuild, which the executor calls before the build's session can return to the pool, so the PID it signals still belongs to the build — never to an unrelated statement that reused the same pooled backend. A step whose work a WorkSource owns has no build to signal and reports ErrNoActiveBuild; the snapshot's operation tells a caller which case it is in. The signal is sent only to a backend the server reports active in the same statement as the read, which rules out the common way a cancel is lost — a signal landing on an idle backend — without making the signal itself observable.

A nil return means pg_cancel_backend accepted the signal for a backend the same statement had just read as active. It does not mean the build has stopped, and it cannot rule out the build finishing in the instant between that read and the signal, in which case the signal lands on an idle backend and is dropped: the server acts on a cancel at its next interrupt check, and the build returns through the executor's normal path — failed with its catalog verdict, or finished — either way on the blocking executor call, not here. The caller's ctx gates whether the signal is attempted; the signal itself runs bounded and detached from it, because the session it rides on is the one the build's verdict needs intact.

CancelBuild waits for an in-flight progress poll or another cancel to release the reserved session, for as long as the caller's ctx lasts. A caller whose ctx ends first — during that wait, or by the time the session is held — gets ErrCancelNotDispatched wrapped with its context error, and no signal was sent. The outcomes sort into four classes:

  • nil: the signal was sent and accepted.
  • ErrCancelNotDispatched, with the context error: nothing was sent; the caller may retry.
  • ErrNoActiveBuild, ErrBuildNotRunning, ErrBuildUnobservable: nothing was delivered to the build, for the reason each sentinel names.
  • any other error, a context error without ErrCancelNotDispatched included: it came back after the signal query was issued, and the signal may have reached the build.

Because the second class matches both the sentinel and the context error, a caller tests for ErrCancelNotDispatched before it tests for a context error; the other order reads "nothing sent" as "may have been sent".

The reserved session's role must be allowed to signal the build's backend: the same role, or a member of pg_signal_backend. Otherwise pg_cancel_backend raises an error rather than returning false, and that error is returned wrapped; it is a permanent condition of the role, not one a retry clears.

func (*Tracker) Finish

func (t *Tracker) Finish(err error)

Finish records a terminal execution outcome and the instant it happened; elapsed values in later snapshots freeze at that instant.

func (*Tracker) Now

func (t *Tracker) Now() time.Time

Now returns the tracker's injected time for executor duration accounting.

func (*Tracker) Progress

func (t *Tracker) Progress(ctx context.Context) (Snapshot, error)

Progress returns a snapshot and, for an active concurrent index build, queries PostgreSQL's progress view by the executor-owned backend PID; for a step with a WorkSource it asks the source for the step's counters. On a query or source error the snapshot still carries the last-known tracker state. The state lock is released before the query, so concurrent pollers serialize only against each other (and the four handoff fences), never against the executor's own state updates.

A poller waits for the poll gate for as long as its ctx lasts; one that gives up first, or whose ctx has already ended when it takes the gate, gets the last-known snapshot and ErrProgressNotRead wrapped with ctx's error, having read nothing. Once the gate is held, a concurrent build's progress read runs on the executor's reserved verdict session bounded and detached from ctx, so an observer whose context ends mid-read — an HTTP request timing out — cannot tear down the session the build's failure verdict needs. Progress is therefore not bounded by ctx once the read is issued: it returns when the server answers, which on a pkg/dbconn pool is within its statement_timeout, and within twice dbconn's default statement_timeout (one minute) at the latest. A caller that needs a hard return at its own deadline calls Progress from its own goroutine. A WorkSource is read under ctx, as its contract requires.

func (*Tracker) SetAttempt

func (t *Tracker) SetAttempt(attempt int)

SetAttempt records the current bounded retry attempt.

func (*Tracker) SetConcurrentBuild

func (t *Tracker) SetConcurrentBuild(session dbconn.RowQuerier, pid uint32)

SetConcurrentBuild enables on-demand server progress for pid. The executor supplies its reserved verdict session so polling cannot starve behind the build session even when the pool has only two connections. A step's work comes from one place, so any WorkSource the step had is dropped — after waiting, as StopWorkSource does, for a poll still reading it, so the source's owner never finds its state observed after the handoff.

func (*Tracker) SetWorkSource added in v0.4.0

func (t *Tracker) SetWorkSource(source WorkSource)

SetWorkSource makes source the current step's work for every later poll. A step's work comes from one place: setting a source drops any concurrent build the step was polling, and SetConcurrentBuild drops the source.

Like StopWorkSource, it waits for an observation or cancel signal in flight, so the build it replaces is never released while a poll still reads its session, and a source it replaces has left its last poll before the engine lets the state behind it go. The engine calls StopWorkSource before the source's state goes away.

func (*Tracker) Start

func (t *Tracker) Start(total int, operation Operation)

Start records the beginning of an execution. It resets all per-execution state, so a reused tracker never leaks a prior run's step, terminal time, or session into the new run's snapshots.

func (*Tracker) StartStep

func (t *Tracker) StartStep(step int, operation Operation, statement string)

StartStep advances a sequence to a 1-based step, records the exact SQL the executor will run, and drops any build session or work source from a prior step, so a later step can never poll a stale build or a finished source.

func (*Tracker) StopConcurrentBuild

func (t *Tracker) StopConcurrentBuild()

StopConcurrentBuild waits for an in-flight observation or cancel signal and releases the reserved session back to the executor before its catalog verdict. It is the fence that keeps CancelBuild's target honest: the executor calls it before the build's own session can return to the pool, so no signal that read the build's PID completes after that backend could be running someone else's statement.

func (*Tracker) StopWorkSource added in v0.4.0

func (t *Tracker) StopWorkSource()

StopWorkSource waits for an in-flight observation and then stops polling the source. It is the fence between the source and its owner's return: the engine calls it before the state the source reads is released, so no poll that began while the step ran completes against a source whose owner has gone.

type WallClock

type WallClock struct{}

WallClock reads the process wall clock.

func (WallClock) Now

func (WallClock) Now() time.Time

Now returns the current wall-clock time.

type Work

type Work struct {
	RowsCopied       uint64 `json:"rows_copied"`
	RowsTotal        uint64 `json:"rows_total"`
	BytesCopied      uint64 `json:"bytes_copied"`
	BytesTotal       uint64 `json:"bytes_total"`
	ChunksCompared   uint64 `json:"chunks_compared"`
	RowsHashed       uint64 `json:"rows_hashed"`
	ChunksMismatched uint64 `json:"chunks_mismatched"`
	ChunksRepaired   uint64 `json:"chunks_repaired"`
	ChunksReread     uint64 `json:"chunks_reread"`
	ChangesApplied   uint64 `json:"changes_applied"`
	ChangesBuffered  uint64 `json:"changes_buffered"`
	LagBytes         uint64 `json:"lag_bytes"`
	BlocksDone       uint64 `json:"blocks_done"`
	BlocksTotal      uint64 `json:"blocks_total"`
	TuplesDone       uint64 `json:"tuples_done"`
	TuplesTotal      uint64 `json:"tuples_total"`
	LockersTotal     uint64 `json:"lockers_total"`
	LockersDone      uint64 `json:"lockers_done"`
}

Work reports observed work. It is present only when something measured it — the server published a progress row for a concurrent build, or the engine's own WorkSource reported the step's counters — and then every counter marshals explicitly — a fresh build reports honest zeros, never an empty object a consumer must guess at. Rows and bytes belong to the copy-and-swap row copy; chunks compared, rows hashed, chunks mismatched, chunks repaired and chunks reread to the checksum pass; changes applied, changes buffered and lag bytes to the catch-up; blocks, tuples and lockers to a concurrent index build. No operation fabricates another's counters.

type WorkSource added in v0.4.0

type WorkSource interface {
	Work(ctx context.Context) (Work, error)
}

WorkSource reports engine-derived work for the current step: the counters of an operation whose progress PostgreSQL publishes no view for, such as the copy-and-swap row copy, which knows its own rows copied from the chunks it has landed, or the checksum pass, which knows the chunks it has compared and repaired. The tracker polls it inside Progress, on the observer's context, so the source must be safe to call from any goroutine while the step runs; the tracker itself never calls it from more than one goroutine at a time. Every counter the source does not measure stays zero — a source reports what it observed, never an estimate dressed as a count.

Work is on the engine's own stop path, so it has three obligations beyond returning counters:

  • Work bounds itself. SetWorkSource, SetConcurrentBuild and StopWorkSource wait for a poll in flight, and an observer may hand the tracker a context that never ends, so a Work that only returns when its caller gives up can stall the engine indefinitely. Work reads memory, or reads the catalog on a session whose statement_timeout is set, and honours ctx as well — a cancelled observer must not keep the poll alive.
  • Work takes no lock the engine holds while it calls SetWorkSource, SetConcurrentBuild or StopWorkSource. Those calls wait for Work to return; a Work that waits for the engine's lock would deadlock the step with its observer.
  • A Work that reads the catalog is a CO-9 read site: every catalog relation, function and operator is pg_catalog-qualified, and its test runs under a search_path that shadows the names it uses.

Jump to

Keyboard shortcuts

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