applier

package
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package applier turns decoded changes into shadow-table writes. A Buffer merges the stream into one Entry per primary key — the newest image or a delete marker, with an UPDATE overlaying only the columns it carries so an unchanged-TOAST marker is never mistaken for a value (CO-5, CO-8) — and Drain judges every key against the copier's Position: landed keys flush, uncut keys are discarded, in-flight keys wait for their chunk (CO-4). A Flusher applies the drained Batch in one guarded transaction under the table lock: it first reads a completion for every moved marker-bearing image the batch names, from the old key's shadow row or from the source when the old key was reused, and hands each back as a HeldImage with the WAL position of the read — the row read can be newer than the stream, so the buffer holds the image (Hold) until the stream has passed the read (Release) and flushes it then. It next checks, in one statement that also reads the WAL position, that the shadow holds the row of every marker-bearing image that did not move, and holds an image whose row is absent the same way, with nothing written: the stream has yet to deliver the DELETE that explains the absence, and an image still absent once the stream has passed the check is refused (CO-8). It then writes column-wise, every delete before any image: a delete, an upsert of a whole image, or an UPDATE of only the columns an image carries. On a unique or exclusion violation it falls back to deleting every key in the batch and inserting every surviving whole row (CO-6, CO-8). A batch a constraint still refuses comes back as ErrBatchDeferred for the caller to Requeue, and one the server rolled back as a deadlock victim, against the copier's open chunk, as ErrBatchDeadlocked. Catchup owns the loop: it reads the stream into the buffer, releases held images as the stream passes their reads, drains against the copier's Position read after the last Add, flushes, requeues a deferred or deadlocked batch or holds the flushed batch's images, and confirms the lesser of the delivered position and the oldest pending change (ST-4); it is the tracker's WorkSource for a catch-up step (changes_applied, changes_buffered, lag_bytes). Pause holds its flushes for a caller that needs the shadow still — a live repair — while the loop goes on reading and confirming the stream.

Index

Constants

View Source
const (
	// DefaultCatchupInterval is how long a cycle gathers changes before it
	// drains and flushes what it holds when the stream is not busy enough
	// to fill it first.
	DefaultCatchupInterval = 250 * time.Millisecond
	// DefaultCatchupMaxChanges is how many changes a cycle adds before it
	// drains and flushes, whatever the interval says.
	DefaultCatchupMaxChanges = 10_000
	// DefaultDeadlockAttempts is how many flushes in a row the server may
	// roll back as a deadlock victim before the catch-up stops, when
	// CatchupOptions leaves DeadlockAttempts zero.
	DefaultDeadlockAttempts = 10
	// DefaultDeadlockBackoff is the wait before the first retry of a batch
	// the server rolled back as a deadlock victim, when CatchupOptions
	// leaves DeadlockBackoff zero. Each later wait is one backoff longer,
	// as the copier's collision passes wait, so the default attempts
	// together outlast a chunk's collision passes and the chunk pass on
	// the other side of the deadlock has time to commit or roll back.
	DefaultDeadlockBackoff = 250 * time.Millisecond
)

Variables

View Source
var (
	// ErrInvalidCatchupOptions reports catch-up options that cannot bound a
	// cycle.
	ErrInvalidCatchupOptions = errors.New("invalid catch-up options")
	// ErrCatchupAlreadyRun reports a second Run on a Catchup. A catch-up is
	// single-use: its stream, once failed, is not reopened here.
	ErrCatchupAlreadyRun = errors.New("catch-up has already run")
)
View Source
var (
	// ErrInvalidOptions reports flusher options that cannot bound a flush: a
	// timeout below PostgreSQL's one-millisecond resolution, which the server
	// would read as no timeout at all.
	ErrInvalidOptions = errors.New("invalid flusher options")
	// ErrBatchDeferred reports a batch the flush could not apply because a
	// unique index or exclusion constraint refused it even after the
	// delete-all-then-insert-all fallback (CO-6): a surviving image collides
	// with a shadow row the batch does not name — a stale row whose own
	// deletion is buffered behind an in-flight chunk. The transaction was
	// rolled back and the shadow is as it was; the stream owner puts the
	// batch back with Buffer.Requeue and drains again once the copier has
	// moved.
	ErrBatchDeferred = errors.New("batch deferred: a unique index or exclusion constraint refused it")
	// ErrBatchDeadlocked reports a batch whose flush the server rolled back
	// to break a deadlock (SQLSTATE 40P01). The shadow's writers — the
	// copier's chunk passes and the flush — insert values under the same
	// unique indexes, so while source changes move values between keys the
	// two can each wait on a value the other's open transaction holds; the
	// server picks one to roll back, and this is the flush picked. The
	// transaction committed nothing and the shadow is as it was; the stream
	// owner puts the batch back with Buffer.Requeue and flushes it again
	// after a backoff (CatchupOptions.DeadlockBackoff). A retry that waits
	// on the other writer past the flush session's lock_timeout fails with
	// the server's lock-timeout error.
	ErrBatchDeadlocked = errors.New("batch deadlocked: the server rolled the flush back to break a deadlock")
)
View Source
var ErrConversionDrift = chunksql.ErrConversionDrift

