Skip to content

🐛 fix(sink/git,controller): prune multipart git exports once against the union (REL-GIT-MULTIPART) - #183

Merged
konih merged 2 commits into
mainfrom
fix/rel-git-multipart-prune-union
Aug 3, 2026
Merged

konih merged 2 commits into
mainfrom
fix/rel-git-multipart-prune-union

Conversation

@konih

@konih konih commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Bug: silent data loss in multipart Git-sink exports

For perResource/split git layouts the controller writes a sharded export part-by-part, calling sink.RunExportEnvelope once per part. Each call pruned directory-scoped with a keep-set of only that part's files, so part 2's prune deleted part 1's files — last-part-wins silent data loss.

Root cause: git PRUNE, not path collision

Every part projects into the same generation directory. The item path template {cluster}/{sourceNamespace}/{kind}/{sourceName} has no inventory-name component, so the .part-NNNN-of-NNNN object-path suffix never separates parts on disk — they collide in one dir and per-part prune erases siblings. (A prior implementer empirically disproved the path-collision theory; unique-per-part paths are not the fix.) Document layout (prune=false) is safe and untouched.

Fix invariant

For a multipart set, prune runs EXACTLY ONCE, against the UNION of all parts' projected paths, on the final part — never per-part.

Seam: passed-in accumulator (sink.PrunePlan)

  • Additive PrunePlan *PrunePlan on ExportEnvelopeRequest. Both controllers create one when len(parts) > 1 and share it across the sink's parts (per-job, inside the export goroutine).
  • resolveSnapshotExport records each part's projected paths, and for a prune-bearing layout:
    • non-final part → SuppressPrune (prune skipped)
    • final part → prune with PruneKeepPaths = union of all parts
  • Parts commit+push sequentially onto the same branch, so the final part's workdir already holds parts 1..N-1; keeping the union preserves prior parts while genuinely-stale (previous-generation) files — absent from the union — are still deleted.

Fail-safe & backward-compat guard

  • Fail-safe: a multipart set with no accumulator suppresses prune entirely rather than risk a per-part prune.
  • Backward-compat guard (the single most important one): a nil/empty PruneKeepPaths keeps the legacy keep-set (= paths written this call). Single-part exports, non-git sinks (S3/GCS/Postgres/Kafka), and document mode are byte-for-byte untouched.
  • SuppressPrune additionally overrides an explicit spec.git.prune=true, so suppression holds even when the sink-level prune flag is set.

git/gitlab ExportFiles now take ExportFilesOptions{Prune, PruneKeepPaths, SuppressPrune} instead of a bare prune bool; both the go-git (removeBillyOrphans) and CLI (removeDiskOrphans) prune paths honor the union keep-set. Prune primitives are unchanged.

Two-test rationale (+ a third to make the invariant real)

Strict TDD, RED before GREEN. Integration tests use a file:// bare remote (which drives the CLI prune path).

  1. Reproduction: two disjoint parts, no PrunePlan → both files must survive. RED today (part 2 prunes part 1), GREEN via the nil fail-safe.
  2. Invariant: Gen1 {api,web}; Gen2 = two parts {api},{db} sharing one PrunePlan → api survives (in the union), db written, web (dropped resource) pruned. Distinguishes the union fix from merely disabling prune.
  3. Never-per-part under spec prune: spec.git.prune=true + three parts → a non-final part must not prune a prior part's file (a 2-part test can't expose this — part 1's only wrongful deletions are prior-generation files that part 2 rewrites anyway). Proves SuppressPrune overrides the sink-level flag.

Gates (all green)

go build, go vet, task lint (golangci-lint v2 + go-arch-lint), task verify, task test (envtest, 0 failures), task coverage 85.3% ≥ 85% floor, and the changed-package integration tests. (Docker/testcontainers-backed integration tests — forgejo/kafka/nats/postgres/s3 — skip in this environment for lack of rootless Docker; unrelated to this change.)

