Skip to content

fix(markers): stop retrying contribution conflicts - #559

Merged
Quick104 merged 3 commits into
mainfrom
codex/marker-contribution-idempotency
Aug 7, 2026
Merged

Quick104 merged 3 commits into
mainfrom
codex/marker-contribution-idempotency

Conversation

@Quick104

@Quick104 Quick104 commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #558.

Problem

The daily marker-contribution task treated provider HTTP 409 responses as generic errors. Because duplicate suppression intentionally excludes retryable error rows, every unchanged conflict was sent again on the next scheduled run. The existing lookup was also scoped to a local media-file ID, allowing identical provider payloads from duplicate local files to be submitted independently.

Approach

  • Map structured plugin AlreadyExists responses and the deployed legacy submit HTTP 409 error shape to a typed terminal conflict.
  • Record conflicts with status = 'conflict' and HTTP status 409, and count them as skipped work instead of failed work.
  • Deduplicate terminal contributions by provider, segment kind, and content hash. The hash already includes the resolved external target, segment bounds, and video duration, so corrected markers and rematched releases remain eligible.
  • Migrate historical 409 error rows to the terminal state and add a partial index supporting the new lookup.
  • Keep all other plugin failures retryable.

Validation

Focused tests:

$ go test ./internal/markers ./internal/taskmanager/tasks
ok  github.com/Silo-Server/silo-server/internal/markers (cached)
ok  github.com/Silo-Server/silo-server/internal/taskmanager/tasks (cached)

$ go test -race ./internal/markers ./internal/taskmanager/tasks
ok  github.com/Silo-Server/silo-server/internal/markers 1.332s
ok  github.com/Silo-Server/silo-server/internal/taskmanager/tasks 1.633s

Repository checks:

$ make migrate-validate
go run github.com/pressly/goose/v3/cmd/goose@v3.27.1 -dir migrations/sql validate

$ make verify-local-paths
scripts/check-local-path-leaks.sh

$ make lint
golangci-lint run

$ cd web && pnpm run lint && pnpm run format:check
✖ 157 problems (0 errors, 157 warnings)
All matched files use Prettier code style!

Known baseline/environment failures outside this backend-only change:

  • go test ./... passes the changed packages but fails two untouched Jellycompat process-lock tests: TestBeginWebOperationRecoversDeadProcessLock and TestBeginWebOperationRejectsLiveProcessLock. An isolated internal/playback rerun also passed after one flaky full-tree failure.
  • make test-web reports 36 failures and 1,775 passes. Thirty-five failures are in untouched appearance/storage tests where Node warns that --localstorage-file has no valid path and localStorage.clear is unavailable; the remaining existing failure is settingValuesRealtime.test.tsx.

Adversarial review

  • Treating every plugin error as terminal would hide outages. The mapping is deliberately limited to structured AlreadyExists and the exact legacy submission-409 shape; a regression test proves HTTP 500 remains retryable.
  • Cross-file deduplication could suppress distinct releases if keyed too broadly. The lookup retains provider and segment kind, while the content hash includes item identity, episode coordinates, duration, and bounds.
  • Reverting settled rows to error would recreate the request flood. The down migration removes the supporting index but intentionally retains already-settled conflict rows.

Risk

The legacy compatibility mapping depends on the deployed plugin error text containing submit HTTP 409. Structured AlreadyExists remains the preferred long-term plugin contract.

AI Disclosure

  • Tool(s): Codex
  • Model(s): gpt-5.6
  • Involvement: fully AI-generated
  • Adversarial review: reviewed terminal-error classification, cross-file hash scope, and migration rollback behavior; narrowed the mapping, added retry and dedup regression tests, and retained settled rows on rollback.

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of provider conflicts, including HTTP 409 and equivalent submission errors.
    • Prevented repeated retries of contributions that providers have explicitly rejected.
    • Deduplicated identical submissions across different media files, including concurrent submissions.
    • Preserved retries for temporary provider failures and canceled submissions.
  • Improvements

    • Conflict outcomes are now reported as skipped rather than submitted or failed.
    • Existing conflict records are settled and retained for consistent future processing.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change classifies provider conflicts as terminal contribution outcomes, deduplicates identical provider payloads across media files, migrates historical HTTP 409 errors, preserves transient retries, and counts conflicts as skipped work.

Changes

Marker contribution conflict handling

