From 17832cb3d309d04124ea43a3b2c6f86d51a13126 Mon Sep 17 00:00:00 2001 From: Rory Shanks Date: Mon, 16 Nov 2026 10:08:34 +0000 Subject: [PATCH] Release stale compaction claims by heartbeat, not claim time compact_stale_at was the claim time, so a dead compactor held its COMPACTING rows, and blocked finalization of their partitions, until the compact window (24h) passed since the claim. Heartbeats now move compact_stale_at, and maintenance releases rows whose last heartbeat is older than 5 minutes. The compact window still caps live batches in the worker. Co-Authored-By: Claude Opus 5.5 --- cmd/partforge/main.go | 20 +++++--------- cmd/partforge/main_test.go | 13 --------- docs/operations.md | 2 +- docs/postgres.md | 4 +-- docs/rewrite-flow.md | 2 +- internal/state/postgres.go | 7 +++-- internal/state/postgres_integration_test.go | 29 ++++++++++++++++++++- 7 files changed, 41 insertions(+), 36 deletions(-) diff --git a/cmd/partforge/main.go b/cmd/partforge/main.go index af32401..ece527c 100644 --- a/cmd/partforge/main.go +++ b/cmd/partforge/main.go @@ -54,6 +54,10 @@ const defaultCompactWindow = 24 * time.Hour const defaultCompactMaxArtifacts = 20 const defaultCompactMaxBytes uint64 = 150 * 1024 * 1024 * 1024 const compactSourceMergeWaitCap = 5 * time.Minute +const compactHeartbeatInterval = 5 * time.Second + +// A COMPACTING row whose last heartbeat is older than this belongs to a dead worker. +const compactLeaseTimeout = 5 * time.Minute const compactMergeBackgroundPoolSize = 1 const compactMergeConcurrencyRatio = 1.0 const maxBackupChainDepth = 100 @@ -1964,8 +1968,6 @@ func runWorker(ctx context.Context, args []string) error { return fmt.Errorf("derive clickhouse merge settings: %w", err) } sourceMergeMaxRuntime := sourceMergeWaitMaxRuntime(*mergeMaxRuntime, roleSettings.SourceMergeCompactCap) - compactStaleAfter := compactLeaseStaleAfter(*compactWindow) - compactHeartbeatInterval := 5 * time.Second slog.Info( "configured clickhouse resource settings", "cpus", workerLimits.CPUs, @@ -1992,7 +1994,7 @@ func runWorker(ctx context.Context, args []string) error { "compact_merge_timeout", rewrite.DefaultCompactMergeTimeout, "compact_merge_max_timeout", *compactWindow, "compact_merge_settle_min_wait", rewrite.DefaultCompactMergeSettleMinWait, - "compact_lease_stale_after", compactStaleAfter, + "compact_lease_timeout", compactLeaseTimeout, "compact_heartbeat_interval", compactHeartbeatInterval, "compact_max_artifacts", *compactMaxArtifacts, "compact_max_bytes", *compactMaxBytes, @@ -2062,7 +2064,7 @@ func runWorker(ctx context.Context, args []string) error { MergeSelectingSleepMS: mergeTreeSettings.MergeSelectingSleepMS, MergePoolFreeEntriesThreshold: mergeTreeSettings.PoolFreeEntriesThreshold, CompactWindow: *compactWindow, - CompactLeaseStaleAfter: compactStaleAfter, + CompactLeaseStaleAfter: compactLeaseTimeout, CompactHeartbeatInterval: compactHeartbeatInterval, CompactProgressInterval: *stateProgressInterval, CompactBatching: state.CompactBatching{MaxArtifacts: *compactMaxArtifacts, MaxBytes: *compactMaxBytes}, @@ -2817,16 +2819,6 @@ func sourceMergeWaitMaxRuntime(maxRuntime time.Duration, compactEnabled bool) ti return maxRuntime } -func compactLeaseStaleAfter(compactWindow time.Duration) time.Duration { - if compactWindow <= 0 { - return 5 * time.Minute - } - if compactWindow < 5*time.Minute { - return 5 * time.Minute - } - return compactWindow -} - func compactClaimSplay(compactWindow time.Duration) time.Duration { maxDelay := compactClaimSplayMax(compactWindow) if maxDelay <= 0 { diff --git a/cmd/partforge/main_test.go b/cmd/partforge/main_test.go index 19006d5..c6368d2 100644 --- a/cmd/partforge/main_test.go +++ b/cmd/partforge/main_test.go @@ -1193,19 +1193,6 @@ func TestCompactBatchDeadlineDisabledForZeroWindow(t *testing.T) { } } -func TestCompactLeaseTimingDerivedFromCompactWindow(t *testing.T) { - staleAfter := compactLeaseStaleAfter(2 * time.Hour) - if staleAfter != 2*time.Hour { - t.Fatalf("compactLeaseStaleAfter = %s, want 2h", staleAfter) - } - if got := compactLeaseStaleAfter(time.Minute); got != 5*time.Minute { - t.Fatalf("compactLeaseStaleAfter short window = %s, want 5m floor", got) - } - if got := compactLeaseStaleAfter(0); got != 5*time.Minute { - t.Fatalf("compactLeaseStaleAfter zero window = %s, want 5m floor", got) - } -} - func TestSourceMergeWaitMaxRuntimeCapsWhenCompactEnabled(t *testing.T) { if maxRuntime := sourceMergeWaitMaxRuntime(2*time.Hour, true); maxRuntime != compactSourceMergeWaitCap { t.Fatalf("source merge max runtime = %s, want %s", maxRuntime, compactSourceMergeWaitCap) diff --git a/docs/operations.md b/docs/operations.md index ade3423..19b7128 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -129,4 +129,4 @@ Notes: ## Shutdown behavior -On `SIGINT`/`SIGTERM` a worker stops claiming new work immediately. An active insert is canceled and its part returned to `READY`. Active compaction stops waiting for more merge progress, then uploads its output only if it reduced the physical part count, otherwise releases the batch back to `COMPACT_READY`. If a worker process dies outside handled code, the part stays visible as `IN_PROGRESS` or `COMPACTING` for manual inspection or reset (`set-part-state` / `retry-failed -include-in-progress`). +On `SIGINT`/`SIGTERM` a worker stops claiming new work immediately. An active insert is canceled and its part returned to `READY`. Active compaction stops waiting for more merge progress, then uploads its output only if it reduced the physical part count, otherwise releases the batch back to `COMPACT_READY`. If a worker process dies outside handled code, an `IN_PROGRESS` part stays visible for manual inspection or reset (`set-part-state` / `retry-failed -include-in-progress`). A `COMPACTING` batch returns to `COMPACT_READY` once its last heartbeat is more than 5 minutes old. diff --git a/docs/postgres.md b/docs/postgres.md index 01869dc..19d3604 100644 --- a/docs/postgres.md +++ b/docs/postgres.md @@ -51,14 +51,14 @@ The original primary key `(job_id, part_id)`, state columns, and full `data` JSO | `compact_bytes` | Persisted compact data size used for claim metadata and diagnostics | | `compact_normalized` | Identify artifacts containing one physical part | | `compact_partition_id` | Generated from `data` for normalized artifacts; groups sibling artifacts for batch claims | -| `compact_stale_at` | Indexed stale-compaction lookup, preserving the existing earlier-of-heartbeat-and-claim timeout | +| `compact_stale_at` | Indexed stale-compaction lookup: the last heartbeat of a `COMPACTING` row | | `original_compact_ready_at` | Indexed job compact deadline lookup | Application writes update these projections in the same SQL statement as the JSON or status change. No triggers are installed. Use PartForge commands for state changes; direct SQL must maintain the corresponding derived columns too. The full Part record remains in `data`; no job metadata or progress table is required. Compactors claim the most-fragmented eligible unlocked artifact, using its physical ClickHouse part count. Job, destination, and explicit partition filters still apply; partitions with an active compactor are no longer deprioritized. -A single `_maintenance` record reserves compaction maintenance once every ten seconds across the worker fleet. `worker -once` requests an immediate pass but still skips a pass already in progress. Only the reservation holder scans job summaries and expires stale work. The reservation commits with the work, and active maintenance is skipped by other workers without waiting. Workers sharing a state table should use the same compact-window and stale-timeout settings. New finalizable output can wait up to the next maintenance pass; a long maintenance run or database contention can extend that delay. +A single `_maintenance` record reserves compaction maintenance once every ten seconds across the worker fleet. `worker -once` requests an immediate pass but still skips a pass already in progress. Only the reservation holder scans job summaries and expires stale work. The reservation commits with the work, and active maintenance is skipped by other workers without waiting. Workers sharing a state table should use the same compact-window setting. New finalizable output can wait up to the next maintenance pass; a long maintenance run or database contention can extend that delay. Rewrite progress combines live query counters and stage timing in one periodic heartbeat. Rewrite and compact progress updates use conditional SQL patches that check worker ownership. A failed rewrite heartbeat cancels processing and surfaces the error. diff --git a/docs/rewrite-flow.md b/docs/rewrite-flow.md index 1d4cbfe..7fe8a2d 100644 --- a/docs/rewrite-flow.md +++ b/docs/rewrite-flow.md @@ -133,7 +133,7 @@ The compactor downloads and attaches the claimed artifact before starting the me The compact output is uploaded only if the final active output part count is lower than the active input part count. If compaction does not reduce the count, the worker releases the input back to `COMPACT_READY`. The job-wide finalization window starts when the last original source artifact finishes rewriting. All compact batches use that same deadline, and successful compact outputs inherit the input compact-ready timestamp. -Live compaction workers heartbeat their claimed `COMPACTING` rows. An independent observer polls `system.parts` and `system.merges` every 5 seconds after merge tuning starts. It publishes each current ClickHouse merge and per-partition input/current part shape to Prometheus, and persists the aggregate stage, active merge count, byte-weighted current merge-wave progress, and current physical part count at `-state-progress-interval`. Observation or progress-write failures cancel and release the batch rather than leaving an apparently healthy stale status. Before claiming more compaction work, workers release `COMPACTING` rows whose heartbeat is stale for the derived lease timeout, currently `-compact-window` with a 5 minute floor. Once a job's compact window has expired, workers stop claiming new compact work for that job. Claimed compaction batches use the same compact-window deadline; when it is reached, including during fragmented-input normalization, the worker measures the current output and uploads it if the active part count was reduced, otherwise it finishes the input as it is. Remaining compact-ready artifacts are promoted to `FINISHED` once there is no source work, in-progress rewrite, failed work, or active non-stale compaction for that job. Single-part artifacts follow the batching finalization rule above. +Live compaction workers heartbeat their claimed `COMPACTING` rows. An independent observer polls `system.parts` and `system.merges` every 5 seconds after merge tuning starts. It publishes each current ClickHouse merge and per-partition input/current part shape to Prometheus, and persists the aggregate stage, active merge count, byte-weighted current merge-wave progress, and current physical part count at `-state-progress-interval`. Observation or progress-write failures cancel and release the batch rather than leaving an apparently healthy stale status. Workers heartbeat every 5 seconds. Compaction maintenance releases `COMPACTING` rows whose last heartbeat is more than 5 minutes old, so a dead worker's batch returns to `COMPACT_READY` within about 5 minutes. The `-compact-window` deadline caps a live batch separately. Once a job's compact window has expired, workers stop claiming new compact work for that job. Claimed compaction batches use the same compact-window deadline; when it is reached, including during fragmented-input normalization, the worker measures the current output and uploads it if the active part count was reduced, otherwise it finishes the input as it is. Remaining compact-ready artifacts are promoted to `FINISHED` once there is no source work, in-progress rewrite, failed work, or active non-stale compaction for that job. Single-part artifacts follow the batching finalization rule above. `job-status` physical part counters refer to ClickHouse parts, not PartForge state rows. Source rows count the attached source part or persisted rewritten destination part count. Compact rows count the physical destination parts that fed that compact output. Live `COMPACTING` rows report the physical parts actually attached into the local compact table as input and the latest active local ClickHouse parts as output while merges are still running. The compact summary reports finalization blockers and ETA, followed by one row per active compacting batch with its sub-stage and current merge-wave progress; `job-status -parts -json` also exposes the persisted compact fields on each claimed input row. diff --git a/internal/state/postgres.go b/internal/state/postgres.go index 998f046..059dc82 100644 --- a/internal/state/postgres.go +++ b/internal/state/postgres.go @@ -480,9 +480,8 @@ func partWriteValues(part Part) ([]any, error) { if err != nil { return nil, fmt.Errorf("compact time for %s/%s: %w", part.JobID, part.PartID, err) } - if staleAt == nil || parsed.Before(*staleAt) { - staleAt = &parsed - } + staleAt = &parsed + break } if staleAt == nil { return nil, fmt.Errorf("compacting part %s/%s has no updated_at or compacting_at", part.JobID, part.PartID) @@ -991,7 +990,7 @@ func (s *Store) HeartbeatCompactBatch(ctx context.Context, batch CompactBatch, w func (s *Store) updateCompactProgress(ctx context.Context, part Part, workerID string, patch []byte, now time.Time) (bool, error) { var requested bool err := s.pool.QueryRow(ctx, `UPDATE `+s.tableSQL+` SET status = 'COMPACTING', worker_id = $1, updated_at = $2, - compact_stale_at = LEAST($2::text::timestamptz, COALESCE(NULLIF(btrim(data->>'compacting_at'), '')::timestamptz, $2::text::timestamptz)), + compact_stale_at = $2::text::timestamptz, data = (data - 'error' - 'compact_cooldown_until') || $3::jsonb || jsonb_build_object('status', 'COMPACTING', 'worker_id', $1::text, 'updated_at', $2::text, 'compacting_at', COALESCE(NULLIF(btrim(data->>'compacting_at'), ''), $2::text)) diff --git a/internal/state/postgres_integration_test.go b/internal/state/postgres_integration_test.go index 6a1d66c..9adc57f 100644 --- a/internal/state/postgres_integration_test.go +++ b/internal/state/postgres_integration_test.go @@ -605,6 +605,33 @@ func TestPostgresCompactOptionsAndSummaries(t *testing.T) { } } +func TestPostgresCompactLeaseFollowsHeartbeat(t *testing.T) { + ctx := context.Background() + s := postgresTestStore(t) + now := time.Now().UTC().Truncate(time.Microsecond) + part := NewPart("job", "part", "bucket", "source", "finished", now) + part.Status = StatusCompactReady + part.CompactReadyAt = formatTime(now) + part.DestinationDatabase, part.DestinationTable, part.DestinationSchema = "db", "table", "schema" + part.DestinationActivePartCount = 2 + part.DestinationActivePartitionCounts = map[string]uint64{"p": 2} + seedPostgresParts(t, s, []Part{part}) + batch, err := s.ClaimNextCompactBatch(ctx, "worker", now, CompactClaimOptions{}) + if err != nil || batch == nil { + t.Fatalf("claim = %+v, %v", batch, err) + } + heartbeat := now.Add(time.Hour) + if _, err := s.HeartbeatCompactBatch(ctx, *batch, "worker", heartbeat); err != nil { + t.Fatal(err) + } + if n, err := s.ReleaseStaleCompactingParts(ctx, heartbeat.Add(4*time.Minute), 5*time.Minute); err != nil || n != 0 { + t.Fatalf("released a claim with a recent heartbeat: %d %v", n, err) + } + if n, err := s.ReleaseStaleCompactingParts(ctx, heartbeat.Add(5*time.Minute), 5*time.Minute); err != nil || n != 1 { + t.Fatalf("stale release after missed heartbeats = %d, %v", n, err) + } +} + func TestPostgresManualCompactFinalization(t *testing.T) { for _, action := range []string{"ready", "release", "complete", "stale-release", "finished"} { t.Run(action, func(t *testing.T) { @@ -835,7 +862,7 @@ func assertSchedulingColumns(t testing.TB, s *Store) { COALESCE((data->>'destination_active_part_count')::numeric, 0) = 1 AND (SELECT count(*) = 1 AND COALESCE(bool_and(p.value::numeric = 1), false) FROM jsonb_each_text(COALESCE(NULLIF(data->'destination_active_partition_counts', 'null'::jsonb), '{}'::jsonb)) p WHERE btrim(p.key) <> '' AND p.value::numeric > 0)) OR - compact_stale_at IS DISTINCT FROM (CASE WHEN status = 'COMPACTING' THEN LEAST(NULLIF(updated_at, '')::timestamptz, NULLIF(data->>'compacting_at', '')::timestamptz) END) OR + compact_stale_at IS DISTINCT FROM (CASE WHEN status = 'COMPACTING' THEN COALESCE(NULLIF(updated_at, '')::timestamptz, NULLIF(data->>'compacting_at', '')::timestamptz) END) OR original_compact_ready_at IS DISTINCT FROM (CASE WHEN COALESCE((data->>'compact_generation')::int, 0) <= 0 AND jsonb_array_length(COALESCE(NULLIF(data->'compact_input_part_ids', 'null'::jsonb), '[]'::jsonb)) = 0 THEN NULLIF(data->>'compact_ready_at', '')::timestamptz END)`).Scan(&mismatches) if err != nil { t.Fatal(err)