ErrConversionDrift aliases the one sentinel every guarded transaction wraps when the catalog the conversion expressions resolve in has changed since the shadow build (CO-9); the flusher's drift wraps it together with ErrInvariantViolation, so a caller can tell this breach from any other.

View Source
var ErrInvariantViolation = dbconn.ErrInvariantViolation

ErrInvariantViolation aliases dbconn's fail-closed error class so one errors.Is check covers a breach raised here or in the connection layer.

View Source
var ErrTableLockLost = dbconn.ErrTableLockLost

ErrTableLockLost aliases dbconn's table lock loss: every LK-1 error the applier returns for a lost lock wraps it, with ErrInvariantViolation.

Functions

This section is empty.

Types

type Batch

type Batch struct {
	// Entries are the landed keys' entries, each a copy the buffer no longer
	// holds; a later Add for the same key does not change it. They are in
	// ascending key order, which is not an order the flush may write them
	// in one pass: a moved image sorts by its new key, after or before the
	// delete marker at the old key it still has to read (see CompleteFirst).
	Entries []Entry
	// Discarded counts the entries dropped because their keys were uncut:
	// the copier's own read of those chunks will see the change.
	Discarded int
	// Deferred counts the entries still buffered because their keys are
	// inside an in-flight chunk, or are moved images whose old key's entry
	// is in flight or invisible, or travel with an invisible image. This is
	// the number a stalled catch-up is waiting on the copier for.
	Deferred int
	// Held counts the entries still buffered because a flush held them (see
	// Buffer.Hold) — with a completion, or because their shadow row was
	// absent: they wait for the stream to pass the position of the flush's
	// read, not for the copier.
	Held int
	// Invisible counts the entries still buffered because the snapshot the
	// drain judged them against did not show their transaction visible yet
	// (see Snapshot). They wait for a later drain's snapshot, not for the
	// copier; an entry deferred only because it travels with one of them
	// counts as Deferred.
	Invisible int
}

Batch is what one Drain decided: the entries to flush now, in ascending key order, and how many buffered entries it discarded or left waiting. The flush takes two passes over Entries: it completes every entry CompleteFirst names, then writes the rest. Key order does not express that dependency.

func (Batch) CompleteFirst

func (b Batch) CompleteFirst() []Entry

CompleteFirst returns the images whose value depends on a row the flush must read before it writes anything in the batch: the moved images still carrying an unchanged-TOAST marker. For an image whose OldKey was not reused, the value lives in the shadow row under OldKey (D13), and the delete marker at that old key may be in the batch too, sorted by its own key, so a flush that wrote Entries in order could delete the row before reading it. For an image whose OldKeyReused is set, the old key's shadow row is another row's and the value is read from the source row under Key; it is named all the same, since it has to be whole before it is written. An image that did not move is not named: its marker stands for the row under its own key, which no other entry deletes — the primary path's upsert writes only present columns and leaves that value in place, and the fallback, which needs every image whole, completes it from that row before the fallback's own deletes. The result is in Entries' order and copies them: a completion the flush reads comes back to the buffer through Buffer.Hold, not through the batch.

func (Batch) OldestFirstLSN

func (b Batch) OldestFirstLSN() (decode.LSN, bool)

OldestFirstLSN returns the earliest FirstLSN among the batch's entries, and false when the batch is empty. Until the flush of this batch commits, the position the stream owner may confirm is bounded by this and by the buffer's OldestPending together, whichever is lower: the batch's entries have left the buffer, so OldestPending alone no longer covers them, and a restart after a failed flush must replay from a position their first event's transaction committed above.

type Buffer

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

Buffer holds the latest knowledge of every primary key captured since the last flush: one Entry per key, merged rather than replaced, so a flush applies each key once with its newest image or deletion (CO-5). It is not safe for concurrent use; the stream owner adds and drains it from one goroutine.

func NewBuffer

func NewBuffer() *Buffer

NewBuffer returns an empty buffer.

func (*Buffer) Add

func (b *Buffer) Add(ev decode.ChangeEvent) error

Add merges one decoded change into the buffer in stream order. An event the source could not have produced given what is already buffered — an UPDATE or INSERT over a deleted row, an INSERT over a live one, an INSERT missing a value, a move onto a live key or from a deleted one — returns ErrInvariantViolation, and the buffer is left as it was.

func (*Buffer) Drain

func (b *Buffer) Drain(pos copier.Position, snap Snapshot) Batch

Drain decides every buffered entry against one reading of the copier's position and one snapshot of the source. Each key is judged on its own (CO-4): an uncut key's entry is discarded, because the copier's own read of that chunk will see the change; a landed key's entry is flushed; an in-flight key's entry stays buffered until a later Drain finds its chunk landed. Discarding is sound only when the copier reads an uncut key's chunk after the buffered change is visible, so the caller adds every event it holds, then takes snap, then reads the copier's Position, then drains: a transaction snap shows visible is visible to every read the copier or a flush makes after it. An entry whose transaction snap does not show visible yet stays buffered whatever its key's state — discarded, the copier's read could miss it; flushed, a completion read could — and is judged again by the next Drain. Discarded and flushed entries leave the buffer; a flush that then fails is not re-buffered — the stream replays from its last confirmed position, which stays below OldestPending and the batch's OldestFirstLSN until the flush commits, and rebuilds them.

