service

package
v0.2.13 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 30 Imported by: ? modules, 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 service implements chinit's convergent boot pipeline, retry engine, state persistence, configuration rendering, and recurring cluster maintenance operations.

Index

Constants

View Source
const (
	// ConfigD / UsersD are the ClickHouse drop directories.
	ConfigDir = "/etc/clickhouse-server/config.d"
	UsersDir  = "/etc/clickhouse-server/users.d"

	// ChinitStatePath is the state file (resume + subcommand identity).
	ChinitStatePath = "/var/lib/chinit/state.json"

	// NodeEnvPath is the shell identity contract for unit scripts that
	// still source it (kept until every consumer is a chinit
	// subcommand).
	NodeEnvPath = "/var/lib/clickhouse-bootstrap/node-env"

	// BootFinishedMarker is what health verification greps for.
	BootFinishedMarker = "/var/lib/cloud/instance/boot-finished"
)

Paths the boot pipeline owns (mirrors the bash script's constants).

View Source
const (
	CheckStatusPass = "pass"
	CheckStatusFail = "fail"
	CheckStatusSkip = "skip"
)

Check statuses. "skip" is a first-class outcome: optional checks (-keeper, -spec, -self) that were not requested must appear in the report so scripts see a stable shape, while never counting against health.

View Source
const (
	ReportStatusHealthy  = "healthy"
	ReportStatusDegraded = "degraded"
)

Report statuses: healthy only when every executed check passed.

View Source
const (
	DefaultQuorumPollInterval = 5 * time.Second
	DefaultQuorumWaitTimeout  = 2 * time.Minute
)

DefaultQuorumPollInterval and DefaultQuorumWaitTimeout mirror the controller's defaultQuorumDisruptPollInterval / WaitTimeout.

View Source
const ClickHouseDataDir = "/var/lib/clickhouse"

ClickHouseDataDir is the server's store root (the metadata-disk mount; keepers use their own coordination directories and never reach this step).

View Source
const DefaultHealthTimeout = 5 * time.Second

DefaultHealthTimeout bounds one probe when the -timeout flag is not given. 5s matches the keeper mntr default: a probe that cannot answer in 5s is a down node, not a slow one.

View Source
const DefaultReplicaGcPattern = "reader-*"

DefaultReplicaGcPattern is the eligibility glob for a GC sweep. The AWS stack's dead-replica-gc.sh gated on reader-%: only readers are disposable; a stale writer or keeper registration must survive a GC pass untouched, so the default keeps that gate.

View Source
const DefaultSchemaSyncRetries = 2

DefaultSchemaSyncRetries is the default -retries for schema sync: two full create passes. One pass re-runs the operator's per-SQL retry, but a materialized view whose TO-target table lands later in the same batch stays uncreated until a fresh pass re-orders the batch against the now existing targets .

View Source
const FaultTolerantMinMembers = 3

FaultTolerantMinMembers mirrors raftFaultTolerantMinMembers from the CHK controller's raft-safety gate: below this ensemble size quorum gating is meaningless — a 1- or 2-member ensemble cannot survive any planned disrupt, so the gate must not pretend otherwise and must allow maintenance.

Variables

View Source
var BootstrapDir = "/var/lib/clickhouse-bootstrap"

BootstrapDir is where the fetched bundle lands (and where chinit writes node-env for legacy consumers during migration). A var (not part of the const block) so tests can redirect it — the bootstrapDDLPath/bootstrapAdminPasswordPath seam pattern.

View Source
var ErrNotSafeToDisrupt = errors.New("disrupting this keeper would drop the ensemble below Raft quorum")

ErrNotSafeToDisrupt is returned when disrupting the target keeper would drop the ensemble below Raft quorum. Callers (lifecycle hooks) must hold the node.

HookEvents is the ordered boundary list (the docs and the specs share it).

Functions

func ConvergePeerDNS

func ConvergePeerDNS(ctx context.Context, provider port.Provider, args ConvergeDNSArgs) error

ConvergePeerDNS converges the private zone's server-role A records: one upsert for SELF, and a delete for every ordinal name whose lease expired (a dead holder's record).

Why periodic, not drain-only: the drain's DNS release is best-effort by design — an instance terminated by an EC2 health check never runs its drain (SSM cannot dispatch to a stopping instance), and the record lingers pointing at a dead IP. Peers resolve the name on every clusterAllReplicas fan-out / schema-sync / remote_servers connection, so ONE stale record wedges the whole fleet's coordination ( writer-1.example.clickhouse.internal kept a dead IP for hours after its holder died mid-churn; every schema-sync pass hung to the 60s query timeout on it, fresh writers stayed table-less, and the ingest/merge load pinned one writer while the ASG scaled into nodes that could not share the work).

The expired-slot delete is safe against the replacement race: a replacement claims the ordinal BEFORE it boots, so the record for a live claim is never a delete candidate; a record whose lease expired has no live holder by definition.

Failure semantics: best-effort, never fatal — the same contract as the hosts convergence. Guards and outages log a warning; the next tick retries.

func ConvergePeerHosts

func ConvergePeerHosts(ctx context.Context, provider port.Provider, args ConvergeHostsArgs) error

ConvergePeerHosts updates /etc/hosts on server nodes from the active ordinal lease claims so short hostnames ({replica} macros) resolve reliably across peer churn.

func CountHealthyByRole

func CountHealthyByRole(rows []port.NodeStatus) (writers, readers int)

CountHealthyByRole folds the status rows into the budget input's counts (healthy, non-cordoned, by role). Claims-joined by the caller; pure over the rows.

func DescribeFailures

func DescribeFailures(w io.Writer, res RunResult)

DescribeFailures renders the failed steps (WARNING lines for BestEffort, ERROR for the Critical one) — the boot log's triage section.

func Do

func Do(ctx context.Context, p Policy, op func(ctx context.Context) error) error

Do runs op under the policy: classification, backoff with jitter, deadline enforcement. The op receives the remaining-deadline context so long operations (S3 fetch, IMDS probe) abort instead of overrunning.

func DropDNSCache added in v0.2.5

func DropDNSCache(ctx context.Context)

DropDNSCache issues SYSTEM DROP DNS CACHE (best-effort) so ClickHouse's in-memory DNSResolver drops stale peer IPs immediately when /etc/hosts changes.

func Fatal

func Fatal(err error) error

Fatal wraps err as a FatalError (see fail.Fatal).

func FormatTimingSummary

func FormatTimingSummary(w io.Writer, res RunResult)

FormatTimingSummary prints the [TIMING] block the bash script printed (dashboards grep the format; chinit keeps it byte-compatible in shape).

func HasQuorumHeadroom

func HasQuorumHeadroom(members int) bool

HasQuorumHeadroom mirrors the controller's ensembleHasQuorumHeadroom.

func IsFatal

func IsFatal(err error) bool

IsFatal reports whether err is a FatalError (see fail.IsFatal).

func KeeperRolloutGate

func KeeperRolloutGate(votingMembers, syncedFollowers int, leaderPresent bool) error

KeeperRolloutGate is the keeper-mode ensemble safety check — the operator's raft-safety parity: a keeper replacement during a degraded ensemble can lose quorum, so the gate refuses unless the ensemble is healthy AND the replacement's absence still leaves the quorum. Pure over the mntr facts.

