Documentation
¶
Overview ¶
Package checkpoint persists the one durable resume record per target — the Checkpoint — in the target database, enforcing ST-1 (one row per target, written atomically), ST-2 (an incompatible record is distinguishable from a transient read error, and neither is mistaken for the absence of a record), and ST-10 (the table evolves additively, and an older engine never alters a newer one's table). The table's shape is derived from its columns: Ensure adds what an older engine's table lacks and refuses, untouched, a table a newer engine shaped (ErrTableNewer); a read or write that reaches an older table before Ensure ran reports ErrTableBehind. The row's format is a separate question from the table's shape: a row an engine of another FormatVersion wrote surfaces from Inspect and Load as an *IncompatibleError on MismatchFormat carrying the row's Identity, which Delete takes for the explicit fresh start. The phase set grows within a format without a bump, so a row a newer engine of the same format left in a phase this one does not know surfaces the same way, on MismatchPhase.
Index ¶
- Constants
- Variables
- type Checkpoint
- type Fingerprints
- type Identity
- type IncompatibleError
- type Mismatch
- type Options
- type Phase
- type Reaped
- type SleepFunc
- type Store
- func (s *Store) Delete(ctx context.Context, lock *dbconn.TableLockSession, schema, table string, ...) error
- func (s *Store) Ensure(ctx context.Context) error
- func (s *Store) Inspect(ctx context.Context, schema, table string) (Checkpoint, error)
- func (s *Store) Load(ctx context.Context, schema, table string, want Fingerprints) (Checkpoint, error)
- func (s *Store) ReapOrphanSlots(ctx context.Context, cfg dbconn.Config) (Reaped, error)
- func (s *Store) Save(ctx context.Context, lock *dbconn.TableLockSession, cp Checkpoint) error
- func (s *Store) WithSlotLock(ctx context.Context, cfg dbconn.Config, name string, ...) (err error)
- type TableNewerError
Constants ¶
const ( // FormatVersion is the row format Save writes and Load accepts. A row // carrying another value was written by an engine whose columns mean // something else, and is incompatible whatever its fingerprints say. // In this format a run that has built its shadow carries the shadow's // proof in the row, and the model fingerprints digest the table's // storage parameters and its columns' sequence declarations. What the fingerprints digest is part of the // format: a row whose fingerprints were computed another way would // otherwise surface as a fingerprint mismatch, blaming the run, rather // than as a row an older engine wrote. FormatVersion int32 = 3 // SchemaName is the engine-owned schema the checkpoint table lives in. // It is the engine's, not the target's, so one table holds every // target's row (D3) and no target schema is written to. It is the same // schema the shape check treats as the engine's own. SchemaName = preflight.EngineSchema // TableName is the checkpoint table. TableName = "pgsprite_checkpoint" // DefaultLoadAttempts bounds how many times Load reads through a // transient error before it gives up. DefaultLoadAttempts = 5 // DefaultLoadBackoff is the first wait between Load's attempts; later // waits grow linearly. DefaultLoadBackoff = 200 * time.Millisecond )
Variables ¶
var ErrForeignObject = errors.New("checkpoint: engine object exists but is not the engine's")
ErrForeignObject reports that the engine schema or the checkpoint table exists but is not the engine's: another role owns it, or the name is taken by a relation that is not a plain table. Ensure refuses rather than adopt it, because whatever hangs off a foreign object — a trigger, a view — would run with the engine's privileges on every Save.
var ErrInvalidCheckpoint = errors.New("checkpoint: invalid checkpoint")
ErrInvalidCheckpoint reports a Checkpoint the store refuses to persist: a missing identifier, an empty fingerprint, an unknown phase, or a shadow proof that is not a JSON object the jsonb column can hold.
var ErrInvalidOptions = errors.New("checkpoint: invalid options")
ErrInvalidOptions reports Options the store cannot run under.
var ErrInvariantViolation = errors.New("checkpoint: invariant violation")
ErrInvariantViolation reports a state the store's own invariants rule out: a row the database returned that no Save could have written.
var ErrNotFound = errors.New("checkpoint: no row for target")
ErrNotFound reports that the store holds no row for the target. It is a positive answer from the database — the read completed and found nothing — and the only Load outcome from which a caller may start fresh (ST-2).
var ErrTableBehind = errors.New("checkpoint: checkpoint table lacks a column this engine uses; Ensure has not run since the engine was upgraded")
ErrTableBehind reports that the checkpoint table lacks a column this engine reads or writes: an older engine created it and Ensure has not run since this engine was installed. The remedy is to run Ensure, which adds the column, and read again; it still carries the server's error for callers that want it.
var ErrTableMissing = errors.New("checkpoint: checkpoint table does not exist; Ensure has not run")
ErrTableMissing reports that the checkpoint table does not exist in the database: Ensure has never run there. It is distinct from ErrNotFound — a database with no table has no checkpoints to read, but that is not a positive "no row for this target" and resume must not start fresh from it — and it still carries the server's error for callers that want it.
var ErrTableNewer = errors.New("checkpoint: checkpoint table has columns this engine does not know")
ErrTableNewer reports that the checkpoint table has columns this engine does not know. Ensure refuses rather than alter it, since this engine cannot preserve the meaning of columns it has never heard of, and leaves the table as it found it. The error a caller receives is a *TableNewerError naming the columns.
Functions ¶
This section is empty.
Types ¶
type Checkpoint ¶
type Checkpoint struct {
Schema string
Table string
ShadowTable string
SlotName string
PublicationName string
// Watermark is the copier's landed frontier; its zero value means
// nothing has landed yet.
Watermark copier.Watermark
LastAppliedLSN decode.LSN
// SourceFingerprint and TargetFingerprint are the Fingerprints the row
// is keyed on.
SourceFingerprint string
TargetFingerprint string
Phase Phase
// UpdatedAt is when the record was last saved, from the store's clock.
UpdatedAt time.Time
// ShadowProof is the JSON proof of the shadow the run built, as the
// builder rendered it, so a resume after the swap — when the shadow
// no longer bears its name and the catalog cannot re-mint the proof —
// still knows which relations the swap was to move. It is empty for a
// run that has no shadow to prove. It comes back as the server renders
// JSON, not byte for byte as it was saved.
//
// Its lifecycle is the runner's, not the store's. The runner writes it
// on the first Save after the build and decodes it on resume
// (schemachange.Proof); it must be a JSON object, with no NUL character
// in any string, or Save refuses it (ErrInvalidCheckpoint). The store
// keeps it write-once: a later Save that carries no proof leaves the
// row's in place, a later Save that carries the same proof is a no-op
// on this column, and a later Save that carries a different proof is
// refused (ErrInvariantViolation) — a different shadow is a fresh
// start, which goes through Delete. Whether a row that should carry a
// proof does, and whether the proof still describes the shadow, is the
// runner's check, not the store's.
ShadowProof json.RawMessage
// Statement is the SQL text of the schema change the run is carrying
// out, as the runner was given it, so a resume can refuse a statement
// other than the one the row was written for even when the two leave
// the same fingerprints — the fingerprints describe the shape the
// change arrives at, not the operation that gets there. It is empty in
// a row an engine that did not record the statement wrote.
//
// Its lifecycle is the runner's, like ShadowProof's: the runner sets it
// on every Save and compares it on resume, and the store keeps it
// write-once — a Save without one leaves the row's in place, a Save
// with the same text is a no-op on this column, and a Save with other
// text is refused (ErrInvariantViolation), because another statement is
// a fresh start, which goes through Delete.
Statement string
}
Checkpoint is the single durable resume record.
func (Checkpoint) Fingerprints ¶ added in v0.4.0
func (c Checkpoint) Fingerprints() Fingerprints
Fingerprints returns the statement identity the checkpoint carries.
func (Checkpoint) Identity ¶ added in v0.4.0
func (c Checkpoint) Identity() Identity
Identity returns the row identity a Save of this checkpoint writes: the current FormatVersion and the checkpoint's fingerprints. A run that wants to discard its own row hands it to Delete.
type Fingerprints ¶ added in v0.4.0
type Fingerprints struct {
// Source is the digest of the source table's introspected model.
Source string
// Target is the digest of the shadow's introspected model after the
// statement ran on it: the after-schema, not the SQL text.
Target string
}
Fingerprints identifies the statement a checkpoint belongs to: the digests of the source's and the shadow's introspected models. Two runs with the same pair are the same schema change; a row carrying another pair is another statement's state (ST-2).
type Identity ¶ added in v0.4.0
type Identity struct {
FormatVersion int32
Fingerprints Fingerprints
}
Identity is everything a stored row is guarded on: the row format it was written in and the statement it belongs to. Save refuses to write over a row with another Identity, and Delete removes a row only when its Identity is the one the caller was shown.
type IncompatibleError ¶ added in v0.4.0
type IncompatibleError struct {
Schema string
Table string
Mismatch Mismatch
Have string
Want string
Stored Identity
}
IncompatibleError reports a stored row the current run must not resume from or write over: it belongs to another row format or another statement, or stands in a phase only a newer engine knows (ST-2). Mismatch names the first disagreeing field, Have is its stored value and Want the current run's; Stored is the whole identity of the row as it was read, which a caller hands back to Delete so that a fresh start removes exactly the row it was shown and no later one.
func (*IncompatibleError) Error ¶ added in v0.4.0
func (e *IncompatibleError) Error() string
Error names the target, the disagreeing field, and both values.
type Mismatch ¶ added in v0.4.0
type Mismatch uint8
Mismatch names which identity field of a stored row disagrees with the run asking for it.
const ( // MismatchFormat means the row was written in another row format: an // engine whose checkpoint columns mean something else. MismatchFormat Mismatch = iota + 1 // MismatchSource means the row was written for a source table whose // introspected model differs from the current one. MismatchSource // MismatchTarget means the row was written for a different statement: // its after-schema model differs from the current one. MismatchTarget // MismatchPhase means the row stands in a phase this engine does not // know: a newer engine of the same row format wrote it, since the phase // set only grows within a format. Have is the stored phase name and // Want the names this engine knows. MismatchPhase )
type Options ¶ added in v0.4.0
type Options struct {
// Clock stamps UpdatedAt on every Save.
Clock progress.Clock
// LoadAttempts bounds how many reads Load makes through transient
// errors (ST-2).
LoadAttempts int
// LoadBackoff is the wait after the first failed read; the n-th wait is
// n times it.
LoadBackoff time.Duration
// Sleep performs the waits between Load's attempts.
Sleep SleepFunc
}
Options bounds the store. Zero values take the defaults: the wall clock, DefaultLoadAttempts, DefaultLoadBackoff, and a sleep that waits.
type Phase ¶
type Phase uint8
Phase identifies the durable schema-change phase. Values are opaque labels: the happy path visits them in declaration order, but PhaseFailed is reachable from any phase, so callers never compare phases for order — they switch on the value or ask Terminal.
The set of phases is append-only within a row format: a new phase is added without a FormatVersion bump, since every row in a phase this engine knows still reads the same way. The one row an older engine of the same format cannot read is a row left in a phase it does not know, and Load and Inspect report that row as an IncompatibleError on MismatchPhase — written by a newer engine — carrying the row's Identity, not as a row no Save could have written. Removing or renaming a phase changes what stored rows mean and is a FormatVersion bump.
const ( // PhaseCopying copies source rows. PhaseCopying Phase = iota + 1 // PhaseCatchingUp applies captured changes. PhaseCatchingUp // PhaseReconciling recovers from slot loss (ST-4): the shadow and the // watermark are kept, the row's slot is not to be trusted, and a new // slot and a recopy pass — comparing every landed chunk and recopying // the ones that differ, without reading them again — must both // complete before change capture resumes. A resume that finds this // phase reconciles again from the top, whatever the slot looks like. PhaseReconciling // PhaseVerifying verifies convergence. PhaseVerifying // PhaseCutover performs the swap. PhaseCutover // PhaseDone is successful and terminal. PhaseDone // PhaseFailed is unsuccessful and terminal. PhaseFailed )
type Reaped ¶ added in v0.4.0
type Reaped struct {
// Dropped slots had no checkpoint row, or a terminal one, and no holder:
// orphans, dropped with their publications.
Dropped []string
// Live slots are named by a checkpoint row in a non-terminal phase: a
// schema change in flight or resumable owns each.
Live []string
// Active slots were held by a walsender or a backend when the reaper
// went to drop them; whoever holds one is the judge of it, so the
// reaper leaves it for a later pass.
Active []string
// Foreign slots wear the engine's prefix without its shape; they are
// somebody else's and are reported, never dropped.
Foreign []string
}
Reaped is what one pass of ReapOrphanSlots found among the engine slots of the store's database, every slot in exactly one list.
type SleepFunc ¶ added in v0.4.0
SleepFunc waits for d or until ctx is done, returning ctx's error in the latter case. Tests inject one that records instead of waiting.
type Store ¶ added in v0.4.0
type Store struct {
// contains filtered or unexported fields
}
Store persists one Checkpoint per target in the target database (D3). Its statements are bounded by the pool's session lock_timeout and statement_timeout, which a pkg/dbconn pool sets.
func NewStore ¶ added in v0.4.0
NewStore prepares a store over pool. It refuses options that cannot bound a read. Any pool is accepted, and the catalog reads Ensure makes resolve to pg_catalog whatever the pool's search_path. The session timeouts, the session-affinity proof, and the removal of a pg_catalog entry listed after a user schema are what dbconn.NewPool adds; a pool built another way supplies its own timeouts.
func (*Store) Delete ¶ added in v0.4.0
func (s *Store) Delete(ctx context.Context, lock *dbconn.TableLockSession, schema, table string, stored Identity) error
Delete removes the target's row so a fresh run can Save its own. It is the one deliberate step between an IncompatibleError and a fresh start, and it removes only the row with the Identity the caller was shown — IncompatibleError.Stored, or a loaded Checkpoint's Identity — so a row another engine wrote in the meantime survives and comes back as a new IncompatibleError (ST-2). It runs under the target's table lock like Save (LK-1), and it is idempotent: a target with no row is already in the state Delete produces.
func (*Store) Ensure ¶ added in v0.4.0
Ensure makes the checkpoint table usable by this engine role and is a no-op once it is. It creates only what is absent: a pre-provisioned schema and table that the engine owns are accepted as they are, so a deployment that keeps database-level CREATE away from the engine role can create them for it beforehand. A schema or table that exists under another owner, or a relation under the table's name that is not a plain table, is refused with ErrForeignObject rather than adopted. A table an older engine created is brought up to this engine's shape by adding the columns it lacks, so its rows stay readable: that ALTER TABLE takes ACCESS EXCLUSIVE on the one table every target's row lives in, waits at most the session's lock_timeout for the writes in flight to clear, and is safe to call again after a lock timeout, which is returned as the server reported it. A table with columns this engine does not know is refused with a *TableNewerError (ErrTableNewer), untouched. Every read and write before Ensure has evolved an older table reports ErrTableBehind.
func (*Store) Inspect ¶ added in v0.4.0
Inspect reads the target's checkpoint before the run knows which statement it is resuming: it returns whatever row the target has, guarded on the row format and the phase alone, so a resume can read the shadow proof and the phase first and only then decide whether the row is its own. Its other outcomes are Load's — ErrNotFound for no row, ErrTableMissing where Ensure never ran, an IncompatibleError for a row in another format or in a phase this engine does not know, and a retried transient read error that is none of those (ST-2). A row Inspect returns is not thereby a row the run may write: Save still guards every write on the whole identity, and a row whose fingerprints are another statement's is still refused there.
func (*Store) Load ¶ added in v0.4.0
func (s *Store) Load(ctx context.Context, schema, table string, want Fingerprints) (Checkpoint, error)
Load reads the target's checkpoint for a run identified by want and tells its four outcomes apart (ST-2): a row carrying want's format and fingerprints is returned; no row is ErrNotFound, the one outcome a caller may start fresh from; a row carrying another format version or another statement's fingerprints, or left in a phase this engine does not know, is an IncompatibleError and must not be resumed from or written over; a read that did not complete is retried through transient errors under the store's bounded attempts and, once they are spent, returned as an error that is none of the above — a blip never reads as "no checkpoint". A database where Ensure has never run has no table to read, which is ErrTableMissing: also none of the above, so a status reader can report "no checkpoint table" without resume mistaking it for ErrNotFound.
func (*Store) ReapOrphanSlots ¶ added in v0.4.0
ReapOrphanSlots drops the engine's orphan replication slots in the store's database (ST-3). An orphan is a logical slot of the engine's name shape that no checkpoint row in a non-terminal phase names and that no process holds: a run makes its slot and commits the row that names it under the engine's lock on the slot's name, so a slot with no row was left by a run that ended without dropping it, and a slot named by a done or failed row by one whose cleanup did not finish.
Ownership is judged twice. The slots are listed first and the rows that own them read in a later statement, which sorts the slots a live row plainly names out of the pass; then, under the engine's lock on the slot's name (WithSlotLock), the row is read again and the slot dropped, and that read is the one that decides: a run claims its slot and its row under the same lock, so a run that claimed the slot since the pass began keeps it, and a run claiming it now waits for the drop and creates afresh. Whether a slot is held is judged at the drop: each orphan goes through decode.DropIdleSlot on a replication connection built from cfg, which refuses a held slot instead of waiting for its holder and takes an idle slot's publication with it. Slots a live row names or a process holds, and names that wear the prefix without the shape, are reported and left as found. The drops stop at the first failure, reporting what was dropped before it. Two reapers over one database take turns at each slot; the one that waited finds the slot gone and reports the drop as its own too.
A database where Ensure has never run has no rows to speak for its slots, so the pass is refused with ErrTableMissing rather than read every slot as an orphan. The reads that decide a slot's fate, the drop's included, do not consult the store pool's search_path, so a caller need not pin it.
func (*Store) Save ¶ added in v0.4.0
func (s *Store) Save(ctx context.Context, lock *dbconn.TableLockSession, cp Checkpoint) error
Save writes cp as the target's one row, atomically: a reader sees the previous record or this one, never a mix (ST-1). It refuses, with IncompatibleError, to write over a row that another statement or another row format owns, or one left in a phase this engine does not know; a run that means to start fresh calls Delete first (ST-2). The row's shadow proof is written once and then kept: a cp that carries no proof leaves the row's in place, and a cp that carries a different proof is refused with ErrInvariantViolation, because a different shadow is a fresh start, which goes through Delete (ST-2). The row's statement is kept the same way: written once, never cleared, and a cp that carries another statement's text is refused. The write runs under the target's table lock session and confirms, from its own transaction, that the session still holds the table (LK-1): a run whose lock went to another engine cannot stamp its stale state over the newer engine's row. UpdatedAt is taken from the store's clock, not from cp.
func (*Store) WithSlotLock ¶ added in v0.4.0
func (s *Store) WithSlotLock(ctx context.Context, cfg dbconn.Config, name string, fn func(ctx context.Context) error) (err error)
WithSlotLock runs fn while this store holds the engine's advisory lock on the named slot, so a run claiming the slot and a reaper judging it never interleave (ST-3). The lock is transaction-scoped on a connection of its own, dialled from cfg outside the store's pool and closed once fn returns, which lets the lock go: fn draws on the pool for its own work, and a lock that sat on a pool connection would hold the seat fn is waiting for, so as many claims at once as the pool has connections would each wait on the others. A run holds the lock while it makes the slot and commits the row that names it, in either order; the reaper holds it from its last read of the row until the slot is dropped. Whichever goes first, the other sees the outcome: a reaper that waited finds the row and keeps the slot, and a run that waited finds whatever bore the name gone and creates afresh.
The lock is let go however fn ends — a return, a panic the caller recovers, or the goroutine exiting — since the connection is closed on the way out. The lock is on the name, in the store's database: the same name in another database is another key, as D11 requires, so a cfg that dials another database or cluster than the store's pool is refused as ErrInvariantViolation before the lock is taken and fn runs. fn's error is returned as it is; a failure to take or let go of the lock is reported alongside.
type TableNewerError ¶ added in v0.4.0
type TableNewerError struct {
Unknown []string
}
TableNewerError is the ErrTableNewer a caller receives: Unknown names the columns this engine does not know, in the table's column order. A column a newer engine added and a column an operator added by hand look the same from here, and both are refused the same way, so the message names both causes and what to do about each.
func (*TableNewerError) Error ¶ added in v0.4.0
func (e *TableNewerError) Error() string
Error names the columns and the remedy for each cause.
func (*TableNewerError) Is ¶ added in v0.4.0
func (e *TableNewerError) Is(target error) bool
Is matches ErrTableNewer, so errors.Is(err, ErrTableNewer) holds for a *TableNewerError.