An image that moved from an old key, and the entry still buffered at that old key, travel together once neither is uncut: the image waits while the old key's entry is in flight or invisible, and the old key's entry waits while the image is invisible. The flush completes the image's unchanged-TOAST markers before it deletes anything (D13), and that reading must not race the copy of the old key's row or a transaction no snapshot shows yet; Batch.CompleteFirst names the images it applies to. A landed old key's entry does not wait for an image whose own chunk is in flight: the row's unique values are still under the old key in the shadow, and the chunk's insert of the row under the new key collides with them until that entry flushes, so holding it back would wait on a chunk that is waiting on it. The image, flushed once its chunk lands, finds the old key's shadow row gone and completes from the source row under its own key instead, held until the stream passes the read (D13). An image whose completion is pending (Buffer.Hold) stays buffered whatever its key's state, until Release lets the completion in or an event drops it.

func (*Buffer) Held

func (b *Buffer) Held() int

Held reports how many images are buffered with a completion pending.

func (*Buffer) Hold

func (b *Buffer) Hold(held []HeldImage) error

Hold puts the images a Flush held back into the buffer, each as the batch carried it, with its completion pending: Drain keeps the image until Release lets the completion in, and an event that replaces the key's entry or reuses its old key drops the completion instead, since the read may have seen that event's row. A completion read from the shadow row is kept in the shadow's form, so the flush that writes it binds it bare instead of converting the shadow's own value again; one read from the source row is kept as it is, to be converted like a value from the stream. Like Requeue, Hold runs before any Add after the Drain; a key the buffer already holds is ErrInvariantViolation, and the buffer is left as it was.

func (*Buffer) Len

func (b *Buffer) Len() int

Len reports how many keys are buffered, including entries a Drain deferred or held.

func (*Buffer) OldestPending

func (b *Buffer) OldestPending() (decode.LSN, bool)

OldestPending returns the earliest FirstLSN among buffered entries: the delivered position the earliest buffered event arrived with. A stream confirmed past it could have discarded that event's transaction, so the confirmed position must stay at or below it — and, until the flush of a drained Batch commits, at or below that batch's OldestFirstLSN too. It never falls below what the stream had confirmed when the event arrived, so a stream always accepts it. The second result is false when the buffer is empty.

func (*Buffer) Release

func (b *Buffer) Release(passed decode.LSN) int

Release tells the buffer that the stream has delivered every change committed at or below passed. A completion read at or below that position whose key no event has replaced since was read from the row the stream knows under the key, so the buffer takes it for every column the image still carries as a marker — an UPDATE of the key that arrived meanwhile kept the completion pending, and its values are newer than the read's — and the next Drain flushes the whole image. Release returns how many completions it took.

func (*Buffer) Requeue

func (b *Buffer) Requeue(batch Batch) error

Requeue puts a drained batch back into the buffer after a Flush returned ErrBatchDeferred, so the next Drain judges its entries again once the copier has moved. The entries go back as the drain handed them out: the flush wrote nothing and completed nothing the batch keeps, so a marker is still a marker. The stream owner adds nothing between the Drain and the Requeue, so no buffered entry can hold a batch key; one that does is ErrInvariantViolation, and the buffer is left as it was.

type Catchup

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

Catchup owns the stream's consumer loop: it reads the stream into a Buffer, drains the buffer against the copier's Position, flushes each drained Batch through the Flusher, and confirms to the server what the shadow durably holds. One Catchup serves one stream for the lifetime of Run; the stream, the flusher, and the buffer are used from Run's goroutine alone, and Status, Work, and Pause are safe to call from any other.

func NewCatchup

func NewCatchup(stream *decode.Stream, flusher *Flusher, positions PositionSource, opts CatchupOptions) (*Catchup, error)

NewCatchup prepares a catch-up that reads stream, judges keys against positions, and flushes through flusher. It refuses options that cannot bound a cycle.

func (*Catchup) Confirmed

func (c *Catchup) Confirmed() decode.LSN

Confirmed is the position the catch-up last confirmed to the server: every change to a landed key that committed at or below it is in the shadow. It is the checksum's ConfirmedSource for a live pass.

func (*Catchup) Pause

func (c *Catchup) Pause(ctx context.Context) (resume func(), err error)