The rules (the highest-blast-radius item in the plan; no exceptions without the force flag, which the CLI owns):

  • the reporting keeper must see a live ensemble (its own mntr answered);
  • the leader must have synced followers ≥ VotingMembers/2 (the quorum: removing one voting member from a HEALTHY ensemble of N leaves (N-1) voting members whose majority floor is (N-1)/2+1 — the gate checks the ensemble CAN lose one: N ≥ 3 and the leader's sync is current);
  • a 1- or 2-keeper ensemble NEVER rolls (the quorum cannot survive the replacement's absence; a 2-keeper roll is a standing outage).

func NextRolloutDispatch

func NextRolloutDispatch(state RolloutState) string

NextRolloutDispatch answers the node the coordinator should submit a rollout task for, or "" when none: the rollout is complete, another task is outstanding, or every off-target node is cordoned.

func PeerHostsPath

func PeerHostsPath() func() string

PeerHostsPath returns the current hosts-file path (test seam).

func QuorumSize

func QuorumSize(members int) int

QuorumSize is Raft majority for an ensemble of n members (n/2 + 1). Extracted from the controller's raftQuorumSize.

func RenderFleetMetrics

func RenderFleetMetrics(in FleetMetricsInput) string

RenderFleetMetrics produces the Prometheus exposition text. Pure over the input — the exporter service and the tests share it.

The metric set (one source of truth; the CloudWatch bridge emits the same core counters):

chinit_fleet_tasks{phase=...}      — the task rows, by phase
chinit_fleet_nodes_healthy        — healthy status rows
chinit_fleet_nodes_degraded        — degraded status rows
chinit_fleet_nodes_cordoned       — cordoned status rows
chinit_fleet_status_age_seconds   — this node's row age (staleness)
chinit_cas_mounts_live            — live CAS mounts (when CAS enabled)
chinit_cas_wedged_namespaces      — wedged CAS GC namespaces
chinit_cas_gc_errors_total        — CAS GC errors in system.cas_gc_log
chinit_up                          — the exporter's own liveness

func RolloutGate

func RolloutGate(budget BudgetVerdict, state RolloutState) error

RolloutGate is the coordinator's verdict over the fleet view (the budget + version gates in one check the CLI logs).

func RunHooks

func RunHooks(ctx context.Context, runner HookRunner, hooks *model.Hooks, event model.HookEvent, identity HookIdentity, drainBoundary bool) error

RunHooks executes one boundary's hooks in list order. The rules (the criticality contract):

  • a non-critical hook's failure is logged and the boundary continues (the operator's best-effort hook semantics);
  • a CRITICAL hook's failure aborts the boundary with the error — EXCEPT on drain boundaries, where the node is already going down and no hook may block it: the failure is logged and the drain continues (the drain's own contract).

An empty boundary (no hooks for the event) is a no-op success.

func SetPeerHostsPath

func SetPeerHostsPath(f func() string)

SetPeerHostsPath redirects the hosts-file path (test seam).

func StaticHostname

func StaticHostname(privateIP string) (string, int)

StaticHostname derives writer-N, keeper-N, or backup-0 from the private IP's last octet (allocated at fixed offsets: writers at +10..+19, keepers at +20..+29, backup at +30).

func SweepExpiredSlotRecords

func SweepExpiredSlotRecords(ctx context.Context, provider port.Provider, args ConvergeDNSArgs) error

Types

type AutoscaleRequest

type AutoscaleRequest struct {
	// ClusterName is the cluster the metrics carry (the EMF
	// dimension every alarm and dashboard keys on).
	ClusterName string
	// Coordinator is the designation this node holds this tick
	// (the app layer's gate output; CoordinatorNone never reaches
	// the service — the CLI no-ops first).
	Coordinator domain.CoordinatorRole
	// Cooldown is the pacing request (Table + Key role-derived).
	Cooldown port.CooldownRequest
	// KeeperIdentity is the keeper coordinator's own instance (the
	// self-resize target; required for CoordinatorKeeper).
	KeeperInstanceID string
	// Ladder is the role's bounded ladder (spec-rendered).
	Ladder domain.TypeLadder
	// Fleet identifies the writers' ASG + launch template (the roll
	// target; required for CoordinatorWriter).
	Fleet port.FleetRefreshRequest
}

AutoscaleRequest is one coordinator invocation.

type AutoscaleResult

type AutoscaleResult struct {
	// Decision is what the tick concluded (breach, step, or no-op
	// with the reason line).
	Decision domain.ScaleDecision
	// Skipped is the pre-decision no-op (cooldown active, no
	// ladder, ceiling reached, unreadable signals) with the reason.
	Skipped string
}

AutoscaleResult is the invocation's outcome (the CLI prints it; the suite asserts it — a decision is data).

type AutoscaleService

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

AutoscaleService is the vertical-scaling use case: the COORDINATOR that decides one step per invocation and executes it over the ports. It replaces the vertical-autoscaler Lambda (SNS alarm → function → AWS API glue) with decision-time reads and live identity — the node is the authority on itself.

The service is pure over the ports: signals arrive through ScaleSignalsReader, identity through InstanceResizer/FleetResizer, pacing through CooldownStore — the fakes drive every branch in the suite; no cloud appears here (the DDD boundary the rest of this package draws: the SchemaService over its SchemaRunner).

Coordinator contract (why ONE node decides — domain/scaling.go): keeper-0 for keepers (static identity; the multi-keeper step order is peers-first, self-last), the ordinal-0 maintenance holder for writers. The CALLER (app layer) holds the designation gate — the service never re-derives who it runs on; it executes the coordinator's will for the identity it is handed.

func NewAutoscaleService

func NewAutoscaleService(signals port.ScaleSignalsReader, keeper port.InstanceResizer, fleet port.FleetResizer, cool port.CooldownStore) (*AutoscaleService, error)

NewAutoscaleService builds the service over its ports. Any nil port is a construction error — the caller reports the missing capability as the skip reason (a half-built service that crashes mid-decision is the failure shape the probes exist to prevent).

func (*AutoscaleService) Autoscale

Autoscale runs one coordinator tick: read signals, judge breach, take at most ONE bounded step, pace it with the cooldown.

type Boot

type Boot struct {
	Spec     *model.BootSpec
	Provider port.Provider
	// Meta is the probed instance metadata (fetched once, reused).
	Meta port.InstanceMetadata

	// Identity is filled by the identity step; later steps and the
	// node-env writer read it.
	Identity model.NodeIdentity

	// Refresh marks the run as an in-place refresh of a converged node
	// (vs. a first boot): every step re-executes, the identity is taken
	// from the state file when present (a refresh must NEVER re-claim an
	// ordinal lease — the node is a live cluster member), and the
	// keeper-ensemble wipe is skipped (raft state is live, not residue).
	Refresh bool
	// StatePath overrides ChinitStatePath (tests); empty means default.
	StatePath string

	// SpecHash gates resume: a new bundle hash invalidates prior step
	// results so the pipeline re-renders.
	SpecHash string

	// PersistIdentity is called by the settle_identity step right after
	// the identity is settled (claimed/derived + DNS): the app wires it
	// to the engine's state so the job subcommands and a crash-recovery
	// re-run always see the SETTLED identity, even if a later critical
	// step fails the boot. Nil (tests) = no persistence.
	PersistIdentity func(model.NodeIdentity)

	// SetHostname is how the settle_identity step sets the system
	// hostname. Production leaves it nil (settleIdentity falls back to
	// the hostnamectl/hostname sequence — best-effort by design); tests
	// inject a recorder so specs never rename the machine they run on.
	SetHostname func(ctx context.Context, hostname string) error
}

Boot is one node's boot pipeline: spec + provider + host. The 19-step order is load-bearing — identity settles BEFORE renders (the ip-* macro bug), passwords land BEFORE the render (passwordFrom refs), keepers skip the server start, and the health gate is non-fatal by design.

func (*Boot) CRName

func (b *Boot) CRName() (string, int)

CRName computes the operator CR host name for server nodes. The CHI spec names its single shard "01", so CR hosts are "01-0".."01-(N-1)" in a fixed order: writers first, then readers offset by WriterCeiling, and the backup replica at 01-(WriterCeiling + ReaderCeiling). Keepers return an empty name.

func (*Boot) ConvergeRemoteServers

func (b *Boot) ConvergeRemoteServers(ctx context.Context) error

ConvergeRemoteServers re-renders the node's remote_servers section from the CURRENT live-claims inventory and installs it ONLY when the content drifted — then hot-reloads ClickHouse (remote_servers changes apply live; no restart, verified against system.clusters).