…the union

For perResource/split git-layout sinks the controller writes a sharded
export part-by-part, calling sink.RunExportEnvelope once per part. Each
call pruned directory-scoped with a keep-set of only THAT part's files,
so part 2's prune deleted part 1's files: last-part-wins silent data
loss. The root cause is git PRUNE, not path collision -- every part
projects into the same generation directory (the item path template
{cluster}/{sourceNamespace}/{kind}/{sourceName} has no inventory-name
component), so per-part prune erases siblings.

Fix invariant: for a multipart set, prune runs EXACTLY ONCE, against the
UNION of all parts' projected paths, on the final part -- never per-part.

Seam: a passed-in accumulator (sink.PrunePlan) is threaded on
ExportEnvelopeRequest. Both controllers create one when len(parts) > 1
and share it across the sink's parts. resolveSnapshotExport records each
part's projected paths and, for a prune-bearing layout:
  - non-final part -> SuppressPrune (prune skipped)
  - final part     -> prune with PruneKeepPaths = union of all parts
Because parts commit+push sequentially onto the same branch, the final
part's workdir already holds parts 1..N-1, so keeping the union preserves
prior parts while genuinely-stale (previous-generation) files, absent
from the union, are still deleted.

Fail-safe: a multipart set with no accumulator suppresses prune entirely
rather than risk a per-part prune. Backward-compat guard: a nil/empty
PruneKeepPaths keeps the legacy keep-set (= paths written this call), so
single-part and non-git sinks are untouched. Document mode (prune=false)
is unchanged. SuppressPrune additionally overrides an explicit
spec.git.prune=true so suppression holds even when the sink-level flag is
set.

git ExportFiles/gitlab ExportFiles take an ExportFilesOptions{Prune,
PruneKeepPaths, SuppressPrune} instead of a bare prune bool; the go-git
(removeBillyOrphans) and CLI (removeDiskOrphans) prune paths both honor
the union keep-set. Prune primitives are unchanged.