Pause holds the catch-up's flushes off the shadow until resume is called. It returns once no flush is in flight, so a caller that then takes the shadow for itself — a live repair recopying it from the source — never waits behind a flush, and the stream never waits behind the caller. The catch-up keeps running under the hold: every cycle still reads the stream, so the walsender's keepalives are answered and nothing it sends is lost, buffers what arrives, and confirms what it may — with unapplied changes buffered that is the position below the oldest of them (ST-4) — and only the drain and the flush are skipped, so the buffer grows by what the source writes for as long as the hold lasts and the first cycle after resume flushes it. The hold is bounded by the caller: a caller that waits for the catch-up to confirm past its own work resumes first, since the confirmation needs the flushes. Pause waits for a flush in flight to commit or fail, or for ctx to end; a second Pause waits for the first's resume; resume is safe to call more than once. A Pause whose ctx ends first takes no hold and returns an error that answers errors.Is for ctx.Err(), and also for the cause when ctx was cancelled with one. Pause before Run takes the hold at once, and a Run started under it flushes nothing until resume. Status reports the hold as FlushesHeld from Pause's return until the resume.

func (*Catchup) Run

func (c *Catchup) Run(ctx context.Context, pool *pgxpool.Pool) error

Run consumes the stream in cycles until ctx ends or the stream, the buffer, or a flush fails. Each cycle gathers changes until MaxChanges are buffered or Interval has passed, takes the source's snapshot and then reads the copier's Position after the last Add — so a discarded uncut key's change is one the copier's read will see, and a change whose commit the source has not yet made visible waits for a later cycle (CO-4) — drains, flushes the batch, puts a refused batch (ErrBatchDeferred) or one the server rolled back as a deadlock victim (ErrBatchDeadlocked) back for a later cycle, or holds the images the flush did not write — those it completed and those whose shadow row it found absent — and then confirms the lowest of the stream's delivered position and the buffer's oldest pending position: everything below it is in the shadow or was discarded as uncut, so a stream reopened from it misses nothing (ST-4). An empty cycle on a quiet table still confirms, so the slot releases WAL while nothing changes. The cycle ends by reading the server's write position on pool, so Status.Lag measures the WAL the catch-up has yet to work through, not how far the walsender has decoded. A cycle under a Pause gathers and confirms but neither drains nor flushes, so the stream is read and answered for as long as the hold lasts and the buffer holds what arrives for the cycle after the resume. The cycles after a deadlocked flush do the same until its backoff has passed on CatchupOptions.Clock, each deadlock in a row waiting one CatchupOptions.DeadlockBackoff longer than the one before.

Run never returns nil: a catch-up has no end of its own, so its owner stops it by ending ctx once the shadow is close enough to cut over, and Run returns the stop, wrapped, once the stream reports it. The stop answers errors.Is for ctx.Err() (context.Canceled or context.DeadlineExceeded), and also for the cause when ctx was cancelled with one (context.WithCancelCause). A stopped catch-up leaves the stream failed and the slot at the last confirmed position, which is where the next stream resumes. A cycle error that is not the stop itself travels with the stop, so a caller checks the failure sentinels — ErrInvariantViolation, ErrTableLockLost, ErrBatchDeferred, ErrBatchDeadlocked — before it reads the stop as clean. The whole run is bound to the table lock session, so losing the lock ends the cycle in flight, a flush or a quiet wait on the stream alike, and Run reports the loss as ErrTableLockLost under LK-1. A batch the shadow refuses once the copy has landed every key ends Run with ErrBatchDeferred: no chunk is left to change the outcome, so the schema change cannot converge. A flush the server rolls back as the deadlock victim CatchupOptions.DeadlockAttempts times in a row ends Run with ErrBatchDeadlocked, wrapping the server's error. While it runs the catch-up is the tracker's work source (CatchupOptions.Tracker), and it has stopped being one by the time Run returns.

func (*Catchup) Status

func (c *Catchup) Status() Status

Status returns the catch-up as of the end of its last completed cycle.

func (*Catchup) Work

func (c *Catchup) Work(context.Context) (progress.Work, error)

Work reports the catch-up's counters for the progress tracker: it is the progress.WorkSource the catch-up registers for the lifetime of Run. Every counter is read from memory — the catch-up knows what it has flushed and what the stream has told it — so a poll never waits on the database.

  • changes_applied is the number of images and delete markers committed flushes have written to the shadow, exact and monotone.
  • changes_buffered is the number of keys the buffer held at the end of the last cycle: changes waiting for an in-flight chunk or for a completion the stream has not yet passed.
  • lag_bytes is how far the confirmed position trails the server's write position, in WAL bytes, both as of the last cycle: the write position is pg_current_wal_lsn() read on the pool as the cycle ended, never the walsender's send position, which stays small while a backlog is undecoded. Zero until a cycle has run.

type CatchupOptions