Why periodic, not boot-only: remote_servers is rendered at boot from the lease-table snapshot of the moment, and fleet churn after the boot (a scale-in removing a peer, a scale-out adding one) leaves the rendered file naming peers that no longer exist — ON CLUSTER DDL fan-outs and clusterAllReplicas reads keep retrying the dead names until the next boot/refresh re-renders ( a scaled-in reader's entry wedged cluster-wide DDL for hours). The /etc/hosts and DNS convergences heal the RESOLUTION of the names; this convergence heals the LIST itself.

The render is the SAME one the boot runs (renderNodeConfig's inventory half — live-claims discovery, the vacant-slot filter, credential injection): a converged file is byte-identical to what the next boot --refresh would write, so the convergence can never fight the render contract.

Failure semantics: best-effort, never fatal — the same contract as the hosts/DNS convergences. A render or install failure logs and keeps the current file; the next tick retries. The RELOAD is only issued after a successful install (reloading an unchanged or failed file is pointless — and a reload failure leaves the file in place for the server's own config-reload watchdog).

func (*Boot) HydrateIdentityFromState added in v0.2.4

func (b *Boot) HydrateIdentityFromState(statePath string)

HydrateIdentityFromState populates b.Identity from the persisted boot state file when present for this instance. Called before the resume engine runs so that if settle_identity is skipped ("already done") on a restarted boot, downstream steps (configure_keeper, bootstrap_schema, configure_server_env) still receive the settled hostname and CR slot.

func (*Boot) LoadCHI

func (b *Boot) LoadCHI(ctx context.Context) (any, error)

LoadCHI loads the CHI spec the bundle delivered (the chctl library seam — no process boundary, no flag parsing).

func (*Boot) LoadCHK

func (b *Boot) LoadCHK(ctx context.Context) (any, error)

LoadCHK loads keeper.yaml (the CHK spec) from the fetched bundle configure_keeper renders the node's single-file config from it.

func (*Boot) Steps

func (b *Boot) Steps(ctx context.Context) ([]Step, error)

Steps builds the ordered boot pipeline. Phase 1 runs independent I/O-bound steps in parallel; Phase 2 runs sequentially to configure and start ClickHouse and its maintenance units.

func (*Boot) WriteNodeEnv

func (b *Boot) WriteNodeEnv(path string) error

WriteNodeEnv snapshots the settled identity into the shell contract file root-owned, 0600, single-quote-escaped (the bash node_env_kv semantics: a value can never inject live shell into a file root sources).

type BudgetInput

type BudgetInput struct {
	// Budget is the spec's policy (zero floors get the safe
	// defaults).
	Budget model.DisruptionBudget
	// HealthyWriters counts writer-role status rows with healthy
	// probes, excluding cordoned ones (a cordoned node is never
	// counted toward the floor — it may be mid-maintenance).
	HealthyWriters int
	// HealthyReaders counts reader-role healthy non-cordoned rows.
	HealthyReaders int
	// TargetRole is the role of the node asking to disrupt.
	TargetRole model.Role
}

BudgetInput is the fleet view the gate computes over: the live claims (liveness) and the status rows (health + cordon), already joined by the caller (the claims carry no role; the status rows do).

type BudgetVerdict

type BudgetVerdict struct {
	// Allowed is true when the voluntary disruption may proceed.
	Allowed bool
	// Reason carries the defer cause (diagnostics; empty on allow).
	Reason string
}

BudgetVerdict is the gate's answer: allow, or defer with the reason (the caller NEVER forces — the same rule dead-replica-gc's writer pass applies: without data, defer).

func CheckDisruptionBudget

func CheckDisruptionBudget(in BudgetInput) BudgetVerdict

CheckDisruptionBudget answers whether ONE more voluntary disruption of TargetRole is within the budget. The counting rule: a node asking to drain itself is currently healthy (its own status row counts toward the floor; the disruption removes it — the gate checks the AFTER picture: healthy - 1 >= floor).

The fail-safe contract: an uncountable fleet (no status rows for the role) defers, never allows — the same rule as dead-replica-gc's writer pass. The one exception is the LAST healthy writer asking to drain at shutdown: a termination is not voluntary deferrable work — the shutdown drain does not consult the budget (the OS is already going down); only voluntary paths (refresh, rollout, scale-in hooks) ask.

type CASMetrics added in v0.2.0

type CASMetrics struct {
	// Enabled reports whether CAS telemetry is active on this node.
	Enabled bool
	// LiveMounts is the count of CAS mounts reporting live state in
	// system.cas_mounts.
	LiveMounts int
	// WedgedNamespaces is sum(wedged_namespace_count) from
	// system.cas_mounts (> 0 indicates GC wedge needing investigation).
	WedgedNamespaces int
	// GCErrors is the count of recent Error entries in system.cas_gc_log.
	GCErrors int
}

CASMetrics carries Altinity Antalya Content-Addressable Storage (CAS) mount and garbage-collector health gauges probed from system.cas_mounts and system.cas_gc_log when CAS is enabled.

type ClickHouseDataStore added in v0.2.5

type ClickHouseDataStore interface {
	ReadEpoch() (PersistentEpoch, bool, error)
	WriteEpoch(epoch PersistentEpoch) error
	HasLegacyS3Store() bool
	ResetReplicaMetadata() error
}

ClickHouseDataStore abstracts local ClickHouse metadata/cache persistence so domain reconcilers stay decoupled from raw filesystem paths.

type Clock

type Clock interface {
	Now() time.Time
	Since(t time.Time) time.Duration
}

Clock abstracts time for the engine (step timestamps, durations). The default is the wall clock; tests run the pipeline instantly.

func NewWallClock

func NewWallClock() Clock

NewWallClock returns the production clock.

type ConvergeDNSArgs

type ConvergeDNSArgs struct {
	// LeaseTable is the node's own lease table (the claim scan reads
	// the same table the boot read).
	LeaseTable string
	// DNSZoneName is the private zone whose writer-*/reader-* records
	// are converged.
	DNSZoneName string
	// Hostname/PrivateIP identify the converging node's own record
	// the self-heal upsert keeps the renewal authoritative for the
	// node's name even when a prior drain missed it.
	Hostname  string
	PrivateIP string
	// WriterPrefix/ReaderPrefix are the hostname prefixes for ASG roles
	// (defaults to writer-/reader- when empty).
	WriterPrefix string
	ReaderPrefix string
	// WriterCeiling/ReaderCeiling bound the full reserved ordinal space
	// (writer_max / reader_max) so scaling in the highest-ordinal node
	// (e.g. writer-1 or reader-1 terminating, leaving only writer-0)
	// still sweeps the retired high-water ordinal's stale A record.
	WriterCeiling int
	ReaderCeiling int
}

ConvergeDNSArgs is the input to the DNS convergence: everything the sweep needs that is not in the provider (the lease table + private zone come from the settled identity, the node's own name/IP from the same identity record).

type ConvergeDNSOpts added in v0.2.0

type ConvergeDNSOpts []ConvergeDNSArgs

ConvergeDNSOpts is a domain collection of optional ConvergeDNSArgs.

type ConvergeHostsArgs

type ConvergeHostsArgs struct {
	// LeaseTable is the node's own lease table (the claim scan reads
	// the same table the boot read).
	LeaseTable string
	// WriterPrefix/ReaderPrefix are the hostname prefixes the claims
	// must match to earn a hosts line (defaults writer-/reader-).
	WriterPrefix string
	ReaderPrefix string
	// DNSZoneName is the FQDN suffix the line's third field carries
	// (writer-0 writer-0.zone) so FQDN resolution benefits too.
	DNSZoneName string
	// BackupReplicaHostname appends the LEASE-LESS backup replica to
	// the hosts file. The backup is a CR member and a part-fetch
	// source, but it holds no ordinal lease — the claim scan never
	// sees it, so without this field every peer resolving its short
	// name for a fetch died on DNS_ERROR Code 198 (the
	// CloudWatch 14 errors/node/hour, queues stalled). The
	// ADDRESS is derived at convergence time by resolving the FQDN
	// through the private zone — never carried in the spec, so a
	// re-provisioned backup converges without a bundle re-render.
	BackupReplicaHostname string
}

ConvergeHostsArgs is the input to ConvergePeerHosts: everything the hosts sweep needs that is not in the provider/lease table (the spec prefixes come from chinit.yaml, the lease table + DNS zone from the settled identity).

type Criticality

type Criticality int

Criticality preserves the bash script's `set -e` vs `|| echo WARNING` split as a first-class property of each step.

const (
	// Critical: failure stops the boot (exit non-zero) so the ASG
	// replaces the node. Disks, secrets, render, start.
	Critical Criticality = iota
	// BestEffort: failure logs a loud WARNING and the boot continues —
	// a reader booting while a peer is down must still join.
	BestEffort
)

func (Criticality) String

func (c Criticality) String() string

type DDLApplyResult

type DDLApplyResult struct {
	DDLPath string
	Created int
	Failed  int
	// Skipped counts statements the role filter dropped (the backup's
	// staging-pipeline objects — Code 499 AccessDenied on the queue's
	// poll).
	Skipped int
}

DDLApplyResult reports one convergence pass of the bundle DDL.

func ApplyBootstrapDDL

func ApplyBootstrapDDL(ctx context.Context, hostname, role string) (*DDLApplyResult, error)

ApplyBootstrapDDL runs one idempotent pass of the bundle's bootstrap-ddl.sql on this node: IF NOT EXISTS creates, the Code 253 stale-znode drop-and-retry, and a failed count the caller turns into a retryable error. It is the shared body of the boot's bootstrap_schema step and the schema-bootstrap timer unit — the heal path for a boot that lost the keeper race. Statements tagged "-- chinit:roles=..." for OTHER roles are skipped (the staging S3Queue + MV are writer/reader-only: the backup's IAM role cannot list staging).

type DiskRelief

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

DiskRelief relieves hot-disk space pressure when online volume growth is unavailable by moving the largest hot-disk partitions to the cold object-storage volume.

func NewDiskRelief

func NewDiskRelief(store port.HotPartitionStore, perPass int) *DiskRelief

NewDiskRelief builds the relief over a partition store. perPass <= 0 falls back to the default bound.

func (*DiskRelief) Relieve

func (r *DiskRelief) Relieve(ctx context.Context) (ReliefResult, error)

Relieve moves up to perPass partitions, biggest first. A move failure never aborts the pass — the steady-state TTL mover owns the retry either way. Returns the moved count (0 = no qualifying candidates; the caller decides whether that is terminal).

type Engine

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

Engine runs the ordered pipeline with state tracking, retries and the [TIMING] summary.

func NewEngine

func NewEngine(clock Clock, store StateStore) *Engine

NewEngine builds an engine. nil clock/store use the defaults.

func (*Engine) IdentityPersister

func (e *Engine) IdentityPersister(cloud string) func(model.NodeIdentity)

IdentityPersister returns a closure the boot's settle step calls the moment identity is settled: it merges the snapshot into the loaded state and saves immediately (a later crash must not lose it, and the job subcommands read the identity from the state file). No-op when the engine has no store (unit tests).

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, steps []Step) RunResult

Run executes the steps in order, honoring: resume (skip steps the state file records done), retries (each step's Policy), criticality (stop or continue), and the fatal-error short-circuit. A Critical failure aborts remaining steps; a BestEffort failure continues. A ParallelGroup runs its children concurrently (errgroup) with the same resume/criticality semantics per child.

func (*Engine) Since

func (e *Engine) Since(t time.Time) time.Duration

Since is the Clock's duration helper.

func (*Engine) WithIdentity

func (e *Engine) WithIdentity(identity *model.NodeIdentity, cloud, specHash string) *Engine

WithIdentity pins the settled-identity snapshot and the spec hash the run executes against (the boot sets both after the identity step; the state file carries them for the job subcommands and for resume invalidation).

func (*Engine) WithRefresh

func (e *Engine) WithRefresh(refresh bool) *Engine

WithRefresh switches the run to refresh semantics: every step re-executes (no resume-skip), the settle_identity step re-uses the persisted identity instead of re-claiming leases, and keeper raft state is preserved. The engine still records results (refresh outcomes are observable in the state file and [TIMING] output, and a fatal refresh failure leaves the node loud rather than silently half-applied).

type EnsembleSnapshot

type EnsembleSnapshot struct {
	// Members is the configured ensemble size.
	Members int
	// Synced is the count of live Raft participants per Keeper mntr.
	Synced int
}

EnsembleSnapshot captures live Raft state before a disrupt decision. Frozen on purpose (the controller does the same): never re-derive after the disrupt starts.

func (EnsembleSnapshot) SafeAfterDisrupt

func (s EnsembleSnapshot) SafeAfterDisrupt(targetSynced bool) bool

SafeAfterDisrupt reports whether the remaining synced members would still meet quorum if this host were disrupted. Re-extracted from the controller's ensembleQuorumSafeAfterDisrupt, with mntr synced-followers replacing STS ReadyReplicas as the live-count source.

type FatalError

type FatalError = fail.FatalError

FatalError aliases fail.FatalError, Fatal and IsFatal wrap errors into it (the leaf package the host-ops adapters also classify through); the aliases keep the engine's call sites short.

type FenceCapabilityError

type FenceCapabilityError struct {
	Hostname string
}

FenceCapabilityError names the missing-fence degradation: the node is quiesced but a human must replace it (no capability to mark the instance unhealthy).

func (*FenceCapabilityError) Error

func (e *FenceCapabilityError) Error() string

type FenceResult

type FenceResult struct {
	// QuiesceFailed marks the stop-serving statements as failed (the
	// fence still marks unhealthy — the node is exiting either way).
	QuiesceFailed bool
	// MarkedUnhealthy is true when the ASG accepted the health flip.
	MarkedUnhealthy bool
}

FenceResult reports the fence outcome: quiesced status and the terminal error (nil = the ASG will replace the instance).

type FileStateStore

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

FileStateStore persists the state file (engine records + identity snapshot). The model.StateFile shape is the on-disk contract.

func NewFileStateStore

func NewFileStateStore(path string) (*FileStateStore, error)

NewFileStateStore builds the store, creating the parent directory.

func (*FileStateStore) Load

func (s *FileStateStore) Load() (*modelState, error)

Load reads the state file; a missing file is an empty state (first boot), not an error.

func (*FileStateStore) Save

func (s *FileStateStore) Save(st *modelState) error

Save writes the state file atomically (tmp+rename: a crash mid-boot never leaves a truncated state the next run chokes on).

type FleetMetricsInput

type FleetMetricsInput struct {
	// Hostname labels every metric with the node's identity.
	Hostname string
	// Role is the node's role label.
	Role string
	// ClusterName is the cluster label (the alerting dimension).
	ClusterName string
	// Tasks is the fleet's task rows (all phases; the counters derive
	// per-phase).
	Tasks FleetTasks
	// Statuses is the fleet's status rows (health + cordon counters).
	Statuses NodeStatuses
	// CAS carries optional Altinity Antalya CAS mount and GC metrics.
	CAS CASMetrics
	// Now is the render clock (staleness gauges).
	Now time.Time
}

FleetMetricsInput is the renderer's data: the fleet view one render call consumes (the exporter service gathers it on each scrape; the CloudWatch bridge gathers it on its tick).

type FleetTaskExecutor

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

FleetTaskExecutor is the node-side half of the task layer: poll this node's OWN rows, claim a pending one, run its motion under a heartbeat, and write the epoch-fenced verdict. Pure orchestration over the store and the MotionRunner port — the subprocess shell, the drain-aware refresh, and every future motion are runner concerns.

func NewFleetTaskExecutor

func NewFleetTaskExecutor(store port.FleetTaskStore, runner port.MotionRunner, hostname string) (*FleetTaskExecutor, error)

NewFleetTaskExecutor builds the executor over its ports.

func (*FleetTaskExecutor) Poll

Poll is one tick: claim and run this node's pending task rows (one motion per tick — the verdict closes the row before the next).

The fail-safe rules:

  • a row in executing with a LIVE heartbeat is another process's motion — never touched (a stale one is the sweep's call, not the executor's);
  • a motion whose heartbeat is refused (the epoch moved) aborts: the stale executor never writes a verdict.

func (*FleetTaskExecutor) WithDisruptionGate

func (e *FleetTaskExecutor) WithDisruptionGate(gate port.DisruptionGate, role string) *FleetTaskExecutor

WithDisruptionGate wires the budget gate (optional: nil-gated is the degraded fleet's answer; the app layer logs the missing capability). The gate is consulted before the claim; a deferred verdict leaves the row pending — the next tick re-asks.

func (*FleetTaskExecutor) WithNow

func (e *FleetTaskExecutor) WithNow(f func() time.Time) *FleetTaskExecutor

WithNow injects the clock (the fencing specs).

type FleetTaskExecutorResult

type FleetTaskExecutorResult struct {
	// Claimed counts rows this poll claimed (0 = nothing to do).
	Claimed int
	// Completed counts motions that finished and wrote done.
	Completed int
	// Failed counts motions that failed and wrote failed.
	Failed int
}

FleetTaskExecutorResult reports one poll tick (the timer's journal line and the CLI's exit text).

type FleetTaskService

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

FleetTaskService runs the coordinator sweep over the task store.

func NewFleetTaskService

func NewFleetTaskService(store port.FleetTaskStore) (*FleetTaskService, error)

NewFleetTaskService builds the service over its port. Without it the fleet has no coordinator — the timer logs the missing capability and exits 0 (degradation is the factory's designed behavior, the same rule as the lease lister).

func (*FleetTaskService) Sweep

Sweep is one coordinator tick: list every task row, re-dispatch the stale ones, fail the exhausted ones. Idempotent — it re-derives the inventory from the table every tick and only acts on stale rows.

The fail-safe rules, per row:

  • a live-executing row (fresh heartbeat) is never touched;
  • a stale executing/ack row with retries remaining is re- dispatched (epoch+1 — the old executor is fenced off on its next write);
  • a stale row with NO retries remaining is failed (terminal; a human or a fresh submit decides the next move — the sweep never invents retries);
  • a transition refused by the CAS (another coordinator raced and won) is recorded in the result, never an error — the next tick sees the winner's decision.

func (*FleetTaskService) WithNow

func (s *FleetTaskService) WithNow(f func() time.Time) *FleetTaskService

WithNow injects the clock (the staleness specs).

type FleetTaskSweepResult

type FleetTaskSweepResult struct {
	// Rows is the inventory the sweep saw (all phases).
	Rows int
	// Redispatched counts rows the sweep re-dispatched (stale
	// heartbeat, retries remaining).
	Redispatched int
	// Failed counts rows the sweep moved to failed (stale heartbeat,
	// retries exhausted).
	Failed int
	// LeftPending counts rows awaiting their first claim (untouched).
	LeftPending int
	// LiveExecuting counts rows with a fresh heartbeat (untouched).
	LiveExecuting int
}

FleetTaskSweepResult reports one sweep tick's decisions (the CLI prints it; the exporter counts it).

type FleetTasks added in v0.2.0

type FleetTasks []port.FleetTask

FleetTasks is a domain collection of FleetTask rows.

type HealthCheck

type HealthCheck struct {
	// Name identifies the check: "server", "keeper", "replicas",
	// "tables", "self" (per-host server checks are aggregated under
	// "server" with the host in Detail; the JSON shape stays one entry
	// per check, not per host — scripts pin on the five names).
	Name string
	// Status is pass, fail or skip.
	Status string
	// Detail says what happened: pass — a short "what was verified";
	// fail — the offending host/table/replica plus the reason; skip
	// why the check did not run (which flag enables it).
	Detail string
}

HealthCheck is one check's outcome. Detail is human-oriented but stable enough for scripts to grep (table names, replica names, the error text).

type HealthReport

type HealthReport struct {
	// Status is "healthy" or "degraded".
	Status string
	// Checks is one entry per check, in execution order: server, keeper,
	// replicas, tables, self.
	Checks []HealthCheck
	// ExpectedTables carries the spec-derived expected table names for
	// the tables check (empty when -spec was not given).
	ExpectedTables []domain.TableRef
}

HealthReport is the full outcome of one health run.

func (*HealthReport) FormatHuman

func (r *HealthReport) FormatHuman() string

FormatHuman renders the runbook-pasteable output: one line per check (✓/✗/SKIP) and a summary line.

func (*HealthReport) Healthy

func (r *HealthReport) Healthy() bool

Healthy reports whether every executed check passed (skips don't count against health).

func (*HealthReport) ToJSONShape

func (r *HealthReport) ToJSONShape() JSONShape

ToJSONShape projects the report onto the stable wire form.

type HealthRequest

type HealthRequest struct {
	// ClusterName is the ClickHouse cluster name (clusterAllReplicas
	// fan-out; whitelisted against the CR by the adapter, same as
	// replica gc).
	ClusterName string
	// Hosts is the cluster inventory; the server check fans out over
	// every entry and reports each.
	Hosts []domain.HostIdentity
	// Credentials connect to the hosts.
	Credentials domain.Credentials
	// HTTPPort is the HTTP interface port (default 8123).
	HTTPPort int
	// Secure marks whether the cluster requires TLS.
	Secure bool
	// Timeout bounds one probe (default 5s).
	Timeout time.Duration
	// KeeperAddress, when non-empty, runs the keeper check against that
	// mntr endpoint. Empty skips the check.
	KeeperAddress string
	// CheckTables enables the tables-present check (the -spec flag).
	CheckTables bool
	// SelfName, when non-empty, runs the self-registration check for
	// that replica name. Empty skips the check. The check consumes the
	// replicas fan-out rows (cluster-wide, host_name tagged) — the
	// full inventory stays valid, no single-host requirement.
	SelfName string
}

HealthRequest is the input to HealthService.Check.

type HealthService

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

HealthService runs the stack's verification checks — the one command that gates boots, refreshes and runbooks, replacing the ad-hoc SQL + mntr snippets each of those carried. It composes two ports: the cluster health probe (server/replicas/tables/self SQL) and the keeper probe (mntr), both injected — the service itself carries no SQL and no driver types.

func NewHealthService

func NewHealthService(cluster port.ClusterHealthProbe, keeper port.KeeperProbe, expectedTables func() []domain.TableRef) *HealthService

NewHealthService builds the service over the probes and the expected-tables resolver.

func (*HealthService) Check

func (s *HealthService) Check(ctx context.Context, request HealthRequest) (*HealthReport, error)

Check runs every requested check and reports pass/fail/skip per check. A failing probe is a failed check — never an abort: a cluster health command must report the whole picture in one pass (the runbooks paste one output, not five partial runs).

The replicas rows are fetched once and shared by the replicas and self checks: both judge system.replicas state, and a second fan-out would double the query load for the same rows.

type HookIdentity

type HookIdentity struct {
	Role       string
	Hostname   string
	Cluster    string
	InstanceID string
}

HookIdentity is the environment the hook runs with: the node's own settled facts, never secrets (the hook resolves its own secrets the same way every other chinit component does — by name, over the instance role).

func (HookIdentity) Env

func (h HookIdentity) Env() []string

Env renders the identity as the hook's environment block.

type HookRunner

type HookRunner interface {
	// RunHook executes one hook's command under ctx and answers the
	// combined output. A non-nil error is the hook's failure.
	RunHook(ctx context.Context, hook model.Hook, identity HookIdentity) (string, error)
}

HookRunner runs one hook command. The production implementation shells `sh -c` with the identity environment; tests record.

type JSONCheckRow

type JSONCheckRow struct {
	Name   string `json:"name"`
	Status string `json:"status"`
	Detail string `json:"detail"`
}

JSONCheckRow is one check in the -json output.

type JSONShape

type JSONShape struct {
	Status string         `json:"status"`
	Checks []JSONCheckRow `json:"checks"`
}

JSONShape is the -json wire form: {"status":..., "checks":[{name, status, detail}...]}. A struct (not a map) so the key order is stable and scripts can pin on it.

type JSONSpanCursorStore added in v0.2.6

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

JSONSpanCursorStore implements port.SpanCursorStore over an atomic JSON file on the local filesystem.

func NewJSONSpanCursorStore added in v0.2.6

func NewJSONSpanCursorStore(path string) *JSONSpanCursorStore

NewJSONSpanCursorStore constructs a JSON-backed SpanCursorStore at path.

func (*JSONSpanCursorStore) LoadCursor added in v0.2.6

func (s *JSONSpanCursorStore) LoadCursor() (model.SpanCursor, bool, error)

LoadCursor reads the persisted SpanCursor, returning ok=false when no cursor file exists yet.

func (*JSONSpanCursorStore) SaveCursor added in v0.2.6

func (s *JSONSpanCursorStore) SaveCursor(cursor model.SpanCursor) error

SaveCursor atomically writes cursor as structured JSON.

type KeeperMntrService

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

KeeperMntrService fetches and formats a keeper's mntr payload — the tested replacement for hand-rolled `echo mntr | nc host 9181 | awk` parsing in node bootstrap and health scripts. It deliberately carries no quorum decision logic: `keeper safe-to-stop` does that; this command only reports what the ensemble member says.

func NewKeeperMntrService

func NewKeeperMntrService(probe port.KeeperProbe) *KeeperMntrService

NewKeeperMntrService builds the service over a probe.

func (*KeeperMntrService) Mntr

func (s *KeeperMntrService) Mntr(ctx context.Context, request MntrRequest) (MntrResult, error)

Mntr queries the mntr endpoint and returns the full parsed payload.

Why an error on empty: a keeper that answers with nothing is not answering mntr at all, and health scripts must read that as "keeper down" (exit 3), not as a healthy empty snapshot.

type KeeperSafetyService

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

KeeperSafetyService decides whether a keeper node may be stopped without dropping the ensemble below Raft quorum, using a KeeperProbe for live state. It is the off-cluster counterpart of the controller's ensureQuorumSafeToDisruptHost.

func NewKeeperSafetyService

func NewKeeperSafetyService(probe port.KeeperProbe) *KeeperSafetyService

NewKeeperSafetyService builds the service over a probe.

func (*KeeperSafetyService) SafeToStop

func (s *KeeperSafetyService) SafeToStop(ctx context.Context, request SafeToStopRequest) error

SafeToStop polls the ensemble until disrupting the target is safe, the wait budget is spent, or the context ends — mirroring the controller's ensureQuorumSafeToDisruptHost flow, refusals included: a disrupt that would break quorum is never allowed, only deferred.

type LeaseRecovery

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

LeaseRecovery handles lease renewal failures by attempting to re-claim the node's own ordinal slot with ExactOrdinal enabled, classifying the outcome as Reclaimed, Contested (held by a live replacement), or Renumbered.

func NewLeaseRecovery

func NewLeaseRecovery(claimer port.OrdinalClaimer, table string) *LeaseRecovery

NewLeaseRecovery builds the recovery over a claimer and the node's lease table.

func (*LeaseRecovery) Recover

func (r *LeaseRecovery) Recover(ctx context.Context, req port.ClaimRequest, ordinal int) (RecoveryOutcome, error)

Recover attempts the exact re-claim after a failed renewal. prefix and ordinal describe the node's own name; the ExactOrdinal claim never walks to another ordinal.

type MntrRequest

type MntrRequest struct {
	// KeeperAddress is the mntr endpoint (host:port).
	KeeperAddress string
}

MntrRequest is the input to KeeperMntrService.Mntr.

type MntrResult

type MntrResult struct {
	// Fields is the verbatim mntr key=value payload.
	Fields map[string]string
	// ServerState is zk_server_state ("leader"/"follower"/...).
	ServerState string
	// SyncedFollowers is zk_synced_followers (the leader's sync set
	// minus itself — the quorum gate's healthy input).
	SyncedFollowers int
	// VotingMembers is the configured voting membership size (the
	// probe's derivation; 0 when the payload omits it).
	VotingMembers int
}

MntrResult is the formatted output of KeeperMntrService.Mntr.

func (MntrResult) FormatJSON

func (r MntrResult) FormatJSON() (string, error)

FormatJSON renders the payload as one JSON object. encoding/json sorts map keys, so the output is deterministic without extra work.

func (MntrResult) FormatLines

func (r MntrResult) FormatLines() string

FormatLines renders the payload as `key=value` lines sorted by key deterministic output for scripts that grep a single field, exactly like the awk parsing it replaces.

type NodeStatuses added in v0.2.0

type NodeStatuses []port.NodeStatus

NodeStatuses is a domain collection of NodeStatus rows.

type OTelCollectorRenderer added in v0.2.6

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

OTelCollectorRenderer renders /etc/otelcol/config.yaml for logs, metrics (Prometheus scrape + local OTLP -> OTLP HTTP or Prometheus Remote Write), and traces (local OTLP -> OTLP HTTP / VictoriaTraces).

func NewOTelCollectorRenderer added in v0.2.6

func NewOTelCollectorRenderer(spec *model.BootSpec, hostname string, units []system.UnitFile) *OTelCollectorRenderer

NewOTelCollectorRenderer constructs a collector config renderer over the node's BootSpec, settled hostname, and role unit inventory.

func (*OTelCollectorRenderer) Render added in v0.2.6

func (r *OTelCollectorRenderer) Render() string

Render produces the complete OpenTelemetry Collector YAML document.

type ParallelGroup

type ParallelGroup struct {
	Children []Step
}

ParallelGroup is a Step that runs its children CONCURRENTLY and completes when every child has (the barrier). It exists because the boot's wall-clock poles are IO-bound and INDEPENDENT: the ordinal claim sweep (settle_identity) can legally wait out a predecessor's lease for many minutes while the bundle fetch, EBS attach and OS tuning all run — serializing them pays the sum instead of the max.

Criticality semantics inside a group: - ANY Critical child failing fails the group Criticalally and cancels the group's remaining children (a failed disk mount must not leave the node half-converged while TLS writes files). - A BestEffort child failing alone is recorded and the group succeeds — the same log-and-continue contract a standalone BestEffort step has. BestEffort children are NOT cancel-safe to skip: their work (monitoring, units) is orthogonal, and the serial engine never skipped them on a sibling's failure either.

Each child runs under ITS OWN retry Policy (the group adds no retry of its own), and state recording is per-child (a resume skips only the children that completed — the group re-runs the rest).

func (ParallelGroup) Criticality

func (g ParallelGroup) Criticality() Criticality

Criticality answers Critical when ANY child is Critical (a Critical child's failure must abort the boot, so the group must be able to convey it — see runGroup).

func (ParallelGroup) Name

func (g ParallelGroup) Name() string

Name reports the group's phase name ("phase: a|b|c" — the [TIMING] line and state file carry it; children keep their own names).

func (ParallelGroup) Policy

func (g ParallelGroup) Policy() Policy

Policy answers the default single-attempt policy: the group itself is a barrier, not an operation — retries belong to each child.

func (ParallelGroup) Run

func (g ParallelGroup) Run(ctx context.Context) error

Run is unreachable through the engine (the engine dispatches groups via the type assertion, never calling Run) but satisfies the Step interface so a group can nest inside steps slices and dry-run plans.

type PersistentEpoch added in v0.2.5

type PersistentEpoch struct {
	S3DataBucket string `json:"s3_data_bucket"`
	CasEnabled   bool   `json:"cas_enabled"`
}

PersistentEpoch captures the S3 bucket and storage-mode epoch that owns the local ClickHouse replica metadata on a persistent EBS volume.

type PersistentEpochReconciler added in v0.2.5

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

PersistentEpochReconciler protects persistent EBS nodes (such as backup-0) from bucket switches or non-CAS -> CAS downgrades that leave stale part stubs pointing to a vanished bucket (Code 499) or v1 packed metadata (Code 287).

func NewPersistentEpochReconciler added in v0.2.5

func NewPersistentEpochReconciler(store ClickHouseDataStore, stopServer func(context.Context)) *PersistentEpochReconciler

NewPersistentEpochReconciler constructs a reconciler over store and a stop callback.

func (*PersistentEpochReconciler) Reconcile added in v0.2.5

func (r *PersistentEpochReconciler) Reconcile(ctx context.Context, spec *model.BootSpec)

Reconcile resets local replica metadata (preserving /var/lib/clickhouse/uuid) whenever the active S3 bucket changes or a CAS backup replica carries legacy disks/s3/store residue, then persists the current epoch.

type Policy

type Policy struct {
	// Attempts is the max tries (0 → 1). Duration-bounded steps (the
	// claim sweep) set Attempts high and rely on Deadline.
	Attempts int
	// BaseDelay is the first retry delay; each subsequent delay grows by
	// Factor (0 → 2) up to MaxDelay (0 → 30s). Jitter spreads herd
	// restarts across an ASG.
	BaseDelay time.Duration
	MaxDelay  time.Duration
	Factor    float64
	// Deadline bounds the WHOLE operation including waits (0 → none).
	// Steps that must finish within a known window (the 2-minute spot
	// drain; the one-lease-window claim) set this.
	Deadline time.Duration
	// Sleep abstracts waiting so tests inject a fake clock. nil →
	// time.Sleep.
	Sleep func(d time.Duration)
}

Policy is one step's retry contract. Zero values mean "sane default"; only the knobs a step actually needs are set.

type QueueHealResult

type QueueHealResult struct {
	// StuckTables lists the tables the detection found past the
	// retry threshold (before any busy-skip gate).
	StuckTables []string
	// OrphanTables lists the tables with NO_REPLICA_HAS_PART queue
	// entries (the orphan-merge class — healed with SYNC only).
	OrphanTables []string
	// OrphanSynced lists the tables that received the orphan SYNC
	// heal.
	OrphanSynced []string
	// Restarted lists the tables that received SYSTEM RESTART REPLICA.
	Restarted []string
	// MergesRunning is the node's in-flight merge count at detection
	// time (the busy-skip gate's evidence).
	MergesRunning int
	// SkippedReason, when non-empty, names why no restart ran: the
	// busy-skip gate ("merges running") or an empty detection ("no
	// stuck entries").
	SkippedReason string
	// ReadonlyTables lists the read-only tables found (Keeper session
	// loss — the separate detection pass).
	ReadonlyTables []string
	// InitFailedTables lists the read-only tables whose queue never
	// started (the attach thread refused them — the
	// force_restore_data heal class, a different pass from the
	// session-loss readonly).
	InitFailedTables []string
	// Restored lists the tables that received the readonly heal
	// (RESTART REPLICA when the Keeper replica path is present,
	// RESTORE REPLICA when absent).
	Restored []string
	// SkippedHeals lists readonly tables whose Keeper-path probe
	// failed — the heal that would have been a guess is deferred to
	// the next pass.
	SkippedHeals []string
	// FailedTables lists tables whose restart or sync failed during this
	// pass; errors are contained per table so remaining tables still heal.
	FailedTables []string
}

QueueHealResult reports the queue-heal outcome: what was stuck, what was restarted, and why nothing happened when nothing happened.

type RecoveryOutcome

type RecoveryOutcome int

RecoveryOutcome is the verdict for one failed renewal.

const (
	// OutcomeReclaimed is the good ending: the node re-took its own name.
	OutcomeReclaimed RecoveryOutcome = iota
	// OutcomeContested is the split-brain ending: a live replacement
	// owns the name — the caller must fence.
	OutcomeContested
	// OutcomeRenumbered is the unrecoverable ending: the identity
	// would CHANGE — the caller must fail loudly.
	OutcomeRenumbered
	// OutcomeUnrecoverable is the input-problem ending (no ordinal in
	// the hostname, or the claim itself failed for an API reason) —
	// the caller surfaces the original error.
	OutcomeUnrecoverable
)

type ReliefResult

type ReliefResult struct {
	// Moved is the partitions sent to the cold volume.
	Moved int
	// Failures is the partitions whose move errored (the pass
	// continues past them; the next tick and the TTL mover both
	// retry).
	Failures int
}

ReliefResult reports what one pass moved.

type ReplacementGate

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

ReplacementGate checks whether another live instance already holds this node's ordinal slot in the claims table so a terminating instance's drain does not delete a replacement node's DNS record.

func NewReplacementGate

func NewReplacementGate(table string, lister port.LeaseLister) *ReplacementGate

NewReplacementGate builds the gate over a live-claims lister. A nil lister (or empty table) is the documented degradation: the gate answers NOT-replaced and the ExactOnly delete remains the only guard.

func (*ReplacementGate) ReplacedBy

func (g *ReplacementGate) ReplacedBy(ctx context.Context, hostname, ownInstanceID string) (string, bool)

ReplacedBy answers whether another live instance holds the named slot. An unreadable claims table answers NOT-replaced: the drain proceeds (the record delete is ExactOnly — a live replacement's value survives either way).

type ReplicaGcResult

type ReplicaGcResult struct {
	// Stale is every stale host name found (before pattern filtering).
	Stale []string
	// Dropped is every host whose registration was removed successfully.
	Dropped []string
	// Failed is every host whose drop errored (already removed from
	// Dropped).
	Failed []string
}

ReplicaGcResult reports the outcome of a GC sweep so the CLI can print the TSV list and the human summary from one pass.

type RolloutInput

type RolloutInput struct {
	// TargetVersion is the version a replacement must report (the
	// new AMI's ClickHouse; the version gate's authority).
	TargetVersion string
	// Statuses is the fleet's status rows.
	Statuses []port.NodeStatus
	// Tasks is the fleet's outstanding task rows (the rollout's own
	// dispatch residue; the coordinator never double-dispatches).
	Tasks []port.FleetTask
	// Role filters the nodes this rollout governs ("writer" or
	// "reader"); other roles' rows are ignored.
	Role string
}

RolloutInput is the coordinator tick's fleet view.

type RolloutProgress

type RolloutProgress struct {
	// Hostname is the node's cluster identity.
	Hostname string
	// OnTarget reports whether the node's status row shows the target
	// version (a replacement that booted the new AMI).
	OnTarget bool
	// Version is the node's reported ClickHouse version.
	Version string
	// Cordoned excludes the node from this rollout's dispatch (the
	// operator owns it mid-maintenance).
	Cordoned bool
	// HasTask reports an outstanding rollout task row for the node.
	HasTask bool
}

RolloutProgress is the coordinator's answer for one node's place in the rollout (the tick's decision input and the CLI's report).

type RolloutState

type RolloutState struct {
	// Nodes is the per-node progress (sorted by hostname).
	Nodes []RolloutProgress
	// Complete is true when every non-cordoned node reports the target.
	Complete bool
}

RolloutState is the fleet's rollout position over the status rows.

func EvaluateRollout

func EvaluateRollout(in RolloutInput) RolloutState

EvaluateRollout derives the rollout state and the next node to dispatch. Pure: the caller (the coordinator CLI) submits the task row; this function only decides.

The sequencing rules (the operator's rollout parity):

  • one outstanding rollout task at a time fleet-wide (the previous node's verdict gates the next dispatch);
  • cordoned nodes are skipped (the operator owns them) but do not block the rest;
  • a node already on the target version needs no dispatch;
  • the lowest-ordinal off-target node is next (deterministic order).

type RunResult

type RunResult struct {
	Steps      []StepOutcome
	Fatality   error // the Critical failure, if any
	StartedAt  time.Time
	FinishedAt time.Time
}

RunResult is the pipeline outcome: every step's status and whether the boot overall succeeded.

func (RunResult) FatalityStep

func (r RunResult) FatalityStep() string

FatalityStep returns the name of the step whose Critical failure aborted the run ("" when the run completed).

type SafeToStopRequest

type SafeToStopRequest struct {
	// KeeperAddress is the mntr endpoint of the leader or any voting
	// member.
	KeeperAddress string
	// Members is the configured ensemble size (defaults to the mntr
	// voting membership when zero).
	Members int
	// TargetIsSynced marks whether the node being disrupted is currently a
	// synced participant (removing an unsynced node cannot break quorum).
	TargetIsSynced bool
	// PollInterval bounds the wait loop (default 5s).
	PollInterval time.Duration
	// WaitTimeout bounds the total wait (default 2m).
	WaitTimeout time.Duration
}

SafeToStopRequest is the input to SafeToStop.

type SchemaRequest

type SchemaRequest struct {
	// ClusterName is the ClickHouse cluster name (remote_servers naming).
	ClusterName string
	// Credentials connect to the target hosts.
	Credentials domain.Credentials
	// Hosts is the cluster inventory (operations address hosts by Name).
	Hosts []domain.HostIdentity
	// HTTPPort is the HTTP interface port (default 8123).
	HTTPPort int
	// Secure marks whether the cluster requires TLS connections.
	Secure bool
	// NormalizedCR is the SpecLoader's CHI output. Required: the operator
	// schemer names replicas by walking the CR's cluster/shard tree, and
	// hand-built Host values panic in its namer.
	NormalizedCR any
}

SchemaRequest binds a schema operation to one cluster context.

type SchemaService

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

SchemaService orchestrates schema/replica operations via a SchemaRunner factory.

func NewSchemaService

func NewSchemaService(factory port.SchemaClientFactory) *SchemaService

NewSchemaService builds the service over a runner factory.

func (*SchemaService) DropReplica

func (s *SchemaService) DropReplica(ctx context.Context, request SchemaRequest, drop domain.ReplicaDropRequest) error

DropReplica removes a dead replica's Keeper registration via a live peer (HostDropReplica — SYSTEM DROP REPLICA).

func (*SchemaService) GcReplica

GcReplica detects stale replica registrations on a peer and drops them in one pass — the dead-replica GC that replaced the weekly bash timer on the AWS stack.

The pattern gate is applied here, not in SQL: detection stays a simple query (stays easy to reason about), and the eligibility rule lives in one place the CLI documents. A host that does not match is reported as stale but never dropped. The exclude list is the caller's second gate (chinit's writer pass excludes hosts with live ordinal leases): an excluded host is reported as stale but skipped at drop time — the sweep stays visible while the liveness override wins.

Drop failures are logged per-host and do not abort the sweep — one flaky replica must not shield the rest from cleanup. The caller is expected to exit non-zero when Failed is non-empty.

func (*SchemaService) QueueHeal

QueueHeal detects and recovers a node's blocked replication queue: entries past the retry threshold with the merge pool idle receive SYSTEM RESTART REPLICA per stuck table followed by SyncReplica.

func (*SchemaService) SyncReplica

func (s *SchemaService) SyncReplica(ctx context.Context, request SchemaRequest, sync domain.ReplicaSyncRequest) error

SyncReplica re-queues replication on a restarted node (HostSyncTables — SYSTEM SYNC REPLICA).

func (*SchemaService) SyncSchema

func (s *SchemaService) SyncSchema(ctx context.Context, request SchemaRequest, sync domain.SchemaSyncRequest) error

SyncSchema creates all schema objects on a target host from cluster peers — the new-reader boot case (HostCreateTables).

Retries: up to sync.Retries full create passes (0 = DefaultSchemaSyncRetries), stopping early on the first clean pass. The operator's ExecHost retry re-runs failed SQLs, but ordering across a fresh pass is not guaranteed the retry loop makes the second pass deterministic instead of relying on a manual re-run.

PruneStaleSelf: when a pass fails with Code 253 (the target's replica registration already exists in Keeper — an ASG/VMSS replacement node re-claiming an ordinal whose dead predecessor left a PERSISTENT znode), the service runs the DropReplica pair for the failed registration and continues the loop. The drop name comes from the error the pass reported; the runner's DropReplica refuses any name not in the inventory, and the flag is opt-in (default false). Unflagged, the 253 error returns immediately with the flag named — every retry would hit the same znode, so a retry would only burn a pass.

Non-253 failures retry through every pass: the MV whose TO-target lands later in the batch is what the NEXT pass fixes.

Without the retry loop: a single-pass failure leaves the node schemaless until a human re-runs the command . Without PruneStaleSelf: a recycled ordinal cannot recover its own registration at all — CREATE and the auto-ATTACH fallback both fail on a fresh disk, and only a manual `replica drop` on a peer unblocks it.

func (*SchemaService) WithForceRestoreFlagger

func (s *SchemaService) WithForceRestoreFlagger(f port.ForceRestoreFlagger) *SchemaService

WithForceRestoreFlagger binds the keeper znode capability (the init-FAILED readonly heal's transport). Optional: without it the init-failed pass reports but cannot heal.

type SelfFenceService

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

SelfFenceService retires an identity-contested node when another live instance holds its ordinal slot: it quiesces local replication and marks the instance unhealthy so the Auto Scaling Group replaces it.

func NewSelfFenceService

func NewSelfFenceService(quiescer port.NodeQuiescer, fencer port.InstanceFencer) *SelfFenceService

NewSelfFenceService builds the fence over its two capabilities.

func (*SelfFenceService) Fence

func (s *SelfFenceService) Fence(ctx context.Context, hostname, instanceID string) (FenceResult, error)

Fence runs the retire sequence: quiesce, then mark unhealthy.

type ShellHookRunner

type ShellHookRunner struct{}

ShellHookRunner is the production runner: `sh -c` with the identity env, bounded by the hook's timeout.

func (ShellHookRunner) RunHook

func (ShellHookRunner) RunHook(ctx context.Context, hook model.Hook, identity HookIdentity) (string, error)

RunHook implements HookRunner.

type SpanShipRequest added in v0.2.6

type SpanShipRequest struct {
	Cluster  string
	Role     model.Role
	Hostname string
	Cloud    string
	Region   string
}

SpanShipRequest carries the node identity dimensions for one pass.

type SpanShipResult added in v0.2.6

type SpanShipResult struct {
	Exported        int
	HighWaterMicros uint64
	SkippedReason   string
}

SpanShipResult reports the outcome of one SpanShipper.Ship pass.

type SpanShipper added in v0.2.6

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

SpanShipper is the domain service that incrementally reads finished spans from ClickHouse's system.opentelemetry_span_log, exports them through port.SpanSink, and advances the persisted SpanCursor only after export succeeds (at-least-once delivery).

func NewSpanShipper added in v0.2.6

func NewSpanShipper(deps SpanShipperDeps) *SpanShipper

NewSpanShipper constructs a SpanShipper with defaults for zero bounds.

func (*SpanShipper) Ship added in v0.2.6

Ship executes one incremental span-forwarding pass.

type SpanShipperDeps added in v0.2.6

type SpanShipperDeps struct {
	Reader          port.SpanLogReader
	Cursors         port.SpanCursorStore
	Sink            port.SpanSink
	Clock           Clock
	BatchLimit      int
	InitialLookback time.Duration
}

SpanShipperDeps bundles the ports and policy bounds for SpanShipper.

type StateStore

type StateStore interface {
	Load() (*modelState, error)
	Save(st *modelState) error
}

StateStore persists the boot state file.

type Step

type Step interface {
	// Name is the step identity in the state file and [TIMING] output.
	Name() string
	// Criticality declares the failure semantics.
	Criticality() Criticality
	// Policy is the retry contract for the step's operations.
	Policy() Policy
	// Run executes the step once (retries wrap it).
	Run(ctx context.Context) error
}

Step is one convergent boot operation. Steps probe real state before acting (idempotent), so a re-run resumes.

func StepFunc

func StepFunc(name string, crit Criticality, policy Policy, run func(ctx context.Context) error) Step

StepFunc adapts a function to Step. Most steps are closures over the spec, provider and host; the struct form is reserved for steps that need their own state.

type StepOutcome

type StepOutcome struct {
	Name      string
	Crit      Criticality
	StartedAt time.Time
	Duration  time.Duration
	Err       error
	Skipped   bool
}

StepOutcome is one step's engine-level result.

func (StepOutcome) Failed

func (o StepOutcome) Failed() bool

Failed reports whether the step failed (BestEffort failures included: the summary must surface them even though the boot continued).

type StorageLossVerdict

type StorageLossVerdict struct {
	// StorageLoss is true when the node's condition matches: a data
	// directory that carries no parts while its replica name holds
	// Keeper registrations.
	StorageLoss bool
	// DataDir is the inspected directory (diagnostics).
	DataDir string
	// Reason carries the evidence (the journal line; empty when no
	// loss).
	Reason string
}

StorageLossVerdict is the detector's answer.

func DetectStorageLoss

func DetectStorageLoss(dataDir string, registeredReplicas []string) (StorageLossVerdict, error)

DetectStorageLoss answers the boot's storage-loss check. Pure over the inputs (the caller gathers the facts; the detector never touches ClickHouse — the DDL pass's Code 253 conflict-retry owns the actual drop-then-recreate, and the replica-sync timer owns the catch-up).

The facts:

  • dataDir: the mounted data directory (the metadata-disk store path); the walk counts ClickHouse part directories ("data_*" under any table path) — zero parts + zero detached = empty;
  • registeredReplicas: the node's OWN replica names found in system.replicas (gathered by the caller over the local port, BEFORE the schema pass would create anything).

The verdict: StorageLoss = an empty data dir AND existing registrations — the re-image/replacement case the operator handles via its migration path. An empty dir with NO registrations is a fresh node (the normal first boot); a populated dir with registrations is the healthy case; a populated dir with NO registrations is the re-attach case (the replica-sync/restore path heals it, not this detector).

Directories

Path Synopsis
Package conformance provides a reusable test suite that verifies cloud Provider implementations against chinit's mandatory and optional capability contracts.
Package conformance provides a reusable test suite that verifies cloud Provider implementations against chinit's mandatory and optional capability contracts.

Jump to

Keyboard shortcuts

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