Skip to content

Conversation

@maparent
Copy link
Collaborator

@maparent maparent commented Oct 23, 2025

This repairs the sync function so it actually gives the latest complete task.

Summary by CodeRabbit

  • Chores
    • Enhanced backend task scheduling and coordination system with improved timing logic and adaptive backoff strategies for managed failures
    • Improved sync operations through enhanced lock-based coordination and robust timeout handling mechanisms
    • Refined task execution tracking with historical run time information

@linear
Copy link

linear bot commented Oct 23, 2025

@maparent
Copy link
Collaborator Author

@CodeRabbit review

@supabase
Copy link

supabase bot commented Oct 23, 2025

Updates to Preview Branch (ENG-976-repair-propose-sync) ↗︎

Deployments Status Updated
Database Thu, 23 Oct 2025 13:15:08 UTC
Services Thu, 23 Oct 2025 13:15:08 UTC
APIs Thu, 23 Oct 2025 13:15:08 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations Thu, 23 Oct 2025 13:15:23 UTC
Migrations Thu, 23 Oct 2025 13:15:27 UTC
Seeding Thu, 23 Oct 2025 13:15:27 UTC
Edge Functions Thu, 23 Oct 2025 13:15:31 UTC

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

@maparent maparent requested review from mdroidian and sid597 October 23, 2025 13:08
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 23, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 23, 2025

📝 Walkthrough

Walkthrough

A new PL/pgSQL function public.propose_sync_task is added to coordinate task scheduling for sync operations. The function manages timing constraints, backoff logic, advisory locking, and state updates. It returns timestamps indicating when tasks can be executed or when they were last successfully completed.

Changes

Cohort / File(s) Summary
Migration & Schema
packages/database/supabase/migrations/20251023130549_repair_propose_sync.sql, packages/database/supabase/schemas/sync.sql
Adds new PL/pgSQL function that accepts target id, function name, worker, timeout, and task interval; manages advisory locks; applies backoff logic; and returns timestamp for task execution eligibility or last successful run time

Sequence Diagram

sequenceDiagram
    participant Caller
    participant propose_sync_task
    participant sync_info DB
    participant Advisory Lock

    Caller->>propose_sync_task: propose_sync_task(target, function, worker, timeout, interval)
    propose_sync_task->>sync_info DB: Attempt INSERT new sync_info row
    alt Row inserted (first time)
        sync_info DB-->>propose_sync_task: Success
        propose_sync_task-->>Caller: Return last_run timestamp
    else Row exists
        propose_sync_task->>Advisory Lock: Acquire lock on row
        Advisory Lock-->>propose_sync_task: Lock acquired
        
        propose_sync_task->>sync_info DB: Load status, failure_count, timing fields
        sync_info DB-->>propose_sync_task: Current state
        
        propose_sync_task->>propose_sync_task: Apply backoff logic<br/>Check timeout & timing constraints
        
        alt Task ready to execute
            propose_sync_task->>sync_info DB: Query last successful run time
            sync_info DB-->>propose_sync_task: max(last_task_start)
            propose_sync_task->>sync_info DB: UPDATE row (active, deadlines, worker)
            sync_info DB-->>propose_sync_task: Updated
        else Task not ready
            propose_sync_task->>propose_sync_task: Compute next eligible time
        end
        
        propose_sync_task->>Advisory Lock: Release lock
        Advisory Lock-->>propose_sync_task: Released
        propose_sync_task-->>Caller: Return timestamp (run or next eligible time)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

The changes introduce moderately dense PL/pgSQL logic involving state management, advisory locking mechanisms, backoff calculations, and conditional timing logic. The function coordinates multiple database operations with constraints and decision branches that require careful verification of correctness, especially around lock handling, race conditions, and the timing/backoff calculations.

Possibly related PRs

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "ENG-976: Repair sync function" directly and clearly relates to the main changes in the pull request. The PR objectives confirm the purpose is to repair the sync function so it "actually gives the latest complete task," which aligns with the changeset modifications to the propose_sync_task function to properly capture and return the last successful run time. The title is concise, specific, and free of vague language or noise—a developer scanning git history would immediately understand this is a bug fix for sync-related functionality. While the title doesn't enumerate every technical detail, that is not required and would actually detract from clarity.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/database/supabase/migrations/20251023130549_repair_propose_sync.sql (1)

52-66: Return value semantics are contextual; document for callers.

The function returns either:

  • The last successful task's last_task_start timestamp (when ready to execute), or
  • The next eligible execution time (when not ready).

Callers need to understand this dual semantics. Additionally, NULL can be returned (when status='complete' never occurred), which represents "never successfully completed," distinct from "not yet ready."

Consider documenting the return value contract in a function comment for clarity.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d208e5a and 9d90c87.

📒 Files selected for processing (2)
  • packages/database/supabase/migrations/20251023130549_repair_propose_sync.sql (1 hunks)
  • packages/database/supabase/schemas/sync.sql (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Supabase Preview
🔇 Additional comments (2)
packages/database/supabase/schemas/sync.sql (1)

95-174: Logic for capturing last successful task timestamp is sound.

The addition at lines 146–149 correctly captures the last successful task's last_task_start timestamp before overwriting it with the current invocation's start_time during the UPDATE. This ensures the return value reflects the previously completed task time, as intended by the PR objective.

The logic is protected by advisory lock (line 132–163), so the SELECT–UPDATE sequence is atomic within the lock scope. The unique index on (sync_target, sync_function) guarantees at most one row per task, so the max() aggregation is deterministic.

packages/database/supabase/migrations/20251023130549_repair_propose_sync.sql (1)

1-72: Function design and concurrency handling are solid.

The migration correctly implements the repair. Key strengths:

  1. Advisory lock pattern (lines 38, 69): Properly brackets all state mutations, ensuring atomic transitions under lock.
  2. INSERT idempotence (line 25): ON CONFLICT DO NOTHING prevents duplicate row creation; caller tolerates seeing an already-created row.
  3. Backoff strategy (line 49): Multiplies interval by (1 + failure_count), creating an exponential-style backoff without explicit exponential calculation.
  4. Timeout detection (line 44): Correctly identifies when an active task has exceeded its deadline.
  5. Precondition assertions (lines 20–22): Validate that timeout * 2 < task_interval to ensure a safety margin exists.

The critical fix—lines 52–55—captures last_task_start before the UPDATE overwrites it, ensuring the caller receives the last successful task's timestamp rather than the current invocation's start time.

@maparent maparent merged commit edc933c into main Oct 26, 2025
5 checks passed
@github-project-automation github-project-automation bot moved this to Done in General Oct 26, 2025
@maparent maparent deleted the ENG-976-repair-propose-sync branch October 26, 2025 17:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants