Skip to content

Offline Sync

This page is for developers building an offline-capable client against TruePPM’s API — there is no end-user setting here. The sync endpoint provides a two-way delta protocol compatible with WatermelonDB’s synchronize() helper: GET pulls server changes since a watermark, and POST uploads a batch of local task mutations.

This page documents the server side, which is live. No client implements it yet. The packages/mobile React Native package is a scaffold — its src/sync/ is a typed boundary with no implementation behind it. No native client is scheduled — a native app is conditional on user demand (#3834) — and the 0.5 installable PWA is the offline mobile surface. You can call these endpoints yourself today.

GET /api/v1/projects/{project_id}/sync/?since={cursor}
Authorization: Bearer <token>

Any project member (Viewer+) may call this endpoint.

ParameterTypeDefaultDescription
sinceinteger0Opaque cursor from a previous response’s timestamp. Returns rows changed strictly after it. Use 0 for a full sync. Keep constant for the whole paging session. Must be between 0 and 2^63 - 1; a negative value is a 400. From 0.5 a value past that range is also a 400; in 0.4 it returns a 500.
cursorstring—Opaque continuation token for the next page. Omit on the first request; pass the previous response’s next_cursor on each subsequent one.
page_sizeintegerTRUEPPM_SYNC_PULL_PAGE_SIZE (1000)Maximum rows returned across all collections in one page. Clamped to TRUEPPM_SYNC_PULL_MAX_PAGE_SIZE (5000).
{
"changes": {
"projects": { "created": [], "updated": [...], "deleted": [...] },
"tasks": { "created": [], "updated": [...], "deleted": [...] },
"dependencies": { "created": [], "updated": [...], "deleted": [...] },
"calendars": { "created": [], "updated": [...], "deleted": [...] },
"memberships": { "created": [], "updated": [...], "deleted": [...] },
"risks": { "created": [], "updated": [...], "deleted": [...] },
"sprints": { "created": [], "updated": [...], "deleted": [...] },
"sprint_retros": { "created": [], "updated": [...], "deleted": [...] },
"retro_action_items": { "created": [], "updated": [...], "deleted": [...] },
"task_suggested_assignees": { "created": [], "updated": [...], "deleted": [...] },
"task_links": { "created": [], "updated": [...], "deleted": [...] },
"task_recurrence_rules": { "created": [], "updated": [...], "deleted": [...] },
"time_entries": { "created": [], "updated": [...], "deleted": [...] }
},
"timestamp": 42,
"next_cursor": "eyJpIjoxLCJ2IjoxLCJpZCI6Ii4uLiIsInciOjQyfQ==",
"has_more": true,
"resync_required": false
}
  • created is always empty — WatermelonDB uses upsert semantics
  • updated — full row objects for live (non-deleted) rows
  • deleted — string IDs of soft-deleted rows (tombstones)
  • timestamp — high-water mark to adopt as since after the delta is fully drained. Pinned when the session’s first page is served, so it is identical on every page of that session
  • next_cursor — opaque continuation token, or null when the delta is exhausted
  • resync_required — false on every normal page. true means your since is too old for any delta to be complete; see Tombstone retention and resync_required. The field ships in 0.5
  • has_more — deprecated, removed in 0.5 — true while more pages remain for this since session. Exactly equivalent to next_cursor !== null; loop on the cursor instead

The pull is cursor-paginated so a cold start (since=0) on a large project never materializes the whole project into one unbounded response. Each page carries at most page_size rows across all collections; the client loops until the delta is drained:

  1. Request the first page with since (no cursor).
  2. Apply the page’s changes.
  3. If next_cursor is non-null, request again with the same since and that cursor.
  4. When next_cursor is null, the session is complete — adopt timestamp as the since for the next sync.

The cursor is a compound keyset on (collection, sync_seq, id), not a scalar sync_seq ceiling. Rows written together share a sync_seq, and a scalar cursor could not split a page between two rows of the same value without either dropping rows or leaving the page unbounded. Keying on the row id (a unique UUID) as a tiebreak makes every page boundary unambiguous — no row is skipped and no row is duplicated, even when thousands of rows share a value. Because the cursor only ever increases, a row edited mid-session moves forward in the stream and is either delivered later or re-delivered under upsert — never lost.

The checkpoint belongs to the session, not the page

Section titled “The checkpoint belongs to the session, not the page”

timestamp is computed once, when the first (cursor-less) page of a session is served, and carried inside the opaque cursor. Every continuation page echoes that same value; it is safe to read the checkpoint off any page of the drain.

That pinning is what makes step 4 sound. Collections are drained in a fixed order, so once the cursor has passed a collection the session can no longer deliver anything written into it. If each page recomputed the checkpoint, the last page would report a value above such a mid-drain write, and the client adopting it would filter that row out of every future pull — the edit would be lost silently, with no error and no retry path. Holding the checkpoint at the first page’s value errs the safe way instead: the mid-drain row stays above the adopted since and arrives on the next pull, and any row the session did deliver above the pin is simply re-delivered under upsert.

The practical rule for clients is unchanged — keep since constant, loop until next_cursor is null, then adopt timestamp. Because the pin lives in the cursor, a continuation token from an older server is rejected with a 400; restart the drain at the same since, which loses nothing.

Retro rows are visibility-filtered (ADR-0071): a Viewer pulling a project whose retros are team-only does not receive the retro’s raw notes or action-item text — those rows are excluded at the queryset level, and tombstones are delivered for visibility-removed rows so the local database drops them.

Every synced model carries two counters. They look interchangeable and are not.

server_version — the per-row save count. Starts at 1 on INSERT, increments atomically on every UPDATE (no lost-update races), and gets one final increment on soft delete. This is the optimistic-lock token: it is what you send back as X-Base-Version, and what a conflict response reports.

sync_seq — the delta cursor. Drawn from the project’s own monotonic sequence, so every synced row in a project is ordered against every other one. This is what since filters on and what timestamp reports. It is not serialized on rows — treat timestamp as an opaque checkpoint and echo it back, which is what the protocol has always asked for.

since=0 returns live rows only, with no tombstones. A cold start holds nothing to delete, and a client that has to rebuild discards its local store before pulling from 0 (see Tombstone retention and resync_required), so no stale row can survive. Any since above 0 returns tombstones as before. The user-scoped program pull (/sync/user/programs/) behaves the same way.

By default a stale write resolves last-writer-wins on server_version: whoever saves last wins the whole row. For the records people most often co-edit — task, project, and risk — the API instead does field-level merge so two people editing different fields of the same record both keep their work (ADR-0217).

A client opts in by sending the version it last saw as the X-Base-Version request header (or a base_version body key) on a PATCH:

  • If no one else has changed the record since that version, the write applies normally.
  • If someone changed different fields, the edits merge: the write applies, and the response carries an X-Merged-Concurrent-Fields header naming what the other writer changed so the client can reconcile its cache.
  • If the record has moved more than 200 versions past the one the client saw, the API does not try to reconstruct what changed and returns 409 Conflict regardless of which fields differ, so a long-offline client reloads instead. A /sync/ push reports such a row in conflicts with ambiguous: true instead of saving it; reload the record and reapply the edit.
  • If someone changed the same field, the API returns 409 Conflict with a structured body — the client shows a “Someone else changed this” prompt with a Reload action rather than silently discarding either edit:
{
"code": "sync_conflict",
"detail": "Someone else changed this. Reload to see their changes.",
"conflict_fields": ["name"],
"server_value": { "name": "Their edit" },
"client_value": { "name": "My edit" },
"server_version": 6
}

Omitting X-Base-Version preserves the legacy last-writer-wins behavior, so the change is fully backward compatible. server_value is drawn from the record’s representation for the requesting user, so it never exposes a field the caller cannot otherwise read.

Board-card order is computed server-side under a row lock via POST /api/v1/tasks/{id}/reorder/ with a single anchor — {"before_id": "…"}, {"after_id": "…"}, or {"to_end": true}. Because the new position is computed while the sibling group is locked, two simultaneous drag-reorders serialize into a deterministic order instead of crisscrossing. Reordering requires Team Member+ (a Viewer cannot reorder).

The server snapshots the project’s cursor before running the delta queries. This prevents the race where a write lands between the checkpoint read and the row queries, causing a row to be included in updated but the timestamp to be set too low — making the client miss it on the next sync. On a paginated pull the snapshot is taken once for the whole session and echoed on every continuation page (see The checkpoint belongs to the session).

Cursor allocation takes the project row’s write lock, so concurrent writes to one project serialize and commit in allocation order. Without that a transaction could take a cursor value, a later one take the next value and commit first, and a pull in between would report the higher checkpoint and permanently skip the lower row.

Deleting a resource sets is_deleted = True, increments server_version, draws a fresh sync_seq, and records deleted_version. The row stays in the database as a tombstone. On the next sync, the ID appears in deleted; WatermelonDB removes the local record. Tombstones are not kept forever: the nightly reaper hard-deletes them after TRUEPPM_TOMBSTONE_RETENTION_DAYS (default 90; see Retention).

Once a tombstone is reaped, no delta can tell a client that the row was deleted. A client that was offline for longer than the retention window would keep that row and believe it was fully synced. To prevent this, the server keeps a tombstone floor for each project: the highest sync_seq of any tombstone the reaper has hard-deleted. The reaper raises the floor in the same transaction as the delete, and it never lowers it.

When 0 < since < floor, the pull returns 200 with this envelope instead of a delta:

{
"changes": {},
"timestamp": 0,
"next_cursor": null,
"has_more": false,
"resync_required": true
}

On resync_required: true:

  1. Discard your local store for this project, including the stored cursor.
  2. Pull again from since=0 and drain every page.
  3. Adopt that session’s timestamp as your new since.

A full pull (since=0) is always served. The floor never exceeds the project’s current cursor, so the timestamp a full re-sync gives you is never below the floor and the recovery cannot loop. The check runs on every page, so a reap that lands partway through a paging session also ends that session with resync_required.

The shape is chosen to fail safe for a client that does not know the flag. It applies no changes and adopts timestamp: 0, so its next pull is a full sync. That delivers every live row and every surviving tombstone, but it cannot remove rows whose tombstones were reaped. Only discarding the local store does that.

Concurrency. The floor is read twice: once off the project row before the delta, and again after the delta queries. The second read is what makes the guard sound. A delta query can miss a reaped tombstone only if the reap committed before that query ran. Because the floor was raised in that same transaction, the later read sees it.

The program pull (GET /api/v1/sync/user/programs/) carries the same guard against an installation-wide floor. The program pull’s floor is raised whenever programs are hard-deleted: sample-data teardown and a full workspace purge. Both remove programs and their memberships without a tombstone, so every client holding them is asked to re-sync.

After the upgrade to 0.5, every client is asked to re-sync once: the upgrade raises every floor just above the current cursor, because tombstones reaped before 0.5 never recorded one (see Upgrading to 0.5).

Task deletion cascades: all Dependency rows where the task is predecessor or successor are also soft-deleted. Mobile clients receive tombstones for both.

POST /api/v1/projects/{project_id}/sync/
Authorization: Bearer <token>

Uploads a WatermelonDB-shaped delta batch (ADR-0082). The request body is an envelope:

{
"client_batch_id": "<uuid>",
"last_pulled_at": 42,
"changes": {
"tasks": { "created": [...], "updated": [...], "deleted": [...] }
}
}
  • Writable surface — only the tasks collection may be uploaded in v1; any other collection key is rejected with 400. All other mutations go via REST.

  • Idempotent replay — client_batch_id is a client-generated UUID. The first request to apply the batch records it and its response atomically; a retry carrying the same id (within the retention window, default 24 hours) replays the stored response without re-applying. Safe against flaky mobile networks.

  • All-or-nothing — the whole batch applies inside one transaction. A row that fails validation or RBAC rejects the entire batch.

  • Refusals are 4xx, never 5xx — a row the task rules refuse returns 400 with the same structured body PATCH /tasks/{id}/ returns, so a client can tell a refusal (fix the row, do not retry as-is) from a server fault (retry). The four task-rule codes are progress_requires_anchor, milestone_rollup_locked, zero_duration_not_milestone and guardrail_blocked, and a fifth, sprint_committed_dates_locked, ships in 0.5 for dating an undated BACKLOG-status task in a planned or active sprint (other statuses are not refused); each carries code, detail and suggested_action, and guardrail_blocked also names the rule. See Errors and status codes.

    {
    "code": "milestone_rollup_locked",
    "detail": "This milestone's progress is rolled up from its linked sprint(s) and cannot be edited manually. Close or unlink the sprint to edit.",
    "suggested_action": "unlink_or_close_sprint"
    }

    A refusal is not recorded against the client_batch_id. Re-sending the same batch validates it again, so it refuses identically while the blocking state holds and applies once that state is fixed (here, once the sprint is unlinked from the milestone).

  • Same rules as REST — apply reuses the same serializer as PATCH /tasks/{id}/, so an upload can never do something the caller could not do over REST. Requires at least the Team Member role; archived projects are rejected. Creating a row additionally requires the plan-authoring rule REST POST /tasks/ applies, so a Scheduler-role caller (who cannot create a task over POST /tasks/ either, and likewise any Enterprise role in the 2xx band) gets a 403 and the whole batch is rolled back.

  • Conflict resolution — plain last-writer-wins; each row is applied unconditionally and server_version is bumped.

  • Limits — the POST path is rate-throttled, and a batch is capped at 500 rows by default (TRUEPPM_SYNC_BATCH_MAX_ROWS).

import { synchronize } from '@nozbe/watermelondb/sync';
await synchronize({
database,
pullChanges: async ({ lastPulledAt }) => {
// Loop the cursor until the delta is drained, merging each page's buckets.
const since = lastPulledAt ?? 0;
const merged: Record<string, { created: unknown[]; updated: unknown[]; deleted: string[] }> = {};
let cursor: string | null = null;
let timestamp = since;
do {
const url = new URL(`/api/v1/projects/${projectId}/sync/`, location.origin);
url.searchParams.set('since', String(since));
if (cursor) url.searchParams.set('cursor', cursor);
const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
const page = await res.json();
for (const [collection, bucket] of Object.entries(page.changes)) {
const dst = (merged[collection] ??= { created: [], updated: [], deleted: [] });
dst.updated.push(...bucket.updated);
dst.deleted.push(...bucket.deleted);
}
timestamp = page.timestamp;
cursor = page.next_cursor;
} while (cursor);
return { changes: merged, timestamp };
},
pushChanges: async ({ changes, lastPulledAt }) => {
// Only the `tasks` collection is uploadable in v1; other mutations go via REST.
await fetch(`/api/v1/projects/${projectId}/sync/`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
// Persist the batch id with the queued batch so a retry after a
// network failure replays idempotently instead of re-applying.
client_batch_id: crypto.randomUUID(),
last_pulled_at: lastPulledAt ?? 0,
changes: { tasks: changes.tasks },
}),
});
},
});
Server modelWatermelonDB collectionUploadable
Projectprojects—
Tasktasks✅
Dependencydependencies—
Calendarcalendars—
ProjectMembershipmemberships—
Riskrisks—
Sprintsprints—
SprintRetrosprint_retros—
RetroActionItemretro_action_items—
TaskSuggestedAssigneetask_suggested_assignees—
TaskLinktask_links—
TaskRecurrenceRuletask_recurrence_rules—
TimeEntrytime_entries—