Layer / File(s) Summary
Conflict error classification
internal/markers/types.go, internal/markers/plugin_provider.go, internal/markers/plugin_provider_test.go
Adds SubmissionConflictError. Plugin errors for gRPC AlreadyExists and legacy HTTP 409 responses now use this type.
Claim-based submission and persistence
internal/markers/contribute.go, internal/markers/contribution_repo.go, internal/markers/contribute_test.go, internal/markers/contribution_repo_test.go, migrations/sql/...
Contributions use atomic claims keyed by provider, segment kind, and content hash. Claims support stale recovery and token ownership. Conflict rows are terminal, transient errors remain retryable, historical HTTP 409 rows are settled, and a partial unique index protects active claims.
Task outcome accounting
internal/taskmanager/tasks/contribute_markers.go, internal/taskmanager/tasks/contribute_markers_test.go
Conflict outcomes are counted as skipped instead of submitted or failed.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PluginProvider
  participant ContributionWorkflow
  participant ContributionStore
  participant ContributionTask
  PluginProvider->>ContributionWorkflow: return SubmissionConflictError
  ContributionWorkflow->>ContributionStore: record conflict with HTTP status
  ContributionWorkflow-->>ContributionTask: return conflict outcome
  ContributionTask->>ContributionTask: count conflict as skipped
Loading

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the primary change: preventing retries for terminal contribution conflicts.
Linked Issues check ✅ Passed The changes satisfy #558 with conflict mapping, terminal persistence, skipped counting, cross-file deduplication, migration, indexing, and retryable transient errors.
Out of Scope Changes check ✅ Passed The claim recovery, synchronization, persistence, migration, and tests directly support conflict deduplication and reliable contribution handling.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/marker-contribution-idempotency

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/markers/contribution_repo.go`:
- Around line 64-79: Replace the check-then-submit flow around
ContributionStore.AlreadySubmitted with an atomic provider-target claim
performed before SubmitMarker, using a globally unique
provider/segmentKind/contentHash constraint or equivalent claim operation.
Ensure concurrent workers receive only one successful claim, and release or mark
the claim as error when a retryable provider failure occurs so later attempts
can proceed; preserve successful claims as deduplication records.

In `@migrations/sql/20260807140637_settle_marker_contribution_conflicts.sql`:
- Around line 1-29: Update the migration to run without a transaction by adding
the Goose NO TRANSACTION directive and removing both StatementBegin/StatementEnd
blocks. Change the index operations for
marker_contributions_provider_hash_terminal_idx to CREATE INDEX CONCURRENTLY and
DROP INDEX CONCURRENTLY, preserving the existing data update and index
definition.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1335aa48-0f9a-435a-a73d-68d3201f5a7f

📥 Commits

Reviewing files that changed from the base of the PR and between fa1d7ba and d898db5.

📒 Files selected for processing (9)
  • internal/markers/contribute.go
  • internal/markers/contribute_test.go
  • internal/markers/contribution_repo.go
  • internal/markers/plugin_provider.go
  • internal/markers/plugin_provider_test.go
  • internal/markers/types.go
  • internal/taskmanager/tasks/contribute_markers.go
  • internal/taskmanager/tasks/contribute_markers_test.go
  • migrations/sql/20260807140637_settle_marker_contribution_conflicts.sql

Comment thread internal/markers/contribution_repo.go Resolved
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Aug 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/markers/contribution_repo.go (1)

101-115: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add an integration test for the claim path. The current isContributionClaimConflict check correctly matches the standalone partial index name in pgconn.PgError.ConstraintName for 23505. Do not add message or table matching. Test a second matching media file against the migrated schema and assert (false, nil).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/markers/contribution_repo.go` around lines 101 - 115, Add an
integration test covering the contribution claim path with the migrated schema:
create or claim one media file, then attempt to claim a second matching media
file and assert the result is (false, nil). Exercise the existing
isContributionClaimConflict handling and verify the standalone partial index
constraint name is matched without adding message or table-name checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/markers/contribute.go`:
- Around line 208-225: Update the claim flow around store.Claim and its
implementation to recover stale submitting claims: allow takeover when an
existing row has status submitting and its updated_at exceeds a defined lease
interval, while retaining normal active-claim protection for fresh rows. Ensure
the takeover refreshes the claim metadata consistently and preserves existing
behavior for inactive or non-submitting rows.

---

Nitpick comments:
In `@internal/markers/contribution_repo.go`:
- Around line 101-115: Add an integration test covering the contribution claim
path with the migrated schema: create or claim one media file, then attempt to
claim a second matching media file and assert the result is (false, nil).
Exercise the existing isContributionClaimConflict handling and verify the
standalone partial index constraint name is matched without adding message or
table-name checks.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1c7ace5f-eab6-4bd6-80d7-cd29cf3cf938

📥 Commits

Reviewing files that changed from the base of the PR and between d898db5 and a2ba490.

📒 Files selected for processing (4)
  • internal/markers/contribute.go
  • internal/markers/contribute_test.go
  • internal/markers/contribution_repo.go
  • migrations/sql/20260807140637_settle_marker_contribution_conflicts.sql

Comment thread internal/markers/contribute.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a2ba490074

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/markers/contribution_repo.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
internal/markers/contribute.go (1)

225-227: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider a reason that covers in-flight claims.

Claim returns false in two distinct cases: a terminal row exists, or another worker holds a fresh claim. The fixed reason "already submitted" describes only the first case. An operator reading task output cannot separate a duplicate from a concurrent in-flight submission.

♻️ Suggested wording
-		return ContributionOutcome{Provider: providerID, Segment: seg.kind, Status: OutcomeStatusSkipped, Reason: "already submitted"}, true
+		return ContributionOutcome{Provider: providerID, Segment: seg.kind, Status: OutcomeStatusSkipped, Reason: "already submitted or claimed"}, true
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/markers/contribute.go` around lines 225 - 227, Update the !claimed
branch in the contribution flow to use a reason that covers both an existing
terminal submission and a concurrent in-flight claim, rather than the narrower
"already submitted" wording. Preserve the existing skipped outcome, provider,
segment, and return behavior.
internal/markers/contribution_repo_test.go (1)