type CatchupOptions struct {
	// Interval is the longest a cycle gathers changes before it drains and
	// flushes. It is also the longest a quiet stream goes between
	// confirmations, so the slot's retained WAL is released at this pace,
	// and it is part of the grace the retained WAL may stand over
	// SlotLagCeiling: a longer Interval lets the slot grow further past
	// the ceiling before the run ends.
	Interval time.Duration
	// MaxChanges is the most changes a cycle adds before it drains and
	// flushes: the bound on a flush transaction's size on a busy stream.
	MaxChanges int
	// Clock times each cycle's interval.
	Clock progress.Clock
	// Tracker, when set, is told the catch-up's work for the lifetime of
	// Run: the catch-up is its progress.WorkSource from before the first
	// cycle until just before Run returns. The caller owns the tracker's
	// steps; the catch-up only fills the current step's counters. A tracker
	// polls one source at a time, so a catch-up that runs alongside the
	// copy is given no tracker, or one of its own: registering it on the
	// copier's tracker would hide the copier's counters, as registering the
	// copier on this one would hide the catch-up's.
	Tracker *progress.Tracker
	// SlotLagCeiling is the most WAL, in bytes, the stream's slot may hold
	// before Run ends with a *decode.SlotLagExceededError (D11, ST-3). It
	// bounds two measures: the WAL the stream has yet to confirm ends the
	// run on the first cycle that reads it over the ceiling, since that
	// lag is the stream's own; the WAL the slot retains on the volume,
	// which the server releases some time after the stream confirms it,
	// ends the run only once it has stayed over the ceiling for the
	// server's release interval plus one cycle. A busy source's slot retains
	// one to two release intervals of the cluster's WAL while the stream
	// keeps up, so a ceiling below a release interval and a cycle of it,
	// with margin, ends a healthy run. Zero takes
	// decode.DefaultSlotLagCeiling; a value below one byte is refused, so
	// the ceiling is always in force.
	SlotLagCeiling int64
	// DeadlockAttempts is how many flushes in a row the server may roll
	// back as a deadlock victim (ErrBatchDeadlocked) before Run ends with
	// that error. A deadlocked batch is requeued whole and flushed again
	// once DeadlockBackoff has passed; a retry that waits on the other
	// writer past the flush session's lock_timeout ends Run with the
	// server's lock-timeout error. A flush that commits, or is refused by a
	// constraint instead, resets the count. Each attempt waits up to the
	// server's deadlock_timeout to be chosen as the victim.
	DeadlockAttempts int
	// Logger receives a record when a cycle requeues its batch, so a
	// caller that does not poll Status sees the condition while it lasts;
	// nil discards them. A batch a constraint refused
	// (Status.BatchesDeferred) waits for the copy by design, so it logs at
	// Info and only as the run's count reaches 1, 2, 4, 8, and so on. A
	// flush the server rolled back as a deadlock victim
	// (Status.BatchesDeadlocked) logs at Warn every time. The records carry
	// schema, table, entries (the batch's size), and batches_deferred, or
	// batches_deadlocked with consecutive_deadlocks and deadlock_attempts;
	// never row data. pg-sprite migrate shows them on stderr only with
	// --debug.
	Logger *slog.Logger
	// DeadlockBackoff is the wait, on Clock, between a flush the server
	// rolled back as a deadlock victim and the first retry of its batch;
	// each later retry in the same run of deadlocks waits one backoff
	// longer than the one before, so the n-th retry waits n backoffs and
	// the longest wait is DeadlockAttempts-1 backoffs, and the waits of a
	// whole run of deadlocks add up to DeadlockAttempts*(DeadlockAttempts-1)/2
	// backoffs. A cycle reads the clock only after its Interval of reading
	// the stream, so every wait ends at the first cycle that ends after it:
	// a backoff below Interval does not bring the first retry any earlier.
	// The cycles while it waits still read, buffer, and confirm the stream,
	// as under a Pause, but neither drain nor flush, and Status.BackingOff
	// says so. Zero takes DefaultDeadlockBackoff; a negative value is
	// refused.
	DeadlockBackoff time.Duration
}

CatchupOptions bounds a cycle. Zero values take the defaults.

type Entry

type Entry struct {
	Key  int64
	Kind EntryKind
	// OldKey is set on an Image whose row moved since the last flush. It is
	// the key the row started at — the only key whose shadow row can hold
	// the row's pre-buffer version — however many moves the buffer merged,
	// and it equals Key when the row moved away and back. The entry at that
	// key, if still buffered, is flushed in the same batch as this image or
	// deferred with it, never before it, because the flush completes this
	// image's unchanged-TOAST markers before it deletes anything (D13).
	OldKey *int64
	// OldKeyReused is set on an Image with an OldKey when the source has
	// since put another row at that key, so the shadow row the copier reads
	// or has read there is that row's, not this one's pre-buffer version.
	// The flush completes a reused image's markers from the source row under
	// Key, never from the old key's shadow row (D13). Inherited through a
	// chain of moves with OldKey; a row returning to its own origin is not a
	// reuse.
	OldKeyReused bool
	// AbsenceAwaited is set on a marker-bearing Image of a row that did not
	// move once a flush has found the shadow holding no row under Key and held
	// the image until the stream passed that check (D13). The source can have
	// deleted the row before the chunk covering its key was read, with the
	// DELETE still undelivered, so a first absence is waited out; an image
	// that returns with the flag set and the row still absent is one the
	// stream holds live, which is an invariant violation (CO-8). A new entry
	// for the key never carries it.
	AbsenceAwaited bool
	// Columns is the merged row image for an Image, in the decoded column
	// order; an absent column is an unchanged-TOAST marker whose
	// value no buffered event carried. It is nil for a DeleteMarker.
	Columns []decode.Column
	// FirstLSN is the delivered position the earliest event this entry still
	// holds arrived with (decode.ChangeEvent.Delivered): a stream confirmed
	// past it could have discarded that event's transaction, so the entry
	// would be lost on replay. It is not the event's own LSN, which can lie
	// below a position already confirmed.
	FirstLSN decode.LSN
	// Xid is the transaction of the latest event merged into this entry
	// (decode.ChangeEvent.Xid). Drain judges the entry only once a snapshot
	// of the source shows that transaction visible: a commit the stream
	// has delivered can still be invisible to readers while the server
	// waits on WAL flush or synchronous replication, and a copier read or
	// flush read taken in that window would not see it. The latest
	// transaction suffices because transactions that write the same key
	// are serialized by the row's lock, which is released only after the
	// earlier one became visible.
	Xid uint32
}

