Skip to content

Delta Sync

NihilDigit edited this page Nov 12, 2026 · 1 revision

Delta sync and batch completion

The SDK exposes PikPak's incremental file-change stream, server watermarks, and task-backed batch mutations as atomic suspend primitives without owning a local database or background sync loop.

API and range scheduling

API priorities are ApiRequestPriority.INTERACTIVE (10), DEFAULT (0), and BACKGROUND (-10). Endpoint defaults preserve any explicitly supplied withApiPriority(...) context:

  • Full scans (sinceSyncTime = "") default to BACKGROUND; nonempty-cursor deltas and getFile detail lookups default to INTERACTIVE.
  • Folder creation, rename, and batch mutations default to INTERACTIVE.
  • When a TransferDemand is present in the coroutine context, queued API entries track its live priorityFlow (INTERACTIVE at STREAMING_PRIORITY 50 and above, BACKGROUND otherwise), including promotion while already queued in RateLimiter. Closing the TransferDemand cancels the queued waiter immediately and refunds its token reservation.

Token buckets with capacity >= 8 reserve min(8, capacity / 3) tokens from BACKGROUND traffic (backgroundReserve). RateLimiter.default() (capacity = 24, refillPerSecond = 20.0) therefore keeps 8 tokens available for interactive and default bursts while a full drive scan runs in the background. Passing backgroundReserve = 0 disables the reserve.

On the CDN side, direct range reads up to 64 KiB (including sampleCid windows) default to PikPakStreamReader.MICRO_PROBE_PRIORITY (12) unless an explicit priority or TransferDemand overrides it. Waiting playback reads run at 100, steady playback at 50, near look-ahead at 10, next-file prefetch warming at 8, comfortable far look-ahead at 6, background blocking reads at 5, downloads/paused look-ahead at 1, and FinishInFlight tail completion at -1. Far look-ahead is demoted to 6 only once the near comfort window is continuously cached in memory (not merely in flight).

Incremental ingestion

listFileChangesPage(sinceSyncTime, pageToken, pageSize) queries GET /drive/v1/files with parent_id=*, with_audit=true, and phase == PHASE_TYPE_COMPLETE, deliberately omitting trashed so trash and permanent-deletion tombstones arrive in the stream. On the server, modified_time.gt compares params.db_modify_time, capturing metadata changes such as starring that leave the visible modified_time unchanged.

FileStat.dbModifyTime and FileDetail.dbModifyTime expose that timestamp. Read isStarred on either model: it combines the raw starred boolean with the STAR entry in tags.

val checkpoint = client.consumeFileChanges(savedCursor) { page ->
    // Stage complete rows, including trashed rows, in a local transaction/staging table.
    stage(page.files)
}
// Atomically commit staged rows and persist checkpoint.syncTime (checkpoint.lastSyncTime).
  • Sequential pages, server-controlled page sizes. pageSize defaults to 500 (1..500), but the server may ignore small limits (limit=2 returned 400 rows in the 2026-11-10 live probe). Always consume every row returned and follow nextPageToken while keeping the sinceSyncTime lower bound fixed across pages.
  • Watermarks (FileSyncCheckpoint). Both firstSyncTime and lastSyncTime are returned; checkpoint.syncTime is lastSyncTime. The 2026-11-10 cross-page live probe verified that sync_time advances with db_modify_time scan order and that rows mutated after being read on page 1 reappear with their updated state on later pages (Measurements). Deduplicate/upsert by file.id.
  • Commit rules. Never advance the durable cursor or sweep missing rows after cancellation, a failed page, a failed local write, or FileSyncVersionOutdatedException. When the server reports version_outdated = true, discard the delta cursor and run a fresh full scan. Repeated nextPageToken values or blank sync_time fields fail explicitly.
  • In-memory convenience. syncFileChanges(sinceSyncTime) collects all pages into a FileDeltaSyncResult(upserted, deletedIds, trashed, checkpoint). deletedIds means removal from the active non-trashed view: both recycle-bin moves and permanent deletions arrive with trashed = true, so deletedIds alone is not proof of permanent deletion. Large SQLite replicas should stream via consumeFileChanges instead.

Initial scan and watermarks

scanFilesPages(pageSize = 500) streams all completed rows (including trashed markers) as a Flow<FileListPage>; consumeFileChanges("") does the same and returns the completion FileSyncCheckpoint. Stage into a candidate generation, publish only after normal completion, and do not overwrite newer local optimistic mutation state with older scan pages.

getFileSyncWatermark(sinceSyncTime) fetches a single small page (pageSize = 1) for a conservative watermark; getCurrentSyncTime(sinceSyncTime) drains all matching pages without retaining rows to read lastSyncTime (scanning the full drive if sinceSyncTime is empty). Never fabricate a sync cursor from the client clock: an empty delta response can echo its input sinceSyncTime.

Batch writes, task completion, and bulk metadata

batchMove, batchCopy, batchTrash, batchUntrash, and batchDelete split inputs into chunks of 500 unique IDs (BATCH_ID_LIMIT, matching the official desktop client) and await each chunk's server task by default (awaitCompletion = true). Earlier chunks remain applied if a later chunk fails; coroutine cancellation or timeout does not cancel an accepted server task.

  • Pass awaitCompletion = false for fire-and-forget submission.
  • For crash-durable recovery, call submitFileBatch(ids, operation, toParentId, onSubmitted = { receipt -> ... }) to persist each FileBatchReceipt(taskId, ids) before the next chunk goes out, then call awaitTasks(taskIds). A crash before receiving a receipt still requires checking remote state.
  • getTasks(ids) looks up tasks in filtered batches. awaitTasks never treats a missing task ID as complete, preserves already-completed tasks, throws DriveTaskFailedException on terminal task error, and throws DriveTasksTimeoutException (carrying unresolvedTaskIds) on timeout. When the with=reference_resource task listing reports "File deleted" because the output file was subsequently removed, awaitTasks verifies via getTask(id) so a completed transfer is not misreported as failed.

For bulk metadata reads via GET /drive/v1/files:batchGet (chunked by 100 repeated ids= parameters, never comma-joined):

  • batchGetFiles(ids, usage = null) returns List<FileStat> in the caller's deduplicated ID order (missing IDs omitted; FileStat preserves any medias and links returned).
  • batchGetFileDetails(ids, usage = "PLAY") returns List<FileDetail> with full medias variants and signed links, feeding both AccountState and HostHealth.observe (~130 ms per video across 100 files vs 1.95–3.6 s per serial getFile; see Measurements).

Signed link flags

DownloadLink.isLimited and VariantLink.isLimited detect x_limited=1 (and 101); maxSpeedBytesPerSec parses the ms query parameter, and expiresAt parses wire and URL signature expiries. Flag detection itself never loops on refreshes automatically; PikPakFileHandle avoids unexpectedly limited links on confirmed premium accounts (client.isFreeAccount == false) up to its bounded remint cap (MAX_HOST_REMINTS = 2).

Clone this wiki locally