Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 6 additions & 14 deletions cmd/partforge/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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},
Expand Down Expand Up @@ -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 {
Expand Down
13 changes: 0 additions & 13 deletions cmd/partforge/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 2 additions & 2 deletions docs/postgres.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<state-table>_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 `<state-table>_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.

Expand Down
2 changes: 1 addition & 1 deletion docs/rewrite-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 3 additions & 4 deletions internal/state/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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))
Expand Down
29 changes: 28 additions & 1 deletion internal/state/postgres_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
Expand Down
Loading