Entry is the buffer's latest knowledge of one primary key: at most one per key at any flush (CO-5).

func (Entry) HasMarker

func (e Entry) HasMarker() bool

HasMarker reports whether the image still carries a column no buffered event supplied, so the flush must complete it (CO-8).

type EntryKind

type EntryKind uint8

EntryKind is what a buffered entry asks the flush to do for its key.

const (
	// Image writes the row: an upsert of every present column, with any
	// non-present column completed by the flush (CO-8).
	Image EntryKind = iota + 1
	// DeleteMarker removes the row.
	DeleteMarker
)

func (EntryKind) String

func (k EntryKind) String() string

String returns the stable kind name.

type Flusher

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

Flusher writes drained batches into the shadow. Each Flush is one bounded read-write transaction under the table's lock session, guarded as the copier's chunk inserts are, that applies every entry of the batch once: a delete marker as a DELETE, an image as an upsert of its present columns (CO-5, CO-8), with the batch-wide fallback D13 decides when a unique index refuses the upserts (CO-6). A column the gated statement retyped with USING is written through that expression, as the copier copies it (D7), so the shadow holds the value the statement would have produced whichever path put it there. A Flusher keeps no state between flushes; the stream owner calls Flush from one goroutine, after Drain and before the next Add.

func NewFlusher

func NewFlusher(target preflight.CopySwapTarget, shadow copier.Shadow, lock *dbconn.TableLockSession, opts Options) (*Flusher, error)

NewFlusher prepares flushes into shadow for the proven target. It refuses a proof, shadow, or lock session that does not describe this table, and options that cannot bound a flush. The shadow is checked as the copier checks it: the flusher writes into the relation the copier writes into and must refuse everything the copier would have.

func (*Flusher) Flush

func (f *Flusher) Flush(ctx context.Context, pool *pgxpool.Pool, batch Batch) (Result, error)

Flush applies one drained batch to the shadow in one transaction, or writes nothing. It first reads a completion for every image Batch.CompleteFirst names (D13): from the shadow row under its old key, locked, or from the source row under Key when the old key was reused or its shadow row is absent. Those images are not written; each comes back in Result.Held with its completion and the WAL position of the read, for Buffer.Hold, because the row read can be newer than the stream. An image neither row can complete is written as a delete of its key, which the source holds no row under, and named in Result.Skipped. The flush then applies the other entries: every delete marker first, then every image — one without markers upserts every column, one with markers updates its present columns and must find the key's row (CO-8). When a unique index or exclusion constraint refuses a write the flush rolls back to its savepoint, completes every image that still carries a marker from the shadow row under its key, deletes every key in the batch, and inserts every image whole (CO-6); a constraint that refuses that too means a collision with a row the batch does not name, and the flush returns ErrBatchDeferred with the shadow unchanged. A marker-bearing image of a row that did not move, whose shadow row is absent, is held without a completion, since the source can have deleted the row before its chunk was read; one that returns after the stream has passed that check, still absent, is an image the source could not have produced given the shadow, and is ErrInvariantViolation, with nothing committed. A flush the server rolls back as a deadlock victim, because it and the copier's open chunk each wait on a unique value the other holds, is ErrBatchDeadlocked with the shadow unchanged, for the stream owner to requeue and flush again after a backoff; a retry that waits on the other writer past the session's lock_timeout fails with the server's lock-timeout error. The transaction runs under the lock session's Bind context, so losing the table lock cancels the flush and it reports the loss. An empty batch is a no-op.

func (*Flusher) FlushIn

func (f *Flusher) FlushIn(ctx context.Context, tx pgx.Tx, batch Batch) (Result, error)