95-103: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive the backdate from contributionClaimLease.

The helper hardcodes one hour. The lease is 15 minutes today, so the value works. If a later change raises the lease above one hour, these tests stop expiring claims and fail with a misleading message. Deriving the interval from the constant keeps the helper correct.

♻️ Suggested change
 func expireContributionClaim(t *testing.T, fixture contributionStoreFixture, id string) {
 	t.Helper()
+	expired := int64((contributionClaimLease + time.Minute) / time.Second)
 	if _, err := fixture.pool.Exec(context.Background(), `
 		UPDATE marker_contributions
-		SET updated_at = now() - interval '1 hour'
-		WHERE id = $1`, id); err != nil {
+		SET updated_at = now() - ($2 * interval '1 second')
+		WHERE id = $1`, id, expired); err != nil {
 		t.Fatalf("expire contribution claim: %v", err)
 	}
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/markers/contribution_repo_test.go` around lines 95 - 103, Update
expireContributionClaim to derive the SQL backdate interval from the
contributionClaimLease constant instead of hardcoding one hour, while preserving
the existing expired-claim behavior and error handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/markers/contribute.go`:
- Around line 225-227: Update the !claimed branch in the contribution flow to
use a reason that covers both an existing terminal submission and a concurrent
in-flight claim, rather than the narrower "already submitted" wording. Preserve
the existing skipped outcome, provider, segment, and return behavior.

In `@internal/markers/contribution_repo_test.go`:
- Around line 95-103: Update expireContributionClaim to derive the SQL backdate
interval from the contributionClaimLease constant instead of hardcoding one
hour, while preserving the existing expired-claim behavior and error handling.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c219135c-445f-410d-b2ba-f70983a14ad6

📥 Commits

Reviewing files that changed from the base of the PR and between a2ba490 and 554d4b3.

📒 Files selected for processing (5)
  • internal/markers/contribute.go
  • internal/markers/contribute_test.go
  • internal/markers/contribution_repo.go
  • internal/markers/contribution_repo_test.go
  • migrations/sql/20260807140637_settle_marker_contribution_conflicts.sql
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/markers/contribute_test.go

@Quick104
Quick104 merged commit 39efe30 into main Aug 7, 2026
4 checks passed
@Quick104
Quick104 deleted the codex/marker-contribution-idempotency branch August 7, 2026 15:21

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 554d4b3a8c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +79 to +81
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS marker_contributions_provider_hash_active_uidx
ON public.marker_contributions (provider, segment_kind, content_hash)
WHERE claim_active;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve global claims when the owning file is deleted

Once this index makes the claim provider-payload scoped, storing its only row under one arbitrary media_file_id is no longer safe: migration 182 still defines that foreign key with ON DELETE CASCADE, and the scanner deletes missing media_files in DeleteMissingByFolder. If duplicate files A and B share a payload, A's terminal row suppresses B; deleting A then cascades away the global claim, so the next run submits B's identical payload again. Preserve the provider-level claim independently of file lifetime, or retain equivalent claim state when its originating file is removed.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

@Rhainland Rhainland mentioned this pull request Oct 13, 2026
13 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fix(markers): stop retrying terminal contribution conflicts

1 participant