Changelog¶
All notable changes to this project are recorded in this file. The format follows Keep a Changelog, and version numbers follow the compatibility policy.
[0.4.0] - 2026-11-10¶
Breaking¶
- Every Storage failure from the offline bucket is now supabase-kt's
StorageRestException: noNotFoundRestException,BadRequestRestExceptionorUnauthorizedRestExceptionany more, so test the status, not the type.httpStatusOrNull(), aSyncFailedExceptionand a rejected upload'sstatuscarry the Storage API's own status, the one its error body names, and itscodeis Storage's error code, such asNoSuchKey. Hosted Storage sends a refusal on an HTTP 400 with the real status in the body, so a refusal recorded as400is now403or409, and a body5xx,408or429behind an HTTP 400 now keeps an upload queued where it was rejected. supabase-kt's RealtimerequireValidSessionnow defaults totrue: while the token provider throws, no join is sent and supabase-kt tries again everyrejoinDelaywithout giving up, so the table readsSubscribing. An object name holding a lone UTF-16 surrogate is refused withIllegalArgumentExceptionbefore anything is sent, and never cached.
Added¶
SyncStatus.isQueueCountedsays whether the status's three counts have been read from the queue:falsein the value a client starts with, where they are0for want of a count, andtruefrom the first counted value on, the last value atclose()included. A badge or a banner that would otherwise say "nothing waiting" for a moment waits for it, as the samples' Sync badges now do, in place of a count read once at launch. The Swift package'sSyncStatushas it too, and each testing artifact'ssyncStatushas an overload that takes it; the existing overloads build a counted status.
Changed¶
SyncStatus.lastSyncedAtis kept on the device. When sending empties the current user's queue, the time is written to one more reserved row ofobject_cache,last_synced_at, beside the cache owner's, with whose queue it was, and a new client carries it from its first counted value on, so a Sync screen no longer says "never synced" on every cold start.clearLocalData()removes the row with everything else, and the cache passing to another user removes the earlier user's, so one user's time never shows for the next. Data already on a device moves nowhere: the row appears after the first sync on this version, and an older build reads past it, as it does past every reserved row it does not know. The Swift package'sSyncStatus.lastSyncedAtis kept the same way. The network and Realtime switches are still not kept.- The library is built and tested against supabase-kt 3.9.0, with Ktor 3.6.0, kotlinx.coroutines
1.11.0 and okio 3.18.2, the versions it was released with. 3.9.0 is the first supabase-kt release
carrying both Realtime fixes the library waited for on 3.6, with a batch of Realtime reliability
fixes besides. What an app now gets by default:
dryRun(),maybeSingle(),notIn(in reads and in writes sent online; a write filtered with it is negated,not.in.(…), which the queue cannot record, so it is sent at once and never queued, and offline throwsMutationNotQueueableException), theisdistinctoperator,purgeCacheon the offline bucket (passed through, behind the network switch, leaving the cached copy alone), and Storage object names holding%,?or#cached like any other, since supabase-kt percent-encodes them. The warning at install names 3.9. - Filters: two top-level filters on one column are sent, and the server joins them as AND; the
library captures, replays and admits them like any other filters, and no longer refuses them. A
pattern list (
likeAll,likeAny,ilikeAll,ilikeAny) is refused only when it is empty, since supabase-kt now quotes each pattern as Postgres reads it. Aninelement or group value holding a quote or a backslash is still refused. In the Swift package, a text search beside a filter on its column keeps both, and an update or a delete with two filters on one column can now be queued. - Cache keys: a query with a pattern list, or
cs,cdorov, whose elements hold a comma, a brace, a quote, a backslash, a period, a colon, a parenthesis, white space orNULL, or are empty, and a query witheqand a text search on one column, get a new key once, as supabase-kt 3.9 writes them: such a query starts with a cold cache, and its old rows go with eviction. A Swift app's keys change for the same inputs, and for a read with a configured text search beside another filter on its column. The database, the queue and the cached files are read as before. A replayed insert or upsert now names its columns quoted on the wire (columns="id","title"). Acs,cdorovliteral queued by 0.3.0 that the server would have rejected as malformed is moved to the rejected list when it comes up for sending. - Realtime: a binding the server refuses after the join is handled through supabase-kt's system
message, and that table alone is joined again on the library's schedule while the others keep
receiving. After
disableNetwork(), or once the network is known down, the library closes supabase-kt's socket when nothing but its own channels was on it. In every other case supabase-kt closes an empty socket afterdisconnectOnEmptyChannelsAfter(its default, 30 s) rather than at once.
Fixed¶
- Inherited from supabase-kt 3.9: the heartbeat that could race Realtime's disconnect and end the
app's process; the channel leave sent without its
join_ref; the one401after a token refresh, when the first request went out with the old token; and the local session kept after a sign-out the server refused. - A queued upload whose object name cannot be put in a URL now goes to the rejected list instead of holding the queue.
[0.3.0] - 2026-10-29¶
Added¶
QuerySnapshot.pendingRowKeysnames the rows a queued write added, changed or removed: the primary key of each, worked out in the pass that lays the writes over the rows, so a per-row pending mark never shows before its row or stays after the write is sent. A row a write removed keeps its key, and a row without its whole key adds none. A one-shot read's result has the samependingRowKeys, and the Swift package'sQuerySnapshotandOfflineResponsehave it as a set of key dictionaries. The testing artifacts'querySnapshotandcachedResult(in Swift,querySnapshot,cachedResponseandofflineResponse) have overloads that take the keys.Offline.rejectedMutationList()andOffline.conflictedMutationList()read the rejected and conflicted lists once, the listrejectedMutations()andconflictedMutations()emit first, aspendingMutationCount()reads the queue's count; the Swift package has the same two calls.- On Android,
localFileIfCached(path)gives the cached copy of an object as aFile, ornullwhen none is cached, besidelocalUriIfCached(path), which gives it as aUri. OfflineClientClosedException, the error every call on a closed client throws, and a call the closing stopped. It is anIllegalStateExceptionwith the message the closed error always had, "This offline client is closed", so an existingcatch (e: IllegalStateException)or a check of the message keeps working; match the type instead. The testing artifact'sofflineClientClosedException()builds one.SyncReport.stopReasonsays why a sync returned when it did, and so why writes remain: it completed, the network could not be reached, the server failed in a way that may pass (with itsSyncFailedException), a failure on the device stopped it, the session was not ready or changed user, network access was off, writes wait behind another table, or local data was cleared. The set is open, so awhenover it keeps anelsebranch. The Swift package'sSyncReporthas the samestopReason, aSyncStopReasonwith an extensiblekindand the failure aserror, and the testing artifacts build one withserverFailureStop,localFailureStopand asyncReportoverload in Kotlin, andsyncStopReason(kind:error:)and asyncReportoverload in Swift.identityFromAccessTokenininstall(Offline), and the same setting in the Swift package'sConfig: a client without the Auth plugin tells its users apart by thesubclaim of the token its own provider returns, read and never verified. Each user's queued writes are then sent only with that user's token, the caches belong to one user at a time and are dropped when the token names another, and the Realtime channel is joined again for the new user, as with Auth, so a Swift app no longer needs its own sign-out routine. It is off by default, which changes nothing.offline.storage.clearFileCache()deletes every downloaded Storage file and its record, in every bucket, and leaves the mutation queue, the cached query results and the rejected and conflicted lists, so an app can free the device's storage without dropping writes waiting to sync. A download in flight is handed to its caller but not kept, as acrossclearLocalData(). The Swift package has it asstorage.clearFileCache().- A bucket's
evictCachedFile(path)deletes one object's cached copies, the untransformed one and every image transform, andevictCachedFile(path) { … }one transform's copy alone; nothing is sent. The Swift package hasevictCachedFile(path:)andevictCachedFile(path:transform:). - A bucket's
pinCachedFile(path)keeps an object on the device: the cache never evicts its copies, the untransformed one and every image transform's, across restarts, untilunpinCachedFile(path),evictCachedFile(path), a delete through the bucket,clearFileCache(),clearLocalData()or a change of user. Pinning sends and downloads nothing, writes keep the pin, and a move takes it along;isCachedFilePinned(path)says whether an object is pinned. The Swift package haspinCachedFile(path:),unpinCachedFile(path:)andisCachedFilePinned(path:). ensureCachedFile(path) { progress -> … }hands its lambda the download's progress: the bytes received and the object's size,nullwhen the server gave none, as aDownloadProgress. Every call waiting for one object's shared download is handed it, in its own coroutine, and the last one before it returns; a call without the lambda adds nothing to the download. The Swift package hasensureCachedFile(path:isPublic:onProgress:)andDownloadProgress, and the testing artifacts adownloadProgressfactory.cachedFile(path) { … }returns the cached copy of one image transform, the one a download with the sametransform { … }keeps, so a cached thumbnail can be handed to an image loader as a file.localUriIfCached(path) { … }on Android andlocalPathIfCached(path) { … }on iOS give it in the platform's terms, and the Swift package hascachedFile(path:transform:).- A Storage upload can wait in the mutation queue with the row writes around it:
upload(path, data, MutationStrategy.QueueIfOffline)on an offline bucket keeps the file's bytes on the device and returnsUploadOutcome.Queuedwhen it cannot be sent at once, and a later pass sends it in the order it was made, so a row written after it that names the file is sent after the file. It survives a restart, belongs to the user who made it, is refused onto the rejected list with its bytes kept for a retry, and goes withclearLocalData(); while it waits,cachedFile,ensureCachedFileand the platform helpers return its bytes on the device, and once Storage has it they become the cached copy. An upload whose answer was lost is sent again, and its refusal counts as stored only when the object at its path is verifiably its bytes.offline.storage.pendingUploads(),rejectedUploads()andrejectedUploadList()list them,SyncReport.rejectedUploadsreports a refusal, anddiscardPendingMutation,dismissRejectedMutationandretryRejectedMutationtake an upload's id. The Swift package has the same calls, and both testing artifacts build the new values. RejectedUpload.localPathis a refused upload's kept file on the device, for the app to show what was refused:cachedFileandensureCachedFilenever answer a refused upload, since Storage may hold other bytes at its path. The Swift package'sRejectedUploadhas it too, and each testing artifact'srejectedUploadhas an overload that takes it.- The testing artifact's
InMemoryStorekeeps an in-memory client's local data for the next client built over it: a client built withinMemory(clock, store)orinMemory(clock, realtime, store)after an earlier one closed finds its queued writes, which it replays, its rejected and conflicted lists, and its cached queries and files, so a test can simulate an app killed and relaunched. A client built over a store another client holds fails withIllegalStateException. The Swift testing product has the sameInMemoryStoreandinMemory(…, store:)overloads. cachedResult(data, supabase, fetchedAt, hasPendingMutations)in the testing artifact builds aPostgrestResultthatisFromCache,fetchedAtandhasPendingMutationsread as given, for a fake of an app's own repository. The Swift testing product hascachedResponse(value:data:count:fetchedAt:hasPendingMutations:).FakeRealtime.joinCount, in Kotlin and Swift, counts the joins the client has handled: once it moves, the client has reported the channel subscribed and asked for the named tables to be read again, so a test that waits for it reports a change after the join instead of racing it.realtimeTableStatussays where each table named inrealtime { }stands, keyed and ordered as named, besiderealtimeStatus; the Swift package reads it as aRealtimeTableStatusSequenceof[RealtimeTable: RealtimeStatus].FakeRealtime.failTablerefuses one table in a test, in both testing artifacts.
Changed¶
- When an object and a folder of the same name are both cached in one bucket, or two objects whose
names differ only in case on a case-insensitive volume, the one downloaded second is stored under
storage-hashed/, in the file named by a hash of its key, and its row'slocalPathrecords that file. Files and rows already on a device stay as they are and are read as before. An earlier build that finds such a row drops it when the object is next read, downloads the object again, and leaves the file until the file cache or local data is cleared. Until that read, an earlier build on iOS stops at such a row in every eviction pass, so its size bound evicts nothing while a row likealbum/cover.pngbeside the filealbumis there. - The query cache's eviction pass runs in the background after a response is written, where it ran before the read returned, and starts when a running count of the cached lists' length passes the bound, where every response of 4 KiB or more, and every 32nd response, summed every cached list first; a pass reads each list's length once and deletes the lists it chose in one transaction.
FakeRealtimeapplies the table'sRealtimeFilteras the server does: an insert or an update whose record does not meet it is dropped and counted indroppedReportCount, and a delete reaches the client whatever the filter. Before, every report to a followed table reached the client, so a test could see a change a device never receives.- Each table named in
realtime { }is followed on a channel of its own, so a table the server refuses, such as one whose filter names a column a migration renamed, stalls and is joined again alone while the others keep receiving, and each join reads only its own table again. Before, one refused binding ended the shared channel: every named table lost its changes, and each retry read every table again.realtimeStatussums the tables up:Stalledwhile any table is, with the first one's cause, otherwiseSubscribingwhile any join is in flight, andSubscribedonce every table is joined. With supabase-kt's defaultmaxAttempts, a refusal still drops the other tables' channels for a moment, as their socket is closed to end the rejoin supabase-kt runs in its read loop;install(Realtime) { maxAttempts = 1 }keeps them joined throughout.FakeRealtime.failChannelanddropChannelend every table's channel. - Concurrent
ensureCachedFilecalls for one uncached object share one download instead of each fetching the whole object, and a bytes or channel download of an object such a call is fetching waits for it and reads its file. A call canceled while another still waits for that download returns at once, and the download goes on for the other; the last caller to cancel still returns only once its partial file is deleted. - A Storage download of an object whose cached copy has an
ETagasks the server whether it changed, withIf-None-Match: a "not modified" answer serves the cached copy without sending the body again and moves itsfetchedAtto the time of the answer, where every download fetched the whole object before. The Swift package's downloads do the same. Each cached file's row records theETagit was sent under, in theeTagcolumn, which was always empty; a file an earlier version cached has none, so its next download fetches it whole once and records it. - Each pinned Storage object is recorded in a row of its own among the library's records in the
database (
pinned_fileand the object's key), so pins outlive a restart. Nothing already on a device changes. An earlier version of the library ignores those rows: 0.2.0 evicts pinned files as any other, deletes the rows withclearLocalData(), and keeps them when another user signs in, so after going back to 0.2.0, a switch of user and an upgrade again, the new user has the earlier user's pins (their files are not kept). - The rejected list keeps a guarded write's base in each guarded entry, under two new keys
(
baseVersion,baseJson), so a retry replays guarded. A list an earlier build wrote reads back without them, and a retry of such an entry replays unguarded, as it did there. - An object whose bucket id or path has a segment that starts with a letter and a colon
(
u:42/a.png) is stored understorage-hashed/, like every other name that cannot be stored verbatim. Nothing was cached under its plain path before, so no file already on a device moves. - An
inelement, or a comparison value inside anor { }orand { }group, that holds"or\and none of,.:()is refused withIllegalArgumentExceptionbefore anything is sent or queued, in a read, an update or a delete, and by the Swift package's core: supabase-kt escapes such a value but does not quote it, so the server read the escapes as the value and the request matched nothing, while a queued row with that value showed offline and vanished on the next refresh. A write queued by 0.2.0 with such aninelement is moved to the rejected list when it comes up for sending, with a message naming the column, instead of being sent and dropped as applied. Filter on such a value with a single top-level filter, which sends it as written. RealtimeFilterrefuses, when made, aninwithout a non-empty list and another operator with a collection or an array, and the Swift package's core refuses a filter that sets both forms or the wrong one: such a filter was sent asowner=in.<id>orid=eq.[1], the server refused the join, and the channel stalled and retried forever. Pass aListforinand a single value for every other operator.- A
QueueIfOfflinewrite sent at once stays queued, instead of being thrown and dropped from the queue, when the server answers408,429,502,504,522or524, or401with PostgREST'sPGRST301orPGRST303(a token the server holds expired while the device's clock says it is fresh), as a replay of the same write always has; a later pass sends it. A caller that relied on the exception to show an error now getsQueued. A500from the database is still thrown. single()is cached as its list, one row long, under the key of the list read with the same query, through the guards a list response passes. Offline, or when the network fails,NetworkFirst,CacheFirstandCacheOnlyanswer it from that list when it holds exactly one row, with the queued writes laid over it; no row or several fail as before. It was never cached, so a detail screen had nothing offline.maybeSingle()on supabase-kt 3.8 is cached the same way, and offline answers only its one row, nevernull.- A one-shot read whose answer had a server change laid over it, one that reached the table while
the request was out, returns those rows without the server's response headers, such as
Content-Range, which describe the rows the server sent. - The mutation queue can hold a Storage upload: a row of a new kind beside the row writes, with
its bytes in a
storage-uploadsdirectory beside the file cache, excluded from iOS backups as the database is and moved with the database into a configureddataDirectory. Data already on a device is untouched: nothing moves, and no stored format changes. An earlier version that opens a queue holding an upload refuses it onto its rejected list. SyncStatus.pendingMutationCountandrejectedMutationCount,pendingMutationCount()with no table, and a sync'ssyncedCount,remainingCountandalreadyOnServerCountcount a queued upload as a write;pendingMutations()andrejectedMutations()still list row writes only. An app that queues no upload sees the counts it saw.
Fixed¶
- A change the server sent to a named table as soon as its Realtime channel was joined could be dropped: supabase-kt starts listening for a table's changes only once the coroutine behind it runs, which could be after the join was taken, and it drops a change nothing listens for. Each table now listens before its join goes out. The read of the table on every join usually made up for the loss.
syncStatuscould stop counting the queue, the rejected list and the conflicted list for good when a read of the rejected or conflicted list failed while a count was being read, as a failing disk under load can make happen: its counts stayed where they were for the life of the client, and a background failure was logged. Such a failure is now logged as any other failed read, and the counts follow the queue again after the usual wait.- An object and a folder of the same name in one bucket, such as
albumandalbum/cover.png, can both be cached now. On disk they would need one name to be both a file and a folder, so the one downloaded second was never cached:ensureCachedFilethrew for it every time, a channel download of it could fetch it twice, and it was not served offline. - On a case-insensitive volume, such as the iOS simulator's or a Mac's, two objects whose names
differ only in case, such as
photoandPHOTO, or whose buckets' names do, shared one cached file, so the one downloaded second replaced the other's bytes, and a write to one deleted the other's copy. The second is now stored apart, and each object serves its own. - With Room 2.8.5 or later, which an app can resolve itself,
pendingMutations()andpendingMutationCountFlow()called afterclose()threw Room'sIllegalStateExceptionfrom the call, where acatchon the flow could not see it. Each now returns a flow that fails withOfflineClientClosedExceptionwhen collected, as every flow made afterclose()does, on every Room version. - In the Swift package, a call that failed for a reason of its own while the client closed threw
clientClosed: anyIllegalStateExceptionor cancellation met during the close read as the closed client, such as the failure of a download whose local data was cleared. It now keeps its own code, and only the closed client's error isclientClosed. - A sync pass that a user switch stopped left
SyncStatus.lastSyncErrorholding an earlier pass's failure, which was about the previous user's writes; it is now cleared then. A pass stopped because the session is not ready, network access is off or a write waits behind another table still leaves it as it was, since no newer answer came for those writes. - A reactive read's refresh asks again, on its retry schedule, for as long as its answers are
refused as older than a change to the table, and reads
Refreshingmeanwhile; aNetworkFirstThenCacheread whose first fetch is refused that way staysRefreshingtoo. Before, the second refusal settled the read on the rows it had and reportedIdle, so a busy table, or a reconnect with queued writes, could leave a list stale for good. - An answer whose request left before a Realtime event or a server record reached the table is
written with that change laid over it, so a refresh lands while other users keep changing a
shared table. Before, every such change refused the answers in flight, and a list read
Refreshinguntil the changes paused; a row deleted while a request was out is still not brought back. A change that cannot be laid over exactly (an insert, a move in an ordered list or a window, a row read without its key) has the read ask once more, and if that answer has one too, it is kept stale and returned as the device's copy (isFromCache), to be read again, instead of as the server's answer. - An upsert, or a Realtime record, into a table whose cached list was read without its key column was added to that list as a new row, beside the row it changed. The list is now marked stale and read again.
- A burst of changes on a followed table, as one statement over a few hundred visible rows sends, overflowed the two buffers between the Realtime plugin and the cache, the plugin's own and the library's, past about 130 waiting changes, and the newest were dropped without a log or a stale mark, so a row could keep an older value until the next join or fetch; every change is now kept, and a backlog of more than 5,000 waiting changes of one table is discarded as a whole, with that table read again as on a join and one warning logged.
- Each change a followed table received was applied as its own pass over the table's cached queries, so a burst ran far behind the connection; the changes waiting for a table are now applied as one pass, in the order the server sent them.
- A one-shot read made while a stored session's token refresh has failed waits for the session,
as it does while one restores. supabase-kt sends the anon key meanwhile, and tries the refresh
again every ten seconds by default; the read returned the anon key's answer, empty under
row-level security, as the server's. When the session does not settle within the wait, a
NetworkFirstread with the query cached, or aCacheFirstread of a list marked stale, serves the cached rows rather than that answer. ANetworkFirstThenCacheread waits the same way before its first emission. A read answered after the session settled asks again at once. - A read of a shape the cache cannot hold (
single(),maybeSingle(),head, acount, …) waits for a session that is restoring, or whose refresh failed, before it is sent. It went out at once on the anon key, where a detail screen'ssingle()failed withPGRST116and acountread 0 at cold start. - A cached list whose shape record the library could not read (one another build wrote, or one that did not decode) admitted every row of its table into the list, for good; the record is now replaced by the one the next read records.
- A write patched into a table while the cache was being trimmed could bring back a list the
trimming had just removed; a patch now changes only the lists still there. A read of the cache
that overlapped
clearLocalData()could leave a record of its query's filter values behind; such a record is now written only beside the rows it describes, and never after a clear. - A
2xxanswer that was not a list of rows (a captive portal's sign-in page, a proxy's block page, a self-hosted server's fallback page) replaced the cached list, and every offline read of the query then failed to decode it. Such an answer is no longer written: aNetworkFirstorCacheFirstread with the query cached within itsmaxAgeis served the cached rows, and a reactive read's refresh asks again,Stalledby that cause after its fast retries. A blank answer is an empty list, served and stored as[]. - Two different queries could share one cache key when a filter value held
&,=or|, and be served each other's rows offline. Such a query's key now ends in a digest of its parts; every other key is unchanged. Such a query's rows cached before the upgrade are not found; it is fetched again once, and the old rows stay until evicted. - A rejected write that was guarded by a version column keeps its base when it is retried: the retry checks the server's row as the first send did, so a row another device changed meanwhile is a conflict for the resolver, not an overwrite.
- A replayed write's returned row moves the base of the writes queued behind it by the same user only. On a shared device, another user's queued write to the same row keeps the version its user saw, so its replay meets the change as a conflict.
- A write parked on the conflicted list leaves the cached row showing the server's values for the
columns the replay read, instead of the values the device last read. The row keeps the version
the device saw, as it now does after the resolver's
KeepServertoo, so a later write to it still meets the move instead of applying over another device's change to a column the replay did not read. KeepServeron a listed entry drops a gone row from the cache, or lays the columns the entry recorded into the cached row while that row is still as the device saw it before the write, as the resolver's ownKeepServerdoes; the lists holding the row are then fetched again.- A sync pass canceled by anything but
clearLocalData()(a cancellation the transport threw) is no longer reported as a cleared pass with nothing left queued. It reports a failure on the device, the writes stay queued, and the library's own passes go on. - A download of a Storage object that was still on the wire when an upload, update, delete, move,
copy or resumable upload of the same object landed no longer becomes the cached copy: the caller
gets the bytes it asked for, and the next read downloads the new ones.
ensureCachedFiledownloads again once when the object outran it, and throwsIllegalStateExceptionwhen that happens twice, as it does after a clear. - A download whose
httpOverride, or a header set on the bucket, asks for part of the object (aRangeorIf-Rangeheader) or none of it (aHEAD) is no longer cached as the whole object, and offline is no longer answered from the whole copy.ensureCachedFileon a bucket with such a header throwsIllegalStateExceptioninstead of caching the fragment. - A cached file whose size is not the one its row recorded, as a power loss right after a download can leave, is dropped and downloaded again instead of being served. Each download is written through to the disk before it is renamed into place.
clearLocalData()part-way through a channel download no longer fails the download on the device, and the in-memory client behaves the same.- A moved object's cached copy keeps the time it was fetched;
cachedFile(path).fetchedAtno longer reads as the time of the move. - An object whose path has a segment that starts with a letter and a colon (
u:42/a.png) is now cached;ensureCachedFileno longer refuses it, and channel downloads of it no longer fetch every time. - A sign-in as another user without a sign-out first, as an anonymous session signing into an account does, kept the Realtime channel joined as the old user, so the new user's named tables were not read again and a change still arriving for the old user could be applied to the new user's cache; the channel is now left and joined again as the new user, and a change from the old user's channel is dropped.
supabase.close()with the Realtime plugin installed before Offline could leaverealtimeStatusatStalled, and it and a sign-out that disconnects Realtime logged a warning that the channel ended and would be joined again; the status now ends atOffat close, and a channel that ended is logged as a warning only when it is joined again.- Without the Auth plugin, a token the app's provider rotated after the refresh a minute before the expiry was not sent to the channel until a minute before its own expiry, so the server closed the channel at the old expiry and the named tables were read again; the provider is now asked more often as the expiry nears, a later token is sent as soon as it is returned, and a provider that failed once is asked again instead of being left until the next join.
- An empty value in an
inlist with other values, such asisIn("status", listOf("", "done")), is kept on the device as the server keeps it: a queued or cached row whose value is the empty string shows in a cached list read through that filter, and a queued update or delete sends the list whole instead of without the empty value. A list of only the empty value still matches no row, as the server reads it. isNetworkOrConnectivityFailure()isfalsefor a failure with an HTTP status further down its chain, ashttpStatusOrNull()reads it, such as an I/O failure raised around a Storage error or aSyncFailedException. Before, it looked only for PostgREST's errors and Ktor's response failures there, so such a failure read as the network's whilehttpStatusOrNull()gave its status.
[0.2.0] - 2026-10-20¶
Breaking¶
- The library depends on supabase-kt's
realtime-kt, from the same BOM as its other modules, for the tables an app names in its configuration to keep current through Realtime. An app that already listsrealtime-ktchanges nothing; one that did not now resolves the module, which it can leave uninstalled.
Added¶
realtime { table("tasks") }ininstall(Offline): the plugin keeps the named tables current through supabase-kt's Realtime plugin, which the app installs. It joins one channel while a user is signed in (or Auth is not installed) and the network is not known down, applies each insert, update and delete asapplyServerRecordandapplyServerDeletedo, reads the named tables again on every join (Realtime replays nothing), and leaves the channel on sign-out, offline,disableNetwork()andclose().table(name, schema, filter)takes a schema and oneRealtimeFilterthe server evaluates;Offline.Config.realtimeTableslists what was named. Tables named withoutinstall(Realtime)failcreateSupabaseClient.Offline.realtimeStatus, aStateFlow<RealtimeStatus>(Off,Paused,Subscribing,Subscribed,Stalled(cause)), and the switchdisableRealtime()/enableRealtime(), not kept across clients, like the network switch.FakeRealtimeinsupabase-offline-kt-testing, withinMemory(clock, realtime): a test reports inserts, updates and deletes to an in-memory client that names tables inrealtime { }, with noinstall(Realtime);subscribedTablessays what the client follows, andfailChannelanddropChannelend the channel as a server or a lost socket would.stalledRealtime(cause)builds the stalled status for a test double.- Swift:
Config.realtimeTables, an array ofRealtimeTable(_:schema:filter:)with aRealtimeFilter(column:operator:value:)orRealtimeFilter(column:in:), and aConfiginitializer that takes it beside the existing one;realtimeStatus, aRealtimeStatusSequenceofRealtimeStatus(off,paused,subscribing,subscribed,stalled(cause:)); anddisableRealtime()/enableRealtime(). The core owns the channel and refreshes its token before it expires throughConfig.accessToken; an app brackets a sign-in or sign-out with the switch, since the core sees no Auth session.FakeRealtimeinSupabaseOfflineTesting, withinMemory(…, realtime:), reports changes to an in-memory client. - Conflict detection for replayed writes, opt-in per table.
versionColumn("tasks", "updated_at")ininstall(Offline), and the mapOffline.Config.versionColumnsbehind it, keyed asprimaryKeysis, names the column a server-side trigger changes on every update of a row (atimestamptzkept bymoddatetime, or an integer). A queued UPDATE or DELETE whose filter pins one cached row of such a table records the row's version, and a sync pass replays it only while the server's row still has that version, asking for the row back; the returned row is cached and its version forwarded to the writes queued behind it. When no row comes back, one read by key tells a gone row, a policy denial (the rejected list), a lost answer whose write had landed (already on the server), a change to other columns only (resent against the new version) and a conflict. Writes sent at once, inserts, upserts and writes the queue cannot pin to one cached row replay as before.versionColumnthrowsIllegalArgumentExceptionfor a blank column, and a column among the table's key columns failscreateSupabaseClientwith it. The documentation's new "Conflicts and merging" page walks through it. Offline.Config.conflictResolver, aConflictResolverthe app may implement, asked about a moved row whose written columns changed on the server too, a DELETE of a moved row, or an UPDATE of a gone one, with aMutationConflict(the row key, the base, the local columns, the server's row,changedOnServerandconflictingColumns) and answering aConflictResolution:KeepLocal(resend against the server's version; the default for a moved row),KeepServer(drop it; the default for an UPDATE whose row is gone),ConflictResolution.apply(columns)(send other columns; an UPDATE of a row still on the server), orHold. A resolver that throws (anything but a cancellation) or takes longer than 30 seconds holds the write; it runs on the library's own dispatcher.Offline.conflictedMutations(), the current user's held writes asConflictedMutationentries, kept across restarts within the rejected list's bounds, withresolveConflictedMutation(id, resolution)(re-queues under a new id preconditioned on the recorded server version, or drops it) anddismissConflictedMutation(id).clearLocalData()clears the list.SyncReport.conflictsResolvedCount,SyncReport.conflictsKeptServerCountandSyncReport.conflicted;SyncStatus.conflictedMutationCount, counted together with the pending and rejected counts; andPendingMutation.baseVersion, the version a queued write replays against.mutationConflict(…)andconflictedMutation(…)insupabase-offline-kt-testing, which build the two new value types for a test of the app's own resolver or conflicted-list screen, and overloads ofpendingMutation(withbaseVersion),syncReport(with the conflict counts andconflicted) andsyncStatus(withconflictedMutationCount) beside the existing factories.ConflictStagingTestshows how to stage a row moved on the server between enqueue and replay with a KtorMockEnginealone: answer the guarded write with[]and the read by key with the moved row.- Swift:
Config.versionColumnsandConfig.conflictResolver, anasync throwsclosure from aMutationConflictto aConflictResolution(keepLocal,keepServer,apply(columns:),hold), with aConfiginitializer that takes them beside the existing ones;conflictedMutations(), aConflictedMutationSequenceofConflictedMutation, withresolveConflictedMutation(id:resolution:)anddismissConflictedMutation(id:); andSyncReport.conflictsResolvedCount,conflictsKeptServerCountandconflicted,SyncStatus.conflictedMutationCountandPendingMutation.baseVersion. The resolver runs in a task of its own, off the caller's actor; a throw holds the write.mutationConflict(…),conflictedMutation(…)and overloads ofpendingMutation,syncReportandsyncStatusinSupabaseOfflineTestingbuild the new values.
Changed¶
- The database moves to schema version 2, which adds
base_versionandbase_jsonto the mutation queue, with a migration that keeps every queued write; a write queued before the upgrade replays unchecked, as it would have. Going back to 0.1.0 across it is not supported, and loses the writes queued since.
[0.1.0] - 2026-10-12¶
The first release.
Breaking¶
- The library is a supabase-kt plugin. Install it with
install(Offline) { … }increateSupabaseClientand reach it assupabase.offline, wherecreateSupabaseOfflineClient(…)returned a client; the settings ofSupabaseOfflineConfigare the plugin'sOffline.Config(offlineStoragePathisdataDirectory, aString). The old names are gone; see Removed. supabase-kt closes the plugin with the client, once it has begun closing its HTTP client: a call made in between, or one whose request had not gone out, is still sent (Ktor can send while its client finishes closing), or ends as it would offline (a read the cache can answer is answered from it, a write the mutation queue holds isQueued) or with the closed error, never with a cancellation; a request already on the wire still answers. Callsupabase.offline.close()first to let the calls not yet sent go out. - A flow being collected when the client closes (
selectAsFlow,pendingMutations,pendingMutationCountFlow,rejectedMutations) completes, where it failed with the client's closed error, so a screen torn down at logout sees its flow end, not an error. A flow collected afterclose()still fails with the closed error, as every other call does. - Logging goes through supabase-kt's own: the plugin logs to the client's logging processor
(
defaultLoggingFactory) with the tagSupabase-Offline, atOffline.Config.logLevelor the client'sdefaultLogLevel.OfflineLogger,OfflineLogLeveland theloggerandminLogLevelsettings are gone: configure logging once, increateSupabaseClient. MutationOutcome.Queuedis a class that carries the queued write as aPendingMutation: match it withis MutationOutcome.Queued, notMutationOutcome.Queued ->.MutationOutcome.AppliedandQueuedhave internal constructors.OfflinePostgrestQueryBuilderis a final class, as supabase-kt's builder is, andOfflineandOfflineBucketApineed theOfflineInternalopt-in to implement. A test double comes fromsupabase-offline-kt-testing.RefreshState.InFlightisRefreshState.Refreshing, andRefreshState.Pausedis new: an exhaustivewhenoverRefreshStateneeds a branch for it.ReadStrategy.NetworkFirst,CacheFirstandCacheOnlytakemaxAge, notcacheDuration, and are no longer data classes.FlowReadStrategyandMutationStrategyare sealed interfaces: their cases are written as before, butentries,values()andvalueOfare gone.- A
CacheOnlyread that finds nothing it may serve throwsCacheMissException, notNoSuchElementException. AQueueIfOfflinewrite the queue cannot hold (a dry run, or one whose request could not be inspected to tell; a filter it cannot record; an unknown user; another schema; a write on its way into the queue while local data was cleared) that cannot be sent for want of a connection throwsMutationNotQueueableException, with that failure as its cause, instead of the failure itself or anIOException.isNetworkOrConnectivityFailure()is stilltruefor it. - The testing hook's opt-in marker
InternalOfflineTestingApiisOfflineInternal. syncPendingMutations(table: String? = null)returns aSyncReport(what it sent, what the server refused, what is still queued) in place of a count, and replacessyncAllPendingMutations(). It no longer throws a failure that stopped the pass: the report says what is still queued andsyncStatus.value.lastSyncErrorwhy. When the library is sending the same writes already, it waits for that and then sends what is left.pendingMutationCountandpendingMutationCountFloweach take onetable: String? = nullin place of two overloads: calls compile as before, compiled callers must be rebuilt. They, and the new queue and rejected-list members, show the current user's writes only, and none while the stored session cannot be read (they showed every user's then).selectAsFlowemits aQuerySnapshotin place ofOfflineReadResult, withisFromCache,fetchedAtandhasPendingMutationsbesideresultandrefresh; it is no longer constructed by an app.autoSyncis on by default and does what it says: the library sends queued writes by itself when the session settles into a user with writes queued, and when the network comes back. SetautoSync = falseto leave those passes to the app; a write queued behind an earlier one is sent by itself either way.- On Android the library's manifest declares
android.permission.ACCESS_NETWORK_STATE, for its connectivity monitor: it appears in the merged manifest of every app that uses the library. - A test builds its client as an app does, with
install(Offline) { inMemory(clock = …) }fromsupabase-offline-kt-testing;buildInMemorySupabaseOfflineClientis gone (see Removed). The client no longer runs in the test's own scope: its background work runs on the library's, and a failure there is logged, never thrown into the test. ReadStrategy.NetworkFirst,CacheFirstandCacheOnlytake aDurationonly: the constructors taking milliseconds are gone, andNetworkFirst(null)now compiles.- The Storage file helpers extend
OfflineBucketApi, the bucketoffline.storage.from(…)returns, in place of supabase-kt'sBucketApi: on AndroidensureLocalFilereturns aFileandensureLocalUriaUri, on iOSensureLocalPathaString, none of them nullable any more, and each takespathas the bucket's own members do.localUriIfCachedandlocalPathIfCachedarenullonly when nothing is cached. On supabase-kt's own bucket they no longer compile, where they returnednull. - A read, an update or a delete with two top-level filters on one column, such as
filter { gte("age", 1); lte("age", 10) }, throwsIllegalArgumentExceptionbefore anything is sent or queued. supabase-kt sends only the first of them, so the read showed rows outside the window and the write reached them, and a queued write replayed that way later. Write the two as oneand { }group, which sends both. - A read, an update or a delete whose pattern list (
likeAll,likeAny,ilikeAll,ilikeAny) is empty, or holds a pattern that is empty,NULL, edged with white space or holding a brace (and none of,.:()), throwsIllegalArgumentExceptionbefore anything is sent or queued, at the top level or in a group. supabase-kt sends such a pattern unquoted, so the server read another list:likeAll("code", listOf(""))went out aslike(all).{}, which matches every row. - On iOS the database and the file cache live in
Library/Application Supportby default (supabase_offline.dbandsupabase_offline/), not inDocuments, which an app with file sharing on shows in the Files app. A client that finds a database inDocumentsmoves it, with its unsent writes and its cached files, when it opens; while another client holds it, it stays there and that client's claim fails the open, and when both places hold a database the one inDocumentsis left and a warning logged. - The iOS framework carries no Swift-only helpers and no SKIE-generated Swift (see Removed). The Swift package reaches it through a bridge of its own.
- On Android, an interface member with a body compiles to a JVM default method only, so the
$DefaultImplsclasses are gone (-jvm-default=no-compatibility). SyncStatus.lastSyncErroris aSyncFailedException?, which is all it ever held: read itshttpStatusandcodewithout a cast. The testing artifact'ssyncStatus(lastSyncError = …)takes one.syncPendingMutations(table)no longer sends a table's writes ahead of an earlier write of the same user to another table: it stops at the first write with an earlier one still queued elsewhere, andSyncReport.heldBehindOtherTablesCountcounts what it held back. Sync every table to send them in order.- On Swift, the requirement of
OfflineFilterValueisofflineFilterText, where it wasfilterText, a name that showed in completion onString,Int,Date,UUIDand every other standard type that conforms, and could collide with one an app declares. A type of your own that conforms declaresvar offlineFilterText: String.
Added¶
- Built and tested against supabase-kt 3.6 (
supabase-bomin the version catalog), with Ktor 3.4.3 and kotlinx.coroutines 1.10.2, the versions it was released with. Not 3.8: supabase-kt 3.7.0 and 3.8.0 carry a Realtime crash and a protocol-V2 leave defect, fixed upstream but not yet released, and this library's pin sets an app's Realtime too; it moves to the first release with both fixes. On 3.6 there is nodryRun(),maybeSingle(),isdistinctfilter orpurgeCache(write a dry run by addingPrefer: tx=rollbackto the request), and a Storage object name with%,?or#is downloaded as supabase-kt downloads it but never cached, since supabase-kt 3.6 puts it in the URL unencoded and can fetch a different object (see the compatibility page). Each minor release of this library names exactly one supabase-kt minor: the artifact compiles supabase-kt's inline functions into itself and implements itsBucketApi, which gains members in minor releases, so a range cannot be promised. When an app resolves another supabase-kt minor, the plugin logs one warning when it is installed, naming both versions, and carries on; a patch difference is no warning. - The
Offlineplugin for supabase-kt:install(Offline) { … }andsupabase.offline, with its settings inOffline.Config: the two cache sizes,dataDirectory,primaryKeys(each table's key,idunless set;primaryKey(table, columns)),responseTrust(ResponseTrust, with the earlier rule asAuthenticatedSessionOnly),logLevel,networkAvailability, the app's own connectivity signal in place of the library's monitor, andautoSync. On Android the plugin needs noContext: androidx.startup gives it the application's. The configuration is read once, when the client is created. - Offline-first PostgREST reads through supabase-kt.
supabase.offline.from(table).select { }takes supabase-kt's own request builder and aReadStrategy(NetworkFirst,CacheFirst,CacheOnlyorNetworkOnly).selectAsFlowemits aQuerySnapshoteach time the cache or the network answers, under aFlowReadStrategy. OfflinePostgrestQueryBuilderhas supabase-kt's verbs and overloads under its names (insert,upsertandupdateof JSON, of a value and of a list, theupdate { set(…) }DSL,delete) and itstable,schemaandpostgrest; the offline choice is a named parameter before the trailing lambda. Most calls written against supabase-kt compile with only the receiver changed andio.github.nesfeder.supabase.offline.offlineimported. These need an edit: a write whose result is read (resultOrNull()); a suspending call or an earlyreturninside a request lambda, since the verbs are notinline(make the call before the verb); a request lambda passed inside the parentheses (name itrequest = { … }or put it after them); the typedrpc(importio.github.nesfeder.supabase.offline.rpcin place of supabase-kt's); and realtime'sselectAsFlowand bucket management, which stay onsupabase.fromandsupabase.storage. Typed writes encode throughpostgrest.serializer, as supabase-kt's do.MutationOutcome.Queued.pendingMutation(PendingMutation: id, table,MutationOperationINSERT,UPSERT,UPDATEorDELETE, createdAt, row keys, body) andMutationOutcome.isQueued.rpcon the plugin, network only, with a typed overload;offline.storage.from(bucket)andoffline.storage[bucket]; a typedapplyServerRecord, whoseprimaryKeysdefault to the table's configured key.applyServerRecordandapplyServerDeletetake aschema, for a table of a schema other than the client's default.OfflineException, open for new subclasses, withCacheMissException,MutationNotQueueableExceptionandNetworkDisabledException;httpStatusOrNull(), which reads supabase-kt's and Ktor's errors, Storage's included.- The opt-in markers
OfflineExperimentalandOfflineInternal, both at error level. API under either is left out of the API records and the compatibility checks: experimental API may change in a minor release with no changelog line. - Writes that work offline.
insert,update,upsertanddelete, and their JSON forms, return aMutationOutcome:Appliedwith the server's response, orQueuedwhen the write was recorded in the mutation queue to be sent later (MutationStrategy.QueueIfOffline, the default). Queued writes show in cached reads until they are sent. - The mutation queue, observed and steered:
pendingMutations(table?)(a flow ofPendingMutation),pendingMutationCount(table?)andpendingMutationCountFlow(table?), anddiscardPendingMutation(id), the way out of a write the server keeps failing (it waits for a send in flight, and what waited behind the write is then sent).syncPendingMutations(table?)replays the current user's queued writes in the order they were made and returns aSyncReport(syncedCount,rejected,remainingCount, andalreadyOnServerCountfor an insert whose earlier send had in fact arrived); it returns promptly when offline. - Refused writes:
rejectedMutations(), a flow of the current user's persisted rejected list (RejectedMutation, with the server'sServerErrorandisRetryable), withdismissRejectedMutation(id)andretryRejectedMutation(id); one user can never see, dismiss or retry another's. A write sent at once that the server refuses still throws the server's error to its caller: the list is for refusals found on replay. syncStatus, aStateFlow<SyncStatus>:network(NetworkStatus:UNKNOWN,ONLINE,OFFLINE,DISABLED), the current user's pending and rejected counts,isSyncing,lastSyncedAt, andlastSyncError, aSyncFailedExceptionthat carries the status and code but no row, filter value or token. The network is current as soon as the switch below returns; the two counts follow the queue shortly after each change, read together. It never throws: atclose()it takes one last value, withisSyncingfalse, and changes no more.disableNetwork()andenableNetwork(): while access is off, nothing is sent, reads are answered from the cache, writes that may queue are queued, reactive reads arePaused, and requests that must reach the server throwNetworkDisabledException, whichisNetworkOrConnectivityFailure()counts as offline. A new client starts with access on.- A connectivity monitor, on by default: Android's
ConnectivityManager(a validated network with internet) and the iOS path monitor. It is a hint, never a gate: it decides when the library tries by itself and whatsyncStatus.networksays, and a request the app makes is tried whatever it says. It starts with the client and stops withclose(). RefreshState.Paused: a refresh that cannot reach a network known to be down waits for it, instead of reading asStalled, and runs again when the network comes back.- Provenance on one-shot reads:
PostgrestResult.isFromCache,fetchedAtandhasPendingMutations, asQuerySnapshothas them, carried in response headers PostgREST never sends; a result from supabase-kt itself has none of them set. - Storage downloads cached on the device.
storage.from(bucket)returns anOfflineBucketApiwithcachedFileandensureCachedFile, and Android and iOS functions return the cached file's location. applyServerRecordandapplyServerDeleteapply a Realtime change to the cached reads.- Size limits for the cached rows and the cached files, in
Offline.Config. clearLocalData()deletes the cached rows, the queued mutations, which are never sent, and the cached files;close()releases the plugin's database.buildInMemorySupabaseOfflineClientin thesupabase-offline-kt-testingartifact: a client that keeps everything in memory, for tests.- A record of the public API of both artifacts, checked on every change, so the API cannot change without a reviewer seeing it.
supabase-offline-kt-testing:Offline.Config.inMemory(clock)keeps the plugin's cache, mutation queue and Storage file cache in memory, writing nothing to disk, with every other setting applied as in an app; the clock is the time the client sees. It watches no connectivity monitor, so its network status isUNKNOWNuntil a test setsnetworkAvailabilityor callsdisableNetwork(), which is how a test takes it offline. Factories build the value types whose constructors are internal, for an app's own test doubles:appliedOutcome,queuedOutcome,cachedFile,pendingMutation,stalledRefresh,querySnapshot,syncReport,syncStatus,rejectedMutation,serverError, and the exceptionscacheMissException,mutationNotQueueableException,networkDisabledExceptionandsyncFailedException.- Published on Maven Central as
io.github.nesfeder.supabase-offline:supabase-offline-ktandio.github.nesfeder.supabase-offline:supabase-offline-kt-testing, for Android,iosArm64andiosSimulatorArm64, each with its sources, an HTML API reference and a signature on every file. - The Swift package
SupabaseOffline(andSupabaseOfflineTestingfor tests), published by each release tohttps://github.com/nesfeder/supabase-offline-swiftunder the same version. It needs iOS 16 and Xcode 26 or later, and runs on arm64 simulators only: a simulator build that includes x86_64 (such as Any iOS Simulator Device) fails to link, so build for a specific simulator, or withARCHS=arm64. Its framework is an asset of this repository's GitHub Release, and carries a privacy manifest, as theSupabaseOfflinetarget does, declaring the file-timestamp and user-defaults APIs it references. It is not code-signed in 0.1.0. SyncReport.heldBehindOtherTablesCount, and the testing artifact'ssyncReport(heldBehindOtherTablesCount = …), defaulting to0.- The Swift package's API reference, built with DocC and published with the documentation site
under
/swift/, with articles on getting started, coming from supabase-swift, offline behavior, handling errors and testing an app; every code sample in it is compiled with the package's tests. The package's public interface is recorded inswift/api/, and a change to it is rated as a change to the Kotlin API is.
Changed¶
- Every public
suspendfunction declares@Throws(Throwable::class), so a framework that exports the library hands Swift a failure as an error instead of ending the process.close(), which overrides supabase-kt's, and thesyncStatusproperty cannot declare it. - A reactive read's refresh that fails for a reason other than the network is logged at WARNING, by type, once for each kind of failure in a row; it was retried silently.
- A reactive read's refresh that waits for the session to settle (an answer it may not cache yet)
reports
RefreshState.Refreshing, neverStalledwith an exception of the library's own. - Expected offline conditions on the read side log at INFO: a
CacheOnlyread with nothing cached, a coldNetworkFirstread offline, a read answered from the cache because the network failed, and a download offline. A download the server refuses logs at WARNING. - A
NetworkFirstThenCacheread fetches again when its cached rows may no longer be the server's: after a write the cache could not follow, a change of the cache's owner, orclearLocalData(). - okio is no longer an
apidependency of the library: no public declaration names one of its types. It still reaches an app, at the same version, through supabase-kt's Auth. - The Android artifact depends on
androidx.startup:startup-runtimeitself, at the version supabase-kt's Auth already brings, instead of reaching it through Auth. - A locally written row shows only in the cached lists whose filters it matches, leaves a list it
stops matching, and joins one it starts matching when another cached list read with the same
columns holds it.
eq,neq,inandisare evaluated with Postgres's null rules; a condition the library cannot evaluate admits the row, and a pending update or delete filtered by one changes nothing shown until it is sent. A queued row is still appended past a list's order and limit. - An upsert is shown merged by its conflict columns, or by the table's key (
idunless configured otherwise), and every row of a multi-row upsert shows once. - Without the Auth plugin, with the app's own token provider, or signed out, an empty answer is cached and reactive reads settle on it. A response received while a stored session restores or refreshes is never cached.
- With the Auth plugin, the cached rows and cached files belong to one identity at a time: when the session settles into another, they are dropped. Queued mutations are kept for their owners.
single(),maybeSingle()(from supabase-kt 3.8),head, counts (a list with a count included),csv(),geojson(),stripNulls()andexplain()are never cached: they go to the network, and underCacheOnlythrowCacheMissExceptionwithout sending anything.- A table in another schema is cached apart. A write to it with the default strategy is sent at
once and never queued; offline it throws
MutationNotQueueableException. - Typed writes (
insert(value),upsert(values),update(value)) encode through the app's own PostgREST serializer, so a customJson, contextual serializers andencodeDefaultsreach the server, and the mutation queue, as supabase-kt sends them; they used the library's ownJson. - Offline, a
NetworkFirstread with a warm cache answers at once instead of after supabase-kt's retries;NetworkFirstThenCachewith a warm cache shows it asStalled(Pausedwhen the network is known to be down) and keeps fetching instead of failing; aCacheFirstThenNetworkrefresh reportsStalledafter about 3.6 s, orPausedat once when the network is known to be down. - After a sync pass stopped on a server's
Retry-After, the library's own next pass waits at least that long (at most an hour); a sync the app asks for is sent at once. - The testing artifact pins the library to its own version with a strict constraint in its published metadata. Beside a newer library, an older testing artifact fails dependency resolution instead of a test failing with a missing method; a newer testing artifact raises the library in the test classpath to its own version without a word. Keep both on one version.
- A slow collector of a
CacheFirstThenNetworkread is handed the latest snapshot, not each one in turn, and never holds back the query's other collectors. - The request lambda passed to a read or a write may run more than once, so it must configure the same request every time.
- The on-device database is schema version 1, the one this release ships: each queued write keeps its owner, its replay order, its schema-cache refusals and whether a send of it may have reached the server in its own row, and each cached query the replay order it has caught up with.
- Replayed writes are kept for the overlay until every cached query of their table has been fetched again since, or until they fall beyond the newest 1,000 of the table, whatever the device clock says; a table nothing caches keeps none.
- A write PostgREST refuses because its schema cache does not know the table or a column yet
(
PGRST205,PGRST204), as happens just after a migration, stays queued, online as well as offline, and its user's later writes wait behind it. It is rejected only at the tenth such refusal, each counted at least 30 seconds after the last while the app runs (the first after it starts counts at once), so a table that does not exist, or a misspelled column, cannot hold the queue for ever. close()lets a replay pass finish the request it has on the wire, and record the answer, before it stops, so the next client does not send the write again. A request the server does not answer holdsclose()for up to its 10-second bound.- The library's internal code is renamed and grouped into packages under
io.github.nesfeder.supabase.offline.internal. No public declaration, stored name or stored format changed. The exported Room schema records one field's new Kotlin name,cacheKey; its column is stillsignature, and the schema's identity hash is unchanged. - The engine's internal store is the set of components the client builds itself. No public declaration, stored name or stored format changed: the exported Room schema and its identity hash are unchanged.
syncStatusfollows the queue from the moment the client opens, so its counts include what an earlier run left queued before the app first reads it; read for the first time afterclose(), it holds the last value it had.- A reconnection, or the session settling, ends at once the wait a failed pass left before the
library's next pass, and starts it again from one second; a server's
Retry-Afteris still waited out. While the monitor says offline, the library makes one failed attempt by itself per offline period and grows no wait. A wrong monitor costs nothing while requests reach the server; after one fails for want of a connection, queued writes wait for the monitor, the session or the app's sync. WithautoSyncon, a client without Auth sends what an earlier run left queued when it opens. An app's connectivity signal that ends while saying offline counts as unknown, as one that fails does. - Keeping the rows
clearLocalData()deleted out of the database's files is best effort, and never holds the clear: it waits at most a second for an open read holding the write-ahead log, then empties the log in the background within a few seconds of the read ending, and once more atclose(). It waited for up to about a minute, holding every send, and then only logged a warning. - Being offline is logged at INFO at most: a write the queue cannot hold that fails for want of a
connection was logged at ERROR, and a replay pass stopped by the network at WARNING. A write that
asked for a rollback (
Prefer: tx=rollback, what a dry run sends) and was committed, as hosted projects do, is logged once per client at WARNING. close()never throws: a failure closing the database is logged, and the database is released.
Removed¶
- The ways in before the plugin, and the names the plugin's API replaced, with nothing deprecated
left behind:
createSupabaseOfflineClient(Android and iOS) andSupabaseOfflineConfig(install the plugin and usesupabase.offline; it opens the same database, on iOS once it has moved fromDocumentstoLibrary/Application Support, so the cache and unsent writes carry over); theSupabaseOfflineClienttype (Offline);insertJson,upsertJsonandupdateJson(insert,upsertandupdate);insertWith,upsertWithandupdateWith, and the reifiedinsert,upsertandupdateextensions (the typed members, which encode throughpostgrest.serializer);storage(bucket)(storage.from(bucket));clearAllCache()(clearLocalData());supabase(supabaseClient);OfflineLoggerandOfflineLogLevel, with the iOS factory'sloggerandminLogLevel(supabase-kt's logging, atlogLevel);syncAllPendingMutations()andsyncPendingMutations(table): Int(syncPendingMutations(table?): SyncReport); the two-overloadpendingMutationCount()/pendingMutationCount(table)andpendingMutationCountFlow()/pendingMutationCountFlow(table)(one member each,table: String? = null); andOfflineReadResult(QuerySnapshot). buildInMemorySupabaseOfflineClient(install(Offline) { inMemory() }), and the millisecond constructors ofReadStrategy.NetworkFirst,CacheFirstandCacheOnly(passmaxAgeas aDuration).- What the iOS framework carried for the old Swift layer:
SupabaseFactoryand itsofflineClientKt,SwiftJson, theencodeToJsonString,encodeToJsonElement,encodeListToJsonStringandencodeListToJsonArrayhelpers,singleElementArray, the fifteen…Ktquery and mutation helpers, the threeapplySwiftOptions,ensureLocalFileUrlandlocalFileUrlIfCached(ensureLocalPathandlocalPathIfCachedstay), and SKIE with the Swift it generated. Nothing has consumed the framework, so no published user is affected; the Swift package will be built on a bridge module of its own. NumericDeltaColumn, and thedeltaColumnsparameter of the update verbs. A queued write replays exactly what was sent; a value that several devices change concurrently, such as a counter or a running total, is computed on the server from the facts clients write.
Fixed¶
- A write is a dry run when any of its
Prefervalues carriestx=rollback, not only the first: supabase-kt writes its ownPreferfirst and appends one the request adds, so a write that addedPrefer: tx=rollbackitself was queued offline and would have been replayed, and committed, as a real write. - Rows a write returns (
select()) are cached with the columns the caller wrote, matched by key; an update that asks for rows back changes only the rows returned. - A write the cache cannot follow marks the cached lists it may reach stale, and they are fetched again, instead of showing values the server no longer holds.
- A cached list a live reader shows is never evicted, for up to 500 live readers.
- A patched list keeps the time it was fetched, and a list made only of local writes is stale.
- A queued write is sent with its owner's session token or not at all: a user signing in while another's writes replay no longer has them sent as theirs.
- A write that may queue, made when the session's token has expired and cannot be refreshed
(offline, or refused by the Auth server), is queued instead of throwing
TokenExpiredException, and replays as never sent once the session is good again. - A replay refused because its stored filter can no longer be read says so, instead of saying the write has no filter.
- The in-memory client of the testing artifact is safe across threads: a live read while another
thread writes no longer fails with
ConcurrentModificationException. - Each emission of a live read is one view of the cache, the queue and its refresh. An insert the
server applied no longer shows twice for an emission (a list keyed by id crashed on it), a
replayed insert no longer drops out of a list opened right after the sync, and a
CacheFirstThenNetworkread no longer reportsIdleone emission before the rows its refresh fetched. - A channel download Storage answers with an error (
ensureCachedFile, the offline bucket'sdownloadAuthenticatedanddownloadPublicto a channel, and supabase-kt's…Tohelpers through it) throws what the bytes download throws. It cached the error body as the file and served it from then on. A redirect from https to plain http is refused too, even where Ktor'sallowHttpsDowngradelets the bytes download follow it. - A live read fetches again after
clearLocalData(), as after a change of owner, instead of showing the emptied cache until something else fetched; a refresh request made while a read's refresh ran is no longer lost. - A live read fetches again after a change of owner whose last step, deleting the file cache's folders, failed: it showed the emptied cache until something else fetched, and the error logged said the cache had not been dropped.
- A read made while the stored session restores waits for it at most 10 seconds instead of waiting
on a session store that hangs. Past that the cache is not served and the read goes out on the anon
key: a one-shot read returns that answer uncached, which under row-level security can hold fewer
rows, or none, and a live read shows none of the cached rows, only the queued writes it admits
(
Refreshing), until the session settles. - A read the cache cannot answer, made while the connectivity monitor says the network is down, is sent once instead of after supabase-kt's retries.
- One failed read of the database no longer turns automatic behavior off for the client's life, or fails a write the server answered: a later sign-in sends the user's queued writes, the sync status follows the queue again, and a write the server applied (or refused), or a discard that happened, is reported as it happened rather than as the failed read.
- A sync that
clearLocalData()cut short reports the writes it had sent before. - A write made as a client without Auth opens, with
autoSyncon, is sent at once and returnsApplied. The pass that client starts for writes an earlier run left could find the new write in the queue and send it itself, so the write returnedQueuedwith the network up and nothing ahead of it; it was still sent once, and never twice. - While a stored session restores, reads and writes read it once between them, not once each.
- A Storage call naming an object whose name holds a
%that does not begin a percent-escape (100%.png) throwsIllegalArgumentExceptionbefore anything is sent. supabase-kt 3.6 puts the name in the URL as written, the HTTP client cannot build that URL, and the failure read as a connectivity failure, so an app took itself to be offline. - A Storage "not found" answered while the session restores, or after its refresh failed, keeps the user's cached copy and is answered from it. The download went out on the anon key, and Storage answers an object that key may not read as "not found", so the copy was dropped and an app opening a private file at launch lost it until the next download.
- A client that opens with
dataDirectorynewly set, and moves the database from the default location, moves the downloaded files with it; one that cannot move is deleted, to be downloaded again. They stayed in the default directory, whereclearLocalData()no longer reached them and, on Android, Auto Backup still included them. SyncStatus.lastSyncErrorfor a pass stopped on the device, by neither the server nor the network, says so in a fixed sentence instead of naming the failure's class. On iOS a pass stopped by a request header the HTTP client refuses now says so, and what to check, instead of that general sentence.