FlushIn applies one drained batch inside a transaction the caller owns and leaves it open: it is the drain the cutover runs under its swap lock, where the writes must commit with the renames or not at all. The batch is applied as Flush applies it — completions first, then markers and images column-wise, with the whole-row fallback (CO-6) — after the same guards: the source and shadow are held in ACCESS SHARE, the lock session's backend is confirmed to hold the table from this connection, both relations are confirmed to be the ones the proofs describe, and, for a copy that evaluates conversion expressions, the catalog they resolve in is confirmed to be the one the build saw, before the writes and again after them (CO-9). The caller's transaction already carries its budgets and role, so none are set here; the flush pins the output settings Flush pins, chunksql.Rendering, so a completion or conversion renders a value as the copy did, and sets the search_path every flush runs under — the catalog alone, or the build's path for a copy with conversions, so their expressions resolve as the gated statement's did (CO-9). It restores the caller's extra_float_digits and bytea_output before it returns and leaves the search_path on the flush's path for the caller to set back as its own statements need.

The second resolution check is what refuses a write that resolved through a catalog change committed after the first; it sees that change only when the caller's transaction is READ COMMITTED, where each statement takes a new snapshot.

A batch the shadow refuses even whole-row is ErrBatchDeferred, and the server has aborted tx: the caller rolls it back. Any other failure leaves tx aborted, or — for a resolution that drifted after the writes, ErrInvariantViolation — open with writes the caller must not commit; either way the caller rolls it back. An empty batch touches nothing, not even the session settings.

type HeldImage

type HeldImage struct {
	// Entry is the image as the batch carried it, markers intact.
	Entry Entry
	// Completed carries the value the read found for each marker column, as
	// the text the server rendered it, or nil for NULL. The values are in
	// the form of the row FromSource names: a shadow row holds a converted
	// column's converted value, a source row the source's, and Hold reads
	// FromSource to tell the flush which it has.
	Completed []decode.Column
	// FromSource reports a read of the source row under Key; false is a read
	// of the shadow row under the old key.
	FromSource bool
	// ReadLSN is the WAL insert position at the read, or at the check that
	// found the shadow row absent. Every change the read saw had committed
	// below it, so a stream that has delivered every change committed through
	// ReadLSN has delivered every change the read knew about.
	ReadLSN decode.LSN
}

HeldImage is an image a Flush did not write: a moved image it completed, or a marker-bearing image of a row that did not move whose shadow row was absent, which carries no completion and has Entry.AbsenceAwaited set (D13).

The value a moved image's markers stand for was read from a row that can be newer than the stream — the old key's shadow row, which the copier read live, or the source row under Key — so a change the stream has not delivered yet could have put another row's value there. The flush hands the completion back with the WAL position of its read, and the buffer writes the image in a later flush once the stream has delivered everything the read could have seen and nothing touched the key (D13). An image held for an absent shadow row waits the same way, for the stream to deliver the DELETE that removed the row from the source.

type Options

type Options struct {
	// LockTimeout bounds every lock wait inside the flush transaction.
	LockTimeout time.Duration
	// StatementTimeout bounds every statement inside the flush transaction.
	StatementTimeout time.Duration
}

Options bounds a flush. Zero values take the dbconn session timeout defaults.

type PositionSource

type PositionSource interface {
	Position() copier.Position
}

PositionSource reports where the copy stands, so a Drain can judge every buffered key against it (CO-4). A running or finished *copier.Copier is one; its Position stays valid after Run returns, with every key landed and nothing in flight.

type Result

type Result struct {
	// Images is the number of row images written, by upsert or, under
	// Fallback, by whole-row insert.
	Images int
	// Deletes is the number of delete markers applied, counting the delete
	// written for each key in Skipped. Under Fallback every key in the
	// batch is deleted before the inserts; those deletes are not counted
	// here, only the markers.
	Deletes int
	// Completed is the number of images whose unchanged-TOAST markers the
	// fallback filled in from the shadow row under their own key before
	// writing them whole (CO-6, D13).
	Completed int
	// Held are the moved images the flush completed from the old key's
	// shadow row, or from the source row under Key, and did not write: the
	// row read can be newer than the stream, so the buffer takes each
	// completion only once the stream has passed its read position (D13).
	// The stream owner gives them to Buffer.Hold before its next Add. Also
	// held, with no completion, is a marker-bearing image of a row that did
	// not move whose shadow row is absent: the source can have deleted the
	// row before its chunk was read, with the DELETE still undelivered, so
	// the image waits for the stream to pass the check's position (D13).
	Held []HeldImage
	// Skipped are the keys of the moved images the flush wrote as a delete
	// because neither the old key's shadow row nor the source row under Key
	// could complete them: the source holds no row under the key, so the
	// shadow must not either, and the event that removed it arrives later
	// (D13).
	Skipped []int64
	// Fallback reports that a unique index or exclusion constraint refused
	// the column-wise writes and the batch was applied as
	// delete-all-then-insert-all (CO-6).
	Fallback bool
}

Result is what one Flush wrote, and what it read but did not write.

type Snapshot

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

Snapshot is what the source showed as committed at one instant: which transactions a reader taking a snapshot then would see. Drain judges a buffered entry only once its transaction is visible in one (CO-4).