Tests (integration, file:// bare remote -> CLI path):
  1. reproduction: two disjoint parts, no PrunePlan -> both files survive
  2. invariant: shared PrunePlan across a generation -> kept parts
     survive, dropped resource is pruned (proves prune still runs)
  3. never-per-part under spec.git.prune=true with THREE parts -> a
     non-final part must not prune a prior part's file
Copilot AI review requested due to automatic review settings August 3, 2026 16:23

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes silent data loss in multipart Git-sink layout exports by ensuring directory-scoped prune runs exactly once per multipart export set, using the union of all projected paths (instead of pruning per part and deleting earlier parts’ files).

Changes:

  • Introduces a shared sink.PrunePlan accumulator to union projected paths across multipart exports and coordinate a single prune on the final part.
  • Replaces the ExportFiles(..., prune bool) API with ExportFilesOptions{Prune, PruneKeepPaths, SuppressPrune} across git/gitlab backends and plumbing.
  • Adds integration tests reproducing the bug and asserting the “prune once against union” invariant (including spec.git.prune=true override behavior).

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
internal/sink/layout_export.go Adds PrunePlan and computes multipart-aware ExportFilesOptions to suppress per-part prune and prune once with union keep-set.
internal/sink/layout_export_test.go Updates fake backend to accept new options and adapts unit tests to new resolveSnapshotExport signature.
internal/sink/layout_export_multipart_prune_test.go Adds integration tests that reproduce the regression and validate union-prune + suppression behavior.
internal/sink/gitlab/backend.go Adopts ExportFilesOptions, including suppression override and union keep-set forwarding.
internal/sink/gitlab/backend_export_test.go Updates GitLab backend tests for the new ExportFilesOptions API.
internal/sink/git/export.go Adds ExportFilesOptions, introduces pruneKeepSet, and applies it to go-git prune path.
internal/sink/git/export_file.go Applies pruneKeepSet to the CLI prune path.
internal/sink/git/config.go Extends git Config with PruneKeepPaths for union keep-set support.
internal/sink/git/backend.go Adopts ExportFilesOptions and ensures SuppressPrune overrides sink-level prune.
internal/sink/git/backend_test.go Updates tests to use ExportFilesOptions{Prune:true}.
internal/sink/export.go Extends ExportEnvelopeRequest with PrunePlan and threads it into snapshot export resolution.
internal/controller/kollectinventory_controller.go Creates and shares a PrunePlan across multipart parts per sink job.
internal/controller/kollectclusterinventory_controller.go Same as above for cluster inventory exports.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +209 to +220
plan.Add(projectedPaths)
if partIndex >= partTotal {
// Final part: prune once, keeping the union of every part's paths.
opts.PruneKeepPaths = plan.Union()

return opts
}

// Non-final part: suppress prune so it runs only on the final part.
opts.SuppressPrune = true

return opts
@codecov

codecov Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Review of PR #183 flagged that the default git engine (go-git) had ZERO
execution coverage of the multipart union-prune fix -- all three new
tests use file://, which the high-level entry point always routes to the
CLI engine. The go-git branches (pruneBillyOrphans, the pruneKeepSet
union branch, and the stageChanges go-git delete branch) were validated
only by manual trace.

Add TestExportRemote_MultipartUnionPrunePreservesPartsDropsStale, which
drives exportRemote directly against a local bare repo (no Docker),
mirroring the multipart controller flow: a non-final part writes with
prune suppressed, then the final part prunes once against the union
keep-set. Asserts a prior part's file survives (no data loss) and a
resource dropped since the previous generation is pruned (union
correctness). Verified RED by neutralizing the union keep-set (prior
part deleted) and GREEN after. All three previously-uncovered go-git
branches are now COVERED (git pkg 84.9% -> 85.1%).

Record the deviation in ADR-0419: ExportFilesOptions.SuppressPrune
authoritatively overrides git.prune=true on non-final parts so per-part
pruning can never re-enable and cause data loss.
Copilot AI review requested due to automatic review settings August 3, 2026 16:43

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated no new comments.

Suppressed comments (2)

internal/sink/git/config.go:35

  • This comment says only a nil PruneKeepPaths preserves legacy behavior, but the implementation treats both nil and an empty slice as legacy (it checks len(cfg.PruneKeepPaths) > 0). Align the comment with the actual behavior to avoid confusion.
	// PruneKeepPaths overrides the prune keep-set. When non-empty, prune keeps exactly these paths
	// (the union of all parts in a multipart export) instead of only the files written this call. Nil
	// preserves the legacy behaviour: keep = written paths.

internal/sink/layout_export_multipart_prune_test.go:145

  • The test name suggests that per-part pruning drops prior parts, but the assertions verify the opposite (both part files must survive). This makes the test intent harder to understand when scanning failures.
func TestRunExportEnvelope_MultipartGit_PerPartPruneDropsPriorParts(t *testing.T) {

@sonarqubecloud

sonarqubecloud Bot commented Aug 3, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
55.4% Coverage on New Code (required ≥ 80%)

See analysis details on SonarQube Cloud

@konih
konih merged commit 3ff2baa into main Aug 3, 2026
31 of 33 checks passed
@konih
konih deleted the fix/rel-git-multipart-prune-union branch August 3, 2026 16:54
konih added a commit that referenced this pull request Aug 3, 2026
…sh + export-flow branches with local repos (COV-90-S02)

Local-repo (no network, no Docker) coverage for the git sink's SSH, push, and
export-flow paths plus the GitLab multipart parity wiring (REL-GIT-MULTIPART, #183):

- writeTempPrivateKey: assert 0600 perms + verbatim content; cover create-temp failure.
- writeTempKnownHosts / sshAuthMethod: cover create-temp failure and malformed
  known_hosts parse error; lock happy-path content.
- pinGoGitSSHResolution: rewrite-to-resolved (public IP literal, no DNS), non-ssh
  passthrough, unparseable URL, forbidden-host resolve failure, unsupported auth (16.7% -> 94.4%).
- pushCommitted against bare local repos: non-fast-forward -> sync fast-forward success;
  a non-reconciling policy surfaces a wrapped, non-ff-classified rejection (not swallowed);
  a transport push failure wraps as "git push" (50% -> 84.6%).
- exportRemote / ExportFilesWithBranch: insecure-SSH + feature-branch checkout, mirror-prep
  failure, no-files guard, CLI-path ClassifyExportError.
- stageChanges: cover the non-prune wt.Add error branch.
- gitlab Backend Export/ExportFiles: merge_request-mode branch-spec + prune-opts wiring
  and NewBackend invalid-spec error.

git pkg uncovered 207 -> 172 (85.1% -> 87.6%); gitlab uncovered 42 -> 39 (83.9% -> 85.1%).
Repo floor gate: internal/ coverage 86.0% (floor 85%).
konih added a commit that referenced this pull request Aug 3, 2026
…0-S01)

Exercise the controllers' error, degrade, and finalizer paths so requeue/
degrade/finalizer behaviour is regression-locked and the biggest uncovered
pool shrinks. Test-only; no production changes.

- KollectTarget Reconcile: transient profile-resolve error propagates for a
  rate-limited requeue without hard-degrading (RED); suspend, missing
  profileRef, profile-not-found, and generic target-Get error branches.
- target finalizer: conflict on remove requeues WITHOUT dropping the finalizer;
  non-conflict error propagates; clean removal; ensure-finalizer conflict.
- ConnectionTest familySinkObject across all families + nil/unknown/NotFound;
  ensureOwnerReference disabled + already-set branches.
- family sink setConnectionVerified one-shot annotation clear, spec-enabled
  retain, and status-update-error propagation.
- ClusterInventory reconcileRollupExport: terminal export EDGE (no requeue,
  Degraded=True/ExportTerminal, Warning Event); multipart len(parts)>1 shared
  PrunePlan wiring (#183 gap); nil-registry and no-sink-refs branches.

internal/controller uncovered 307 -> 250. Fake+interceptor drives the
error-injection branches envtest cannot reach (repo's established pattern).
konih added a commit that referenced this pull request Aug 3, 2026
…sh + export-flow branches with local repos (COV-90-S02)

Local-repo (no network, no Docker) coverage for the git sink's SSH, push, and
export-flow paths plus the GitLab multipart parity wiring (REL-GIT-MULTIPART, #183):

- writeTempPrivateKey: assert 0600 perms + verbatim content; cover create-temp failure.
- writeTempKnownHosts / sshAuthMethod: cover create-temp failure and malformed
  known_hosts parse error; lock happy-path content.
- pinGoGitSSHResolution: rewrite-to-resolved (public IP literal, no DNS), non-ssh
  passthrough, unparseable URL, forbidden-host resolve failure, unsupported auth (16.7% -> 94.4%).
- pushCommitted against bare local repos: non-fast-forward -> sync fast-forward success;
  a non-reconciling policy surfaces a wrapped, non-ff-classified rejection (not swallowed);
  a transport push failure wraps as "git push" (50% -> 84.6%).
- exportRemote / ExportFilesWithBranch: insecure-SSH + feature-branch checkout, mirror-prep
  failure, no-files guard, CLI-path ClassifyExportError.
- stageChanges: cover the non-prune wt.Add error branch.
- gitlab Backend Export/ExportFiles: merge_request-mode branch-spec + prune-opts wiring
  and NewBackend invalid-spec error.

git pkg uncovered 207 -> 172 (85.1% -> 87.6%); gitlab uncovered 42 -> 39 (83.9% -> 85.1%).
Repo floor gate: internal/ coverage 86.0% (floor 85%).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants