Sync outcomes and partial failures
changed: 0 does not prove that data is current. Read SyncResult.reason from
sync.now or sync.done to decide whether the attempted work completed
(data and sync, contracts §5.6).
| Reason | Meaning | Suggested message |
|---|---|---|
ok |
Every attempted operation completed, or no sync server is configured | Checked, within the requested scope |
busy |
Another sync held the lease; no request was attempted | Check already running |
offline |
At least one request had a transport failure | Could not connect |
unauthorized |
A request carrying a bearer token received 401 | Sign in again |
failed |
A server response or protocol error left a pull or push incomplete, a scoped run matched no bucket and attempted nothing, or a background run met the database lock once it was already going | Could not sync |
HTTP 403, HTTP 500, an anonymous HTTP 401, an invalid response body and invalid
pull ordering all count as failed. So does sync.now({ buckets }) naming only
buckets this host does not have — a typo, or a bucket a newer bundle renamed. It
attempts nothing, so it is not an empty success: it reports failed, the host logs
the names it was given, and it writes no outcome at all, leaving whatever the last
real run recorded. That matters because sync.status() is what your “sign in again”
banner reads: a scoped call can never turn a refused account into a healthy one. An anonymous 401 never emits auth.expired:
there was no token to reject. If failures overlap, the reported reason follows
unauthorized, then offline, then failed, then ok. The offline flag still
reports transport failure independently.
A run can apply rows before a later request fails. Keep those changes visible;
a positive changed count is not proof that the entire run succeeded. Unacknowledged
writes stay queued for retry. lastSyncedAt advances only after a successful
unscoped run; a successful bucket-scoped retry does not establish global freshness.
The reasons are an open string set. Treat an unknown reason as incomplete. On an older host that omits the optional field, show that the outcome is unavailable:
const result = await call('sync.now');if (result.reason === 'ok') showChecked();else if (result.reason == null) showOutcomeUnavailable();else showCouldNotSync();The failed value uses the existing nullable string field. It requires no schema
bump or new codegen shape. Declare SyncResult.reason to receive it in generated
types. Older hosts can still report ok for these failures; this is not a
capability test for their behavior. See Login and secrets
for token rejection and Lifecycle for event handling.
busy: finding out who is holding the lease
Section titled “busy: finding out who is holding the lease”busy says a run was refused, not who refused it. On a host at built-in revision
20 or above, sync.status() answers that: leaseKind is the kind of run holding
the lease and leaseAgeMs is how long it has held it.
leaseAgeMs counts from the moment the holder took the lease, so it only ever
increases while one run holds it and two samples can be subtracted. (Before
0.4.0-beta.0 it was measured from the host’s own lease renewal, which happens
after every applied page, so it fell back towards zero as a long sync progressed
and could read lower than a moment earlier. If you worked around that by timing
the holder from your own page, you can delete it.)
const s = await call('sync.status');if (s.leaseKind == null) { // Nothing is holding it. A `busy` a moment ago has already cleared.} else { console.log(`held by ${s.leaseKind} for ${s.leaseAgeMs} ms`);}leaseKind is foreground (UI start, resume, reconnect, sync.now, or an update
check’s data pull), background (the periodic job), push (woken by a data-only
message). It names the class of run, not the individual run: the UI isolate
has one sync driver, so two overlapping foreground triggers read
holder=foreground refused=foreground. That rules out the background isolate,
which is usually the question; the host log distinguishes the rest. Or unknown
for a lease row written before revision 20 that is
nevertheless held. (A host older than revision 20 does not return the field at
all — it is undefined, which is what the builtins gate below is for.) Like reason, it is an open set — treat a value you do not
recognise as “something holds it”.
Both fields are null whenever a run starting now would not be refused. That
includes a lease the host is about to take over: one that has passed its two-minute
expiry, one dated in the future, or one left behind by a launch that crashed. Those
are not what a busy is about, and the host’s log names every row a takeover
displaces, with which of the three cases it was.
Declare them as nullable returned fields to receive them:
"SyncStatus": { "pending": "int", "lastSyncedAt": "int?", "offline": "bool", "reason": "string?", "leaseKind": "string?", "leaseAgeMs": "int?"}Gate on (info.builtins ?? 0) >= 20, not on your own schema number
(capabilities and status).
Use them to report, not to decide. They exist so a stuck-looking sync can be
described accurately — in a diagnostics screen, a support log, or a bug report —
and so the host’s own log can be read. A refusal’s heldForMs= in the log is the
same measurement as leaseAgeMs, so the two can be read together. Do not spin on leaseAgeMs waiting to
declare the holder dead and do something about it: the expiry and takeover rules
are the host’s, and a page cannot release someone else’s lease. If you are looking
at a background lease older than a couple of minutes, the next run will take it
over; if you keep seeing one, that is worth a bug report, and these two fields plus
the host log are what makes it a reportable one.
When a launch and a background sync collide
Section titled “When a launch and a background sync collide”Android’s WorkManager reschedules an unfinished periodic job immediately on the next launch — so after a force-stop, a crash, a task swipe or a reboot, the one moment a background sync is most likely to be running is the moment your first screen needs the database most. What that launch looks like:
- your page’s first reads queue behind the background write, and the host logs
store: waiting operation=… elapsedMs=…for each one that waited; - the foreground sync is refused by a run in its own process, with
holder=background; - the update check gives up, so an OTA that is already published does not install on that launch.
It logs
update: step 7 stopped, another sync holds the lease after a 5-second wait holder=… heldForMs=….
This resolves itself. The next launch finds a lease left by a process that is gone, takes it over and installs the bundle in under a second. The host deliberately does not take the lease away from a run that is still going: the holder is mid-transaction and has no idea it was displaced, so a second sync starting underneath it is exactly the concurrent write over the user’s own rows that the lease exists to prevent.
What you can do from the page is make the wait visible rather than blank. Render your first screen from whatever you already have before awaiting a read, and treat a slow first read as a loading state rather than an empty one — the collision is the worst case of the general rule that an offline-first screen should never depend on a read finishing quickly.
If the background run itself meets the lock, it does not fail the WorkManager job — and where the lock lands decides which answer you get, because the two are not interchangeable:
- taking the sync lease —
busy. The lease is the first write any run makes, so no lease means no pull, no push and nothing observed, which is exactly whatbusyhas always promised. - once the run is going —
failed, carrying the buckets andchangedcount it had already earned rather than zeros, so your freshness line still learns what moved before the lock stopped it. - anything that is not a lock still throws, so a real bug is not hidden by this.
A lease the host cannot release does not throw the run’s result away either; the row then stands until its two-minute expiry, and the log says so, because a “took the lease” with no matching “released” would otherwise read as a torn-down isolate.
On the host side, the log carries the same facts. A refused run prints
holder=, heldForMs= and its own refused= kind; taking and releasing the
lease are each a line, from the lease itself, so an update check’s data pull and
an account switch are bracketed as well as an ordinary run; and the background
isolate prints entering and leaving. The “took the lease” line carries
(dated <n>ms ago), because it is written after the time it records — the row
insert, the commit and the hops back out sit in between — so date the hold from
that rather than from the line’s own timestamp. The trail is not the database
wait: the host samples its clock after that wait on purpose, and the store’s own
waiting line is what reports it. A “took the lease” with no matching
“released” is a lease a torn-down isolate never gave back — which is a thing you
can see rather than infer. See startup
diagnostics.
This outcome handling is covered by host and generated-bridge tests. iOS remains experimental and untested.
Committed HTTP pages and static chunks remain in changed and buckets even
when a later page or lease renewal locks. Earlier unauthorized/offline outcomes
retain precedence. A cleanup lock cannot hide a primary non-lock failure or its
stack, and a non-lock cleanup failure still surfaces. A release-only lock retains
the completed result and logs safely. Lease ownership and timing are unchanged.
A lock on the final outbox read keeps the classified result and reports
pending: 0 rather than throwing the result away — a page gets that, not only a
background run, whose own fallback can only report zeros. When that read is the
only thing that failed, the outcome is failed rather than ok: ok with
pending: 0 reads as “everything is saved”, and nobody looked at the outbox.
sync.status() still reports ok, because the data sync itself completed.