The server writes a transaction's commit to the WAL, and waits for any synchronous standby to acknowledge it, before it marks the transaction visible to new snapshots. The walsender decodes the commit from the WAL as soon as it is flushed, so the stream can deliver a change whose transaction no reader can see yet. A copier chunk read or a flush's completion read taken in that window misses the change; a drain that discarded or flushed the entry then would lose it (CO-4). Visibility is monotone, so a transaction visible in this snapshot is visible to every read taken after it.

The zero Snapshot shows nothing visible, so a drain against one keeps every entry: the safe reading when no snapshot was taken.

func AllVisible

func AllVisible() Snapshot

AllVisible returns a snapshot in which every transaction is visible. It is for a drain under a lock that excludes every writer of the source: each writer's transaction finished, and became visible, before the lock was granted.

func ReadSnapshot

func ReadSnapshot(ctx context.Context, db dbconn.RowQuerier) (Snapshot, error)

ReadSnapshot takes the server's current snapshot on db. The snapshot is read as text and parsed here rather than decoded as the server's xid8 type: the text form is stable across the supported majors.

func (Snapshot) Visible

func (s Snapshot) Visible(xid uint32) bool

Visible reports whether a reader taking this snapshot would see the transaction's writes. The stream numbers transactions in 32 bits, as the WAL does; the transaction is widened to the 64-bit id nearest the snapshot's xmax with those low bits, the way the server itself orders 32-bit ids. A transaction at or above xmax is one the server had not marked complete when the snapshot was taken, however far the stream has delivered it. The zero Snapshot reports nothing visible.

type Status

type Status struct {
	// Delivered is the stream's delivered position: every transaction that
	// committed at or below it has been added to the buffer or discarded.
	Delivered decode.LSN
	// Confirmed is the position last reported to the server as applied,
	// which is where a restarted stream resumes from.
	Confirmed decode.LSN
	// WALEnd is the server's write position, pg_current_wal_lsn() read on
	// the pool after the last cycle's confirmation; zero until a cycle has
	// run. It is measured there rather than taken from the stream: a
	// walsender's keepalive carries its send position, how far it has
	// decoded, which stays small exactly while a backlog is undecoded.
	WALEnd decode.LSN
	// Buffered is the number of keys the buffer holds after the last cycle:
	// entries deferred behind an in-flight chunk or held for a completion.
	Buffered int
	// Deferred is the number of entries the last drain left waiting for an
	// in-flight chunk, or for a batch a constraint refused (ErrBatchDeferred)
	// or the server rolled back as a deadlock victim (ErrBatchDeadlocked).
	Deferred int
	// Held is the number of images buffered until the stream passes a read
	// the flush made: a completion read for a moved image, or a presence
	// check that found an unmoved image's shadow row absent. A nonzero value
	// is normal for the cycle or two a hold lasts.
	Held int
	// Invisible is the number of entries the last drain left waiting for
	// the source to show their transaction visible: a commit the stream
	// delivered that the server was still flushing or waiting on a
	// synchronous standby for. A nonzero value is normal for a cycle;
	// one that persists means the source's commits are not completing.
	Invisible int
	// Applied is the number of images and delete markers committed flushes
	// have written to the shadow.
	Applied uint64
	// Discarded is the number of entries drains dropped because their keys
	// were uncut: the copier's own read sees those changes (CO-4).
	Discarded uint64
	// Fallbacks is the number of flushes that applied their batch whole-row
	// after a unique index or exclusion constraint refused the column-wise
	// writes (CO-6).
	Fallbacks uint64
	// BatchesDeferred is the number of batches a constraint refused even
	// whole-row, requeued for a later drain (CO-6).
	BatchesDeferred uint64
	// BatchesDeadlocked is the number of batches whose flush the server
	// rolled back as a deadlock victim and requeued for a cycle after its
	// backoff (CatchupOptions.DeadlockBackoff). A nonzero value is normal
	// while the copy and the catch-up write the shadow together; a run of
	// them that reaches DeadlockAttempts ends Run, and that last victim is
	// reported in Run's error, not counted here.
	BatchesDeadlocked uint64
	// FlushesHeld is set while a Pause holds the flushes off the shadow,
	// from Pause's return until its resume, and not while a cycle's own
	// flush runs. Unlike the fields above it is not a cycle's record: it
	// moves the moment the hold is taken or given back. Under the hold Lag
	// grows and Applied stands still on purpose, so a caller watching for
	// a stalled catch-up reads FlushesHeld and BackingOff first.
	FlushesHeld bool
	// BackingOff is set when the last cycle waited out a deadlocked batch's
	// backoff (CatchupOptions.DeadlockBackoff) instead of draining and
	// flushing. As under a Pause, Lag grows and Applied stands still while
	// it is set, and the requeued entries stay in Buffered and Deferred.
	BackingOff bool
}

Status is one consistent snapshot of a catch-up as of the end of its last completed cycle: the stream's positions and what the buffer and the flushes have done with the changes, all recorded together, and whether a Pause holds the flushes now.

func (Status) Lag

func (s Status) Lag() uint64

Lag is how far the confirmed position trails the server's write position as the last cycle measured it, in WAL bytes; zero until a cycle has run, or once the confirmation has caught it.

Jump to

Keyboard shortcuts

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