<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Taufik Fredi Pratama on Medium]]></title>
        <description><![CDATA[Stories by Taufik Fredi Pratama on Medium]]></description>
        <link>https://medium.com/@taufikfredipratama?source=rss-3b22395fd2aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hbXsHjVBcp6JYipsrExCZg.jpeg</url>
            <title>Stories by Taufik Fredi Pratama on Medium</title>
            <link>https://medium.com/@taufikfredipratama?source=rss-3b22395fd2aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 12:54:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@taufikfredipratama/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why I’m Building Photo Storage Before the Camera Screen]]></title>
            <link>https://medium.com/@taufikfredipratama/why-im-building-photo-storage-before-the-camera-screen-e9ea08b0ec39?source=rss-3b22395fd2aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ea08b0ec39</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Taufik Fredi Pratama]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 00:00:33 GMT</pubDate>
            <atom:updated>2026-11-09T15:06:24.047Z</atom:updated>
            <content:encoded><![CDATA[<p>Why I’m working on photo storage before the camera UI in Epicnesia Field Operations Kit, and what a saved photo can really prove.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ehqFMjTG-hJ_lP3j.png" /></figure><p>Imagine a technician finishing an inspection of a pump. They take a photo, see a thumbnail, and move on. Later, someone opens the inspection record expecting to find that photo.</p><p>But what if the image is on the phone and the app has lost the connection to the inspection? Or the record says there is a photo, but the file never finished saving?</p><p>That technician is imaginary. Epicnesia Field Operations Kit doesn’t even have a camera screen yet. This is the situation I’m designing for, not a story from a field trial.</p><p>And it’s why I keep coming back to a question that sounds easier than it is: <strong>what should “Saved” actually mean?</strong></p><h3>The screen can wait</h3><p>A camera screen is easy to appreciate. Tap a button, see a preview, add a thumbnail. It makes a convincing demo.</p><p>But a thumbnail only tells you that the app displayed something. It doesn’t tell you whether the file and the inspection record will still agree when someone needs the evidence later.</p><p>So I’m working on the storage path first. Not because the camera is unimportant, but because I don’t want a polished screen making promises the code underneath it can’t keep.</p><h3>A photo needs more than a file</h3><p>For the app to treat a photo as saved evidence, two things need to line up.</p><p>One is the image file itself. The other is a database record that identifies the photo, connects it to an inspection, and stores details such as when it was captured, its size, and a fingerprint of its contents.</p><p>That fingerprint is calculated with SHA-256. Think of it as a way to recognize the bytes the app originally stored. If those bytes change, a later comparison can reveal the mismatch. It doesn’t make the image indestructible or prove that every pixel can be decoded.</p><p>The awkward part is where these two pieces live. The file is stored in the phone’s file system. Its record lives in the app’s database. They’re separate systems, and one database transaction can’t make both writes happen as a single indivisible step.</p><p>That leaves an engineering decision: <strong>which piece should be saved first, and what happens if the next step fails?</strong></p><h3>Why the record comes last</h3><p>The underlying photo storage mechanism was built earlier, in October. The current work isn’t replacing it.</p><p>Its sequence is deliberate. First it checks whether the photo ID already has a record. Then it streams the incoming bytes into a temporary file, counting them and calculating the fingerprint as it goes. It asks the operating system to flush the file, moves it to its final name, and asks the folder to be flushed too. Only after that does it insert the database record.</p><p>Those flush operations are precautions, not proof that a photo can survive every sudden power loss. What matters for this decision is the order: <strong>file first, record last</strong>.</p><p>A leftover file without a record is a problem, but the app doesn’t treat it as evidence. A record pointing to a missing file would make a stronger, and more misleading, claim.</p><p>The store has cleanup rules for the gaps between those steps. If inserting the record fails, it attempts to remove the newly saved file without deleting one already owned by an existing record. If the same photo ID is tried again and no record exists, leftover files for that ID are cleared before the new attempt. That’s not an automatic cleanup system for every abandoned file; it is a narrowly defined recovery path.</p><h3>The failure that makes the decision real</h3><p>The current development slice adds a layer in front of that storage mechanism. It checks the incoming file’s JPEG structure while the bytes are being read, and it translates low-level failures into results that a future screen could understand.</p><p>The slice is still under engineering review, and nothing in the app calls this staging interface from a camera or photo picker yet. But there are recorded tests for it.</p><p>One test starts with a structurally complete JPEG and an inspection ID that doesn’t exist.</p><p>The file gets written and moved into place. Then the database refuses to create its record because the inspection isn’t there. For a brief moment, the file is ahead of the database.</p><p>The storage code responds by removing that file and returning the original failure. The test checks that there is no photo record, no final photo file, and nothing left in the folder.</p><p>That’s the case I find most useful. It shows the cost of saving the record last-and tests the cleanup needed when that choice meets a real failure condition.</p><p>Another test cuts a JPEG short. The structural checker only discovers the missing ending after reading the incoming bytes. By then, some bytes have reached the temporary file. The write is rejected, the temporary file is removed, and no photo record is created.</p><p>These are controlled tests using synthetic images, not photos taken in the field. They were recorded during development on November 7, not rerun for this article. Still, they’re much more useful to me than a thumbnail that merely looks right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbM7dM00VlL4OQXi.png" /></figure><p><em>The save path and the two failure cases covered by the recorded November 7 tests, which used synthetic JPEGs. The files and the database are separate systems, not one transaction.</em></p><h3>What I still can’t claim</h3><p>There is no camera capture flow, photo picker, or completion screen calling this staging code. The JPEG samples came from Android’s encoder or test fixtures, not a real camera. The checker examines JPEG structure; it doesn’t prove that the whole picture can be decoded.</p><p>The tests also don’t kill the app halfway through a write or simulate a power cut. Some recovery cases are tested by constructing leftover files, and a database-reopen test creates a fresh storage object without restarting the operating-system process. Those are narrower claims than “survives a crash.”</p><p>Two simultaneous staging attempts for the same photo ID were tested within one process. That doesn’t establish what happens across processes. There’s no general cleanup job for photos that are never used, either.</p><p>And some important failures remain untested: a full disk, failed rename or flush, and failed deletion during compensation. The recorded tests show cleanup for the failure cases they exercise, not an absolute guarantee that every error leaves the storage perfectly clean.</p><p>Finally, saving locally doesn’t prove a server will accept the image later. The reference API has a development-only size default, while the app has no matching photo-size limit yet. That compatibility question is still open.</p><h3>What I want “Saved” to mean</h3><p>For now, a successful staging result is a limited promise: the incoming bytes passed a structural JPEG check, the file was written, and a database record was created with its identity, size, fingerprint, and link to an existing inspection.</p><p>It isn’t proof of a real camera workflow, a successful server upload, or survival after a power cut. And it doesn’t mean the feature is ready to ship.</p><p>I could put a camera button on the screen before resolving all of that. It would probably make the app feel further along.</p><p>But I’d rather have fewer things on screen and know exactly what they mean.</p><p><em>Development note: This is work in progress, developed with AI-assisted tooling. The behavior described here is based on code review and recorded tests, not new test runs conducted for this article.</em></p><p><em>Originally published at </em><a href="https://epicnesia.id/blog/why-im-building-photo-storage-before-the-camera-screen/"><em>https://epicnesia.id</em></a><em> on November 9, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ea08b0ec39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Offline-First: Saving Locally Is the Easy Part]]></title>
            <link>https://medium.com/@taufikfredipratama/flutter-offline-first-saving-locally-is-the-easy-part-09bfa4c8f5fc?source=rss-3b22395fd2aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/09bfa4c8f5fc</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Taufik Fredi Pratama]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 00:00:04 GMT</pubDate>
            <atom:updated>2026-11-05T17:38:30.805Z</atom:updated>
            <content:encoded><![CDATA[<p>What an offline-first Flutter app needs beyond a local write: pending operations, atomic Drift transactions, and honest delivery states, tested in a small lab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*12qbgLFwbgbJ7xXY.png" /></figure><p>A successful local write tells you that the local database accepted the data. It does not tell you that a remote system received, accepted, or committed the operation.</p><p>That distinction is easy to lose once the happy path works. You tap save, the note shows up in the list, and the screen looks finished. What the app believes about the server is a separate piece of state, and it needs to be modeled on purpose. (How well a write survives a crash or power loss is a different question again, and this article does not test it.)</p><p>For this experiment, I wanted to separate the moment a note was stored from the moment a remote service acknowledged it. I built a small Flutter lab called Field Note Lab to see what that separation takes in code and in tests.</p><p>Some boundaries first. The lab is a standalone demo. It is not a port of any product and not a synchronization framework. The “remote” is a deterministic fake that returns scripted outcomes, so nothing here says anything about a real server. Delivery is triggered manually, so there is no background scheduler. The lab code and the test runs were produced in an AI-assisted session with Claude Code; I set the questions and the boundaries, and the results below are taken from the recorded runs of that session. The tests ran with flutter test on a Windows host. I did not manually run or test the complete desktop application, and no Android or iOS device was involved.</p><h3>One flag is not enough</h3><p>Flutter’s offline-first guide covers two relevant things, in two different places. Under <a href="https://docs.flutter.dev/app-architecture/design-patterns/offline-first#offline-first-writing">Offline-first writing</a>, the app stores the new data in the local database first and then tries the API call, and the guide warns that if the network call fails, the local database and the API service are no longer in sync. Later, under <a href="https://docs.flutter.dev/app-architecture/design-patterns/offline-first#storing-a-synchronization-flag">Storing a synchronization flag</a>, it uses a boolean synchronized field: send to the API only while the flag is false, and set it to true when the request succeeds. The examples leave error handling as placeholder comments, which is reasonable for an illustration.</p><p>A boolean has two values, and the lab wanted to say more than two things. So each note gets a pending operation with one of four persisted statuses:</p><ul><li>pending: saved locally, and no delivery attempt has been recorded</li><li>retryable_failure: an attempt ended without an acknowledgment, either because the remote returned an explicit transient failure response, or because no response arrived at all</li><li>acknowledged: the remote side said it accepted the operation</li><li>rejected: the remote side explicitly refused it</li></ul><p>acknowledged and rejected are terminal in this experiment. There is also a &quot;sending&quot; state, but it exists only in the ViewModel&#39;s memory and is never written to disk.</p><p>One caveat on pending. The lab records an attempt after the remote call returns. If the process died in the middle of a call, nothing would be recorded and the operation would still look pending. I did not test that case, so &quot;no attempt recorded&quot; is as strong as the wording can get.</p><h3>Write the note and its operation together</h3><p>Without a transaction, a failure after inserting the note but before inserting its pending operation could leave an orphaned note. The normal delivery path would have no operation to pick up. So the lab inserts both rows in one Drift transaction:</p><pre>Future&lt;void&gt; insertNoteWithOperation({<br>  required FieldNoteRow note,<br>  required PendingOperationRow operation,<br>}) {<br>  return _db.transaction(() async {<br>    await _db.into(_db.fieldNotes).insert(note);<br>    await afterNoteInsertHook?.call();<br>    await _db.into(_db.pendingOperations).insert(operation);<br>  });<br>}</pre><p>afterNoteInsertHook is a test seam and is null in the app. The test sets it to throw, which puts a failure between the two inserts. After the exception, the test checks that both tables are empty. Then it closes the database, reopens the same file on disk, and checks again. Both checks find zero notes and zero operations.</p><p>A passing test only means something if it can fail. So during the lab work the assistant also ran a one-off mutation check: it temporarily removed the transaction wrapper, so the two inserts ran one after the other, and re-ran only that test. The test failed with Expected: &lt;0&gt;, Actual: &lt;1&gt;. The note was still there, orphaned, without its operation. The wrapper was then restored and the full suite passed again. This check is in the session log, not in the test suite, and I have not repeated it since.</p><p>To me this is the most useful result of the lab. It is a small thing, but it showed that the atomicity came from the transaction itself and not from the code happening to run in the right order.</p><h3>The operation ID is created once</h3><p>The repository generates the note ID and the operation ID when the note is created, and builds the payload snapshot at the same moment. Each later attempt reads the stored operation and sends that ID. One test scripts two transient failures and then an acceptance, and asserts that the fake remote received the same operation ID three times, with attempt numbers 1, 2 and 3.</p><p>That is only about what the client sends. The fake does not de-duplicate anything. For repeated IDs to mean something, a real server would have to cooperate, and nothing here tests that.</p><h3>Four outcomes, three answers</h3><p>The fake can be scripted with four outcomes: accepted, a transient failure response, an explicit rejection, and a lost response. The first three produce something the client can read. The fourth does not. In the repository, the handling looks like this. This is an abridged excerpt, not a standalone example that compiles: the remaining request arguments and the declarations of to and error are left out.</p><pre>try {<br>  final response = await _remote.deliver(<br>    RemoteRequest(<br>      operationId: current.operationId,<br>      // noteId, payload and attemptNumber trimmed from this excerpt<br>    ),<br>  );<br>  switch (response) {<br>    case RemoteAccepted():<br>      to = DeliveryStatus.acknowledged;<br>    case RemoteTransientFailure(:final statusCode, :final message):<br>      to = DeliveryStatus.retryableFailure;<br>      error = &#39;HTTP-like $statusCode: $message&#39;;<br>    case RemoteRejected(:final reason):<br>      to = DeliveryStatus.rejected;<br>      error = reason;<br>  }<br>} on RemoteTransportException catch (e) {<br>  // No response: this is NOT proof that the remote did nothing.<br>  to = DeliveryStatus.retryableFailure;<br>  error = &#39;No response: ${e.message}&#39;;<br>}</pre><p>RemoteResponse is a <a href="https://dart.dev/language/class-modifiers#sealed">sealed class</a>, and the switch uses <a href="https://dart.dev/language/patterns">patterns</a>, so the compiler checks that every response type is handled. If I add another response type later, this code stops compiling until I decide what it means.</p><p>Rejection gets its own status. A transient failure response and a lost response both end up as retryable_failure, but they are stored with different details in lastError: an &quot;HTTP-like 503&quot; message in one case, &quot;No response&quot; in the other. Neither is an acknowledgment, and neither tells the client what happened on the other side.</p><p>The last branch is the one I care about most. In the lost-response test, the fake applies the request and then throws a transport exception, as if the reply never arrived. The client ends in retryable_failure, which is all it can honestly say, while the fake&#39;s own record shows the request was applied. The test then delivers again. The second attempt is acknowledged, the fake has received the same operation ID twice, and it has applied it twice, because this fake does not de-duplicate. That is the point of the scenario: a missing acknowledgment is not the same as nothing having happened, and avoiding duplicate effects has to be handled by the remote side. This lab does not claim to handle it.</p><p>The database update enforces one more rule: a row can only change while it is pending or retryable_failure. Terminal operations are not sent again, and a test asserts that the fake saw a single request after an acceptance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L-jFFXa_mUDOXNV0.png" /></figure><p><em>A local save only stores the note and a pending operation. What the remote did is a separate, simulated fact.</em></p><h3>What the screen is allowed to say</h3><p>The screen reads the same state. Every note shows “Saved locally”, and below it one delivery label: “Pending delivery”, “Delivery failed — retry available”, “Acknowledged (simulated)”, or “Rejected” with the stored reason. While an attempt is in flight it shows “Sending (simulated)…”. There is no “Sync complete” anywhere, and a widget test checks that the string is absent.</p><p>The ViewModel is a plain ChangeNotifier, and the screen listens through ListenableBuilder. That was enough here; I did not need a state management package to get it. The widget tests drive the real repository against an in-memory SQLite database and the scripted fake. They verify what the UI shows, and they say nothing about disk durability, which the persistence tests cover. Flutter&#39;s <a href="https://docs.flutter.dev/app-architecture/case-study/testing">Testing each layer</a> page is a good companion read on testing the layers separately.</p><h3>What this does and does not show</h3><p>In this lab, run on a desktop host, the tests show that:</p><ul><li>A local save creates a note and one pending operation, with no acknowledgment.</li><li>The data and the delivery state survive closing and reopening the same SQLite file.</li><li>The note and its operation are written atomically for the one failure point I injected.</li><li>The operation ID stays the same across attempts.</li><li>Rejection gets its own status, while a transient failure and a lost response share retryable_failure and differ only in their stored diagnostics.</li></ul><p>They do not show:</p><ul><li>That any real server is idempotent, or that anything is delivered exactly once.</li><li>What happens when the process is killed mid-request, or after a reboot.</li><li>What happens on an Android or iOS device.</li><li>What happens when two delivery calls for the same operation run at the same time. The ViewModel ignores a second tap while one is in flight, but the repository has no such guard and no test covers it.</li><li>Behavior across multiple devices, or conflict resolution.</li><li>Anything about production readiness.</li></ul><h3>Environment and reproducibility</h3><p>All results come from flutter test on a Windows 11 desktop host, with Flutter 3.41.7 (stable) and Dart 3.11.5. The resolved packages were drift 2.34.4, drift_dev 2.34.0, sqlite3 3.5.2 and build_runner 2.15.1. With this Flutter version, the newest drift_dev would not resolve alongside Flutter&#39;s pinned meta package, so those versions are what the solver produced without overrides. There is no public repository for the lab, so the code in this article is excerpted from a local project that readers cannot clone.</p><h3>Where this leaves me</h3><p>The local write took a few lines. Most of the work was deciding what the app is allowed to believe afterwards, and writing tests that could catch it believing too much.</p><p>If I took one rule from this, it would be to give delivery its own persisted state and write it in the same transaction as the data. Rejection gets its own status. A failure response and a missing response are both retryable, they carry different diagnostics, and neither one counts as an acknowledgment. The operation keeps one identity across attempts, and the interface says only what the app actually knows.</p><p><em>Sources: </em><a href="https://docs.flutter.dev/app-architecture/design-patterns/offline-first"><em>Offline-first support</em></a><em>, </em><a href="https://docs.flutter.dev/app-architecture/case-study/testing"><em>Testing each layer</em></a><em>, </em><a href="https://dart.dev/language/class-modifiers"><em>Class modifiers</em></a><em> and </em><a href="https://dart.dev/language/patterns"><em>Patterns</em></a><em> from the official Flutter and Dart documentation.</em></p><p><em>Originally published at </em><a href="https://epicnesia.id/blog/flutter-offline-first-saving-locally-is-the-easy-part/"><em>https://epicnesia.id</em></a><em> on November 5, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09bfa4c8f5fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WorkManager Can Retry Your Work. It Can’t Make Your Server Idempotent.]]></title>
            <link>https://medium.com/@taufikfredipratama/workmanager-can-retry-your-work-it-cant-make-your-server-idempotent-084d2d2b0342?source=rss-3b22395fd2aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/084d2d2b0342</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[offline-first]]></category>
            <dc:creator><![CDATA[Taufik Fredi Pratama]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 00:00:54 GMT</pubDate>
            <atom:updated>2026-11-03T15:31:18.298Z</atom:updated>
            <content:encoded><![CDATA[<p>WorkManager can send an operation again. Only the server can stop it applying twice. What the Field Ops tests show, and what they don’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IYN907i6kO3u-xk_.png" /></figure><p>In the last article I said the delivery path in Field Operations Kit is at-least-once with idempotent processing. This one is about the second half of that sentence, because it’s the half people tend to assume WorkManager covers.</p><p>It doesn’t, and the smallest scenario shows why.</p><h3>The request that succeeded but looked failed</h3><p>Here’s an illustrative scenario. The technician, the inspection and the id OP-001 are made up, and the Field Ops Work screens aren&#39;t finished, so no shipped workflow is behind it. Say a technician finishes an inspection and the app stores an operation in its outbox as OP-001. (Real ids are random UUIDs.)</p><p>Attempt 1: the phone sends OP-001. The server applies it, commits the change and records an outcome for OP-001. Then the connection drops, and the response never arrives.</p><p>From the phone’s side, that looks exactly like a request the server never received. A timeout doesn’t say which. Both histories leave the same unacknowledged row in the outbox.</p><p>So the app sends it again. If the server treats the second request as new work, the business effect happens twice. The client can’t prevent that, because it can’t see what it would need to know.</p><h3>What WorkManager can actually do</h3><p>I use WorkManager for scheduling, and I want to be precise about what that buys me. These points come from the current Android documentation (the define-work and manage-work pages).</p><ul><li>A worker can return Result.retry(), and the work is rescheduled according to a backoff delay and policy. The documented default is exponential backoff with a 30-second delay, the minimum you can configure is 10 seconds, and the docs say backoff delays are inexact. Field Ops doesn&#39;t use the 30-second default. It configures exponential backoff starting from WorkRequest.MIN_BACKOFF_MILLIS, the 10-second minimum.</li><li>A constraint such as a connected network defers the work until it’s met. The docs also say the exact run time depends on constraints and system optimizations, so I don’t build on any precise timing.</li><li>Unique work means one chain of work per name. With APPEND_OR_REPLACE, a new request is chained behind the existing one and still runs if the earlier one failed or was cancelled.</li></ul><p>Here’s how Field Ops configures it. The excerpt combines OperationOutboxDrainScheduler ( enqueueUniqueWork is in its requestDrain(), drainRequest() in its companion) with one line from OperationOutboxDrainWorker.doWork(). Both classes share OperationOutboxDrainWorker.kt. It&#39;s reformatted and isn&#39;t standalone.</p><pre>// OperationOutboxDrainScheduler.requestDrain()<br>workManager.enqueueUniqueWork(<br>    &quot;operation-outbox-drain&quot;,<br>    ExistingWorkPolicy.APPEND_OR_REPLACE,<br>    drainRequest(),<br>)<br><br>// OperationOutboxDrainScheduler.drainRequest()<br>fun drainRequest(): OneTimeWorkRequest =<br>    OneTimeWorkRequestBuilder&lt;OperationOutboxDrainWorker&gt;()<br>        .setConstraints(<br>            Constraints.Builder()<br>                .setRequiredNetworkType(NetworkType.CONNECTED)<br>                .build(),<br>        )<br>        .setBackoffCriteria(<br>            BackoffPolicy.EXPONENTIAL,<br>            WorkRequest.MIN_BACKOFF_MILLIS,<br>            TimeUnit.MILLISECONDS,<br>        )<br>        .build()<br><br>// OperationOutboxDrainWorker.doWork(): OperationDrainResult.Retry -&gt; Result.retry()</pre><p>Look at what the unique name identifies. &quot;operation-outbox-drain&quot; is one chain that drains the whole outbox. It says nothing about OP-001. That&#39;s a statement about my scheduling, not about a remote business effect.</p><p>So there are four different things, and each belongs to someone different:</p><p>The drain’s work identity ( operation-outbox-drain)</p><p>WorkManager</p><p>The business operation’s identity ( OP-001)</p><p>my app, persisted in Room</p><p>One HTTP attempt</p><p>the network, and nobody’s promise</p><p>The business effect</p><p>the server</p><h3>Why one operation needs one identity</h3><p>The client’s half of the contract is small, and it’s about not changing anything between attempts. operationId is generated once, when the operation is written to the outbox, and the payload is stored as a snapshot beside it. Delivery builds the request only from those persisted fields. In DeliverOperationAttemptUseCase, prepare() constructs the request from the stored row, and a unit test checks that it&#39;s built from persisted data only. A retry is therefore the same request, even if the local data has moved on.</p><p>The client also decides which failures are worth retrying. Network failures, 5xx and 429 map to RetryLater. A SEQUENCE_BLOCKED response means wait. An IDEMPOTENCY_MISMATCH or an invalid operation is held for attention and isn&#39;t retried automatically, because sending the same bad request again can&#39;t help. DeliverOperationAttemptUseCaseTest asserts those mappings against a scripted fake transport.</p><p>None of this makes the server safe. It just makes sure the server is asked the same question each time.</p><h3>The server has its own job</h3><p>The reference API is a small Ktor and PostgreSQL service. Operations arrive as PUT /api/v1/operations/{operationId}. The part that matters is PostgresStartWorkApplication, and these are the lines that do the deduplication, trimmed and reformatted from the source:</p><pre><br>lockOperationId(c, operationId)   // pg_advisory_xact_lock keyed by operationId<br>findLedger(c, operationId)?.let { return classify(it, fingerprint) }<br>// ... lock the Work Order, check baseVersion and lifecycle ...<br>insertLedger(c, record)  // ON CONFLICT (operation_id) DO NOTHING<br>// ... guarded updates, audit event ...<br><br>private fun classify(<br>    stored: OperationLedgerRecord,<br>    fingerprint: String,<br>): OperationApplyResult =<br>    if (stored.requestFingerprint == fingerprint) {<br>        OperationApplyResult.Success(<br>            OperationReceipt(<br>                stored.operationId,<br>                stored.acknowledgedAt,<br>                stored.resultingServerVersion,<br>            ),<br>            replayed = true,<br>        )<br>    } else {<br>        failure(<br>            OperationErrorCode.IDEMPOTENCY_MISMATCH,<br>            &quot;operationId was already used for a different request.&quot;,<br>        )<br>    }</pre><p>Reading that against the contract I think the server needs:</p><ul><li><strong>A recorded outcome per operation.</strong> The operation_ledger table is keyed by operation_id, with a fingerprint, the acknowledgement time and the resulting server version. The receipt isn&#39;t stored as raw JSON. It&#39;s rebuilt from those fields.</li><li><strong>Recognising a repeat.</strong> The ledger lookup comes first. A match with an equal fingerprint returns the stored receipt and changes nothing.</li><li><strong>Rejecting a changed payload.</strong> The fingerprint is a SHA-256 over a canonical rendering of the request, with operationId deliberately excluded. Same id with a different fingerprint is a 409 IDEMPOTENCY_MISMATCH; that status is defined in OperationResponses.kt.</li><li><strong>No partial commit.</strong> The effect, the ledger row and the audit event are one PostgreSQL transaction. It commits only for a first-seen success. A test makes the last statement fail, after the ledger and state were already written, and checks that everything rolled back.</li><li><strong>Concurrency.</strong> The mechanism is a PostgreSQL transaction-scoped advisory lock keyed by the operation id, which serialises appliers of the same operation, plus the unique ledger key as the last line of defence. That’s the design. The tests cover less: eight concurrent requests, and a fresh application instance on the same database. Independent server processes and other deployment topologies are untested.</li></ul><p>Those rules are tested against a real PostgreSQL started by Testcontainers, not a fake. One test replays the same operation through a fresh application instance against the same database, with a different clock, after the state has moved on, and gets the original receipt. Another fires eight identical requests in parallel from one test run and asserts exactly one non-replayed result, one shared receipt, one ledger row and one audit event.</p><h3>The failure case in the campaign</h3><p>The lost-response scenario is campaign test P0-D, DeliveryRecoveryCampaignTest.d_lostAcknowledgement_isRecoveredByIdempotentReplayOfTheSameRow. Here&#39;s what it does, and what that means.</p><p>It starts work on a Room database, so a real outbox row exists, builds the request from that row, sends it once over the real Retrofit transport to the reference API, and discards the receipt without applying it. The row is still pending, the local version unchanged. After that it calls the production DeliverOperationAttemptUseCase for the same operation.</p><p>The assertions: exactly two HTTP calls to the same /api/v1/operations/&lt;id&gt; path, both 200, with identical response bodies. The outbox row is gone afterwards and the local version is 2. The runner then asserts in SQL that the server holds one ledger row and one audit event.</p><p>It ran on a physical Android phone against a disposable PostgreSQL in Docker, and passed in three recorded executions. The “lost” response was a receipt the test chose to drop, so what’s verified is the state a lost response would leave behind.</p><p>That’s two attempts and one business effect, in one controlled scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4YqiDXnm5vt4-LEr.png" /></figure><p><em>The P0-D scenario against the reference API. It describes one controlled test, not a guarantee about delivery.</em></p><h3>What I still wouldn’t claim</h3><p><strong>Exactly-once.</strong> This article makes no exactly-once delivery claim. A request can arrive any number of times. The property demonstrated is narrower: one committed business effect for the tested operation identity and request contract.</p><p><strong>WorkManager-driven retry.</strong> The scenario above calls the delivery attempt directly. It does not go through the scheduler. Separately, instrumented tests check the worker’s result mapping, the request’s connected-network constraint and exponential minimum backoff, and the shared unique chain. They call doWork() or inspect the request. There&#39;s no recorded run where WorkManager really retries after a lost response, with a real delay between attempts.</p><p><strong>Process death and reboot.</strong> P0-D doesn’t kill the process. The campaign closes and reopens a Room file in a different scenario, which isn’t the same thing.</p><p><strong>The reference server.</strong> It’s my implementation, and the guarantees come from PostgreSQL features that the project’s tests exercise, not from the idea of a ledger. An in-memory map would lose its ledger on restart and wouldn’t protect two instances from each other. No server other than this one has been tested.</p><p><strong>Fresh results.</strong> The campaign and reference-API results come from the project’s records. The reference-API suite’s last recorded run is 2026–10–25. They weren’t rerun while this article was prepared, because Docker wasn’t available.</p><p><strong>A cheap experiment, with limits.</strong> As a cross-check, a small separate Ktor project was built outside the Field Ops tree while this article was prepared. It uses testApplication, an in-memory H2 database and a ledger keyed by operation id, with effect and ledger insert in one transaction. Five tests passed: first submission, identical retry, mismatched payload, a discarded response then a retry, and eight parallel identical requests producing one effect. It was run three times. It isn&#39;t Field Ops code and has no advisory locks, so it supports the shape of the argument and nothing more.</p><h3>What this changes about how I build</h3><p>I now treat retry scheduling and server idempotency as two separate responsibilities: the scheduler is the part that asks again, and the contract is the part that makes asking again safe.</p><p>That gives me a short checklist for any operation I add. Is its identity created once and persisted with the payload? Does a retry send exactly that? Does the server store an outcome in the same transaction as the effect? What happens with the same id and a different body, or when two copies arrive together?</p><p>If I can’t answer one of those from a test, I treat it as unproven. WorkManager can reschedule the work according to its retry policy and constraints. That doesn’t guarantee when delivery will succeed, or whether the server will apply an operation more than once. The second part is the contract’s job.</p><p><em>Originally published at </em><a href="https://epicnesia.id/blog/workmanager-retries-server-idempotency/"><em>https://epicnesia.id</em></a><em> on November 3, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=084d2d2b0342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I’m Building a Field Ops App for Places Without Reliable Internet]]></title>
            <link>https://medium.com/@taufikfredipratama/how-im-building-a-field-ops-app-for-places-without-reliable-internet-b92bc0aa11e3?source=rss-3b22395fd2aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b92bc0aa11e3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[field-service]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Taufik Fredi Pratama]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 00:00:41 GMT</pubDate>
            <atom:updated>2026-11-01T05:17:51.796Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m building the delivery engine before the screens. Here’s why saving work on a device and getting a server acknowledgment are two very different things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fM4IDi_sossxW9OI.png" /></figure><p>While building Epicnesia Field Operations Kit, I keep coming back to one deceptively simple word: “Done.”</p><p>What should it mean when someone finishes a job in a place with no reliable internet connection?</p><p>The Work screen isn’t finished yet, so this isn’t a story from a deployed app. It’s the design problem behind the delivery engine I’m building: recording an operation on the device doesn’t mean the server has acknowledged it.</p><h3>A problem I’m designing around</h3><p>Picture a technician in a plant room with no signal. They finish an inspection step and tap the button. The phone has the change. The server doesn’t, and it might not for hours. That’s an illustration, not a field report, but basements, plant rooms and remote sites make it an ordinary situation for field work.</p><p>An app for that work can’t wait for a signal, which is the whole reason to make it offline-capable. It does leave the app with a question it can’t dodge, because three different facts hide behind the word “done”. The change is saved on the device. The change is waiting for delivery. The server has acknowledged it.</p><p>A phone can speak honestly about the first one. It has to earn the right to speak about the third. If the screen blurs them together, the person holding it believes something the system hasn’t established.</p><h3>What the device can actually know</h3><p>In Field Ops, the middle fact is a row in an outbox table in Room. A row that exists means the operation is pending. When the server answers with a receipt, the app applies it and deletes the row.</p><p>There is no stored “synchronized” status. That’s a recorded decision in the project, not an oversight: the schema has no delivery-status column. A row either still exists or it has been removed after a receipt.</p><p>The consequence is easy to miss. An empty queue means nothing on this device is waiting. It doesn’t prove that the phone and the server agree about everything, because the outbox keeps no history, no last-sync time and no attempt count. The Sync screen is still being built, but one line of its copy is already committed, and it carries the idea: “Queued locally does not mean an operation is uploading or confirmed by the server.”</p><h3>How I’m building the delivery path</h3><p>The first decision is about writing. Starting work is one Room transaction: the status changes, one audit event and the outbox row are committed together or not at all. One of the tests forces the outbox insert to fail and then checks that the statuses and the audit event rolled back with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LNx_fQ_NUC1ONN-4.png" /></figure><p><em>An engineering model of the reference environment, not a shipped user flow. There is no “synced” state: a row either still exists or it has been removed after a receipt.</em></p><p>The operation gets its identity inside that same transaction. operationId is a random UUID, generated once and kept. The payload is stored too, as a snapshot. When delivery runs, the request is built only from persisted fields, so a retry is the same request even if the local data has moved on since.</p><p>That matters because of what the server does with it. My reference API, a small Ktor and PostgreSQL service, keeps a ledger keyed by operationId. If the same operation arrives again, it returns the original receipt. If the same id arrives with different content, it answers 409 IDEMPOTENCY_MISMATCH. So delivery is at-least-once with idempotent processing: a request may reach the server twice, and the second arrival is harmless. I&#39;m not claiming &quot;exactly once&quot;, and the project&#39;s own rules forbid it.</p><p>One scenario in the failure campaign covers the lost response. The device sends an operation, the server applies it, and the app throws the receipt away. The row is still pending, so the normal delivery path sends it again. The server returns the same receipt, byte for byte, and the ledger holds one row. That scenario ran on a physical Android phone against the reference API and a disposable PostgreSQL database, and it passed in the two recorded runs. Acknowledgement is then applied in one transaction: the Work Order’s server version moves forward, never backward, and the row is removed.</p><p>Completing work adds a wrinkle. Its required photos have to reach the server first, so that operation waits until they have.</p><h3>What Field Ops looks like today</h3><p>Epicnesia Field Operations Kit is an Android source-code foundation in Kotlin and Jetpack Compose, under active development. The reference domain is a Work Order with one Inspection, and two operations: start work and complete work. It has not been released, and I’m not giving it a date.</p><p>Today it’s more engine than app. Local persistence, the outbox and the delivery path have tests. The Work screens aren’t there, the Sync screen’s item presentation is unfinished, and there is no authentication.</p><h3>What I still can’t prove</h3><p>I’d rather list the gaps than let the tested parts stand in for them.</p><p><strong>Process death and reboot.</strong> One controlled campaign test closes the Room database and reopens the same file, and the held operation it checks comes back identical. That isn’t a process kill, and there’s no recorded test that kills the process or reboots the device. App-start recovery re-requests delivery when a pending row has nothing scheduled, but a row that was never scheduled before a reboot waits for the next launch.</p><p><strong>WorkManager-driven retry.</strong> Delivery runs as unique one-time work with a network constraint and exponential backoff. A test checks that configuration. The failure-campaign scenarios call the delivery attempt directly, so WorkManager-driven retry hasn’t been observed end to end.</p><p><strong>Rejections.</strong> When the server reports a version conflict, the app stores that on the row and stops sending it. That’s honest, but it isn’t resolution. There’s no workflow for deciding what should happen next, and nothing here covers more than one device.</p><p><strong>Evidence.</strong> The test results I cite come from the project’s own records, and they weren’t rerun for this article. The server is my reference implementation, not a production backend.</p><h3>What this work is teaching me</h3><p>My working position is that I would rather show an accurate pending condition than reassure someone with a “synchronized” label the system can’t prove. It sounds like a wording choice. In practice it forces the data model to know something worth saying. Today the model can tell a pending row from a held one, and it records why a row is held. It has no way to say “synced”. That much exists. The user-facing Sync presentation is still unfinished, so I can’t yet show how those states will read on screen, and I don’t plan to close that gap with a nicer label.</p><p>That leaves a question I want to dig into next: <em>WorkManager Can Retry Your Work. It Can’t Make Your Server Idempotent.</em> Retry can run the work again. Making the other end safe to hear the same request twice is a separate job.</p><p><em>Originally published at </em><a href="https://epicnesia.id/blog/building-field-apps-without-reliable-internet/"><em>https://epicnesia.id</em></a><em> on November 1, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b92bc0aa11e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why a Stock Number Needs a Movement History]]></title>
            <link>https://medium.com/@taufikfredipratama/why-a-stock-number-needs-a-movement-history-9972cb473dc8?source=rss-3b22395fd2aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9972cb473dc8</guid>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Taufik Fredi Pratama]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 00:00:21 GMT</pubDate>
            <atom:updated>2026-10-27T14:32:46.109Z</atom:updated>
            <content:encoded><![CDATA[<p>A quantity says what is available, not how it got there. How Inventory Kit records, orders, and reads back the movements behind a stock number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GWtD8Lg3QmSC5CY9.png" /></figure><p>The quantity tells me what’s available. The history helps me explain how it got there.</p><p>Picture a product that shows 12 units at Main Warehouse and 2 at Retail Store. Those numbers can be perfectly correct and still leave the next question unanswered. Right after the first 20 units were received, it was 20 and 0, so across the two locations there are six fewer units now. Where did those six go, and how did the store end up with two? The balance has no memory. It only holds the latest answer.</p><p>This is a follow-up to the overview in <a href="https://epicnesia.id/blog/why-offline-first-inventory-apps-are-harder-than-they-look/">Why Offline-First Inventory Apps Are Harder Than They Look</a>, where I argued that a number needs a history. This time I want to stay close to the code: what a movement actually is in Inventory Kit, how the history is ordered and read back, and what it does not promise. Everything below comes from the source and its tests, and I’ll point at the symbols as I go.</p><h3>Two things, written together</h3><p>Inventory Kit keeps two kinds of rows. inventory_balances holds the current quantity for one product at one location. stock_movements holds the individual changes. The balance table is keyed on product and location, and the DAO&#39;s own comment calls it &quot;a derived/materialized projection&quot; rather than editable master data.</p><p>So the stored balance is the number the app reads. Showing stock never replays the history; the overview repository’s documentation says outright that quantity comes from the materialized balance and not from a movement replay. The history is there for the other question.</p><p>That makes the model a hybrid, and the hybrid has a price: two things that must agree. Every write path has to touch both in the same transaction. I’ll come back to that.</p><h3>What a movement row records</h3><p>A movement is one signed change at one location. This is the entity, from StockMovementEntity.kt:</p><pre>data class StockMovementEntity(<br>    @PrimaryKey(autoGenerate = true)<br>    val ledgerSequence: Long = 0L,<br>    val id: String,<br>    val productId: String,<br>    val locationId: String,<br>    val type: MovementType,<br>    val quantityDelta: Long,<br>    val note: String?,<br>    val transferGroupId: String?,<br>    val createdAt: Long<br>)</pre><p>MovementType has five values: RECEIVE, ISSUE, TRANSFER_OUT, TRANSFER_IN and ADJUSTMENT. quantityDelta carries the sign, so an Issue is stored as a negative number rather than as a positive one with a &quot;this is an issue&quot; flag. Quantities are Long values scaled by 1000, which is why you will see 5_000L for five units in the tests.</p><p>Receive, Issue, Transfer and Adjustment each write their movement in InventoryRepositoryImpl. A completed Physical Count writes ordinary ADJUSTMENT rows with the note Physical count · &lt;session id&gt;, so a count result looks like any other correction instead of a special case.</p><p>Locations appear in the history in the simplest way available: every row has exactly one locationId. A transfer is therefore two rows, TRANSFER_OUT at the source and TRANSFER_IN at the destination, linked by a shared transferGroupId. Nothing in the ledger says &quot;from A to B&quot; as a single record. That sentence is assembled when the history is read.</p><h3>Following a quantity</h3><p>Here is an illustrative sequence, not a recorded fixture. One product, two locations, four operations:</p><ol><li>Receive 20 at Main Warehouse.</li><li>Transfer 6 from Main Warehouse to Retail Store.</li><li>Issue 4 at Retail Store.</li><li>Adjust Main Warehouse by -2, reason “Damaged in storage”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZsBXWqdO_h7msb7A.png" /></figure><p><em>Four operations, five movement rows, and the balances after each operation. The values are illustrative; the types, signs and the shared transfer group match the data model.</em></p><p>The stored balances end at 12 and 2. The history explains both. Main Warehouse: +20, -6, -2, which is 12. Retail Store: +6, -4, which is 2. The transfer is the one step that touches two locations, so it is the one step that takes two rows.</p><p>Notice what the balance alone could never tell you: that the two units missing from Main Warehouse were a damage adjustment and not an issue, and that the store’s 2 are what is left after an Issue of 4 units. Different histories can end at the same number. The history is the part that tells them apart.</p><h3>Reading it back</h3><p>Writing rows is the easy half. The history screen has to put them in a trustworthy order, and the obvious sort key is the wrong one.</p><p>createdAt is a device timestamp. Clocks can be changed, and two rows written in the same millisecond tie. Before database version 4, the order was in fact device time with the UUID as a tie-break. ledgerSequence replaced it: an INTEGER PRIMARY KEY AUTOINCREMENT that SQLite allocates inside the inserting transaction. Every ordered read in StockMovementDao sorts on it:</p><pre>SELECT * FROM stock_movements WHERE type IN (:types) ORDER BY ledgerSequence DESC LIMIT :limit</pre><p>createdAt stays on the row as a display timestamp. A test in LedgerSequenceTest pins that down by writing a row with a later insertion and an earlier timestamp (excerpt):</p><pre>insertRaw(&quot;first-written&quot;, createdAt = 9_000L) <br>insertRaw(&quot;second-written-clock-rolled-back&quot;, createdAt = 1_000L) <br><br>assertEquals(listOf(&quot;first-written&quot;, &quot;second-written-clock-rolled-back&quot;), ledger().map { it.id })</pre><p>The test’s ledger() helper reverses that same newest-first query, so this assertion lists rows oldest first; the same test also checks that the newest-first read, the one the history screen uses, puts the second-written row on top.</p><p>History is read in pages of 50 raw rows, newest first, with a cursor on ledgerSequence, so a long ledger is never loaded whole. The user can filter by movement type and by location.</p><p>The transfer pair makes paging interesting, because its two rows can land on different pages. MovementHistoryRepositoryImpl looks up the partner rows by transferGroupId and shows each pair once, at its anchor row. It only merges a pair when the group is sane: exactly one out and one in, the same product, the right signs, and equal magnitudes. If any of that fails, the rows are shown individually instead of being merged or hidden. The tests include malformed groups, such as a missing counterpart or a magnitude mismatch, and assert that the rows are preserved and no pair is fabricated.</p><p>One more detail worth knowing. The entries are labelled with the current product and location names, looked up when the history is displayed, not copies stored on each row. A test renames a product and checks that the history follows.</p><h3>Where consistency matters</h3><p>The history is only useful if it matches the balance, and that depends on both being written in the same transaction. In InventoryRepositoryImpl, each operation reads the balance, inserts the movement, and upserts the balance inside one database.withTransaction block. The tests cover the failure paths: a receive against a missing product or location returns Failed and leaves no movement and no balance row behind.</p><p>I wrote about the transfer case, where two movements and two balances share one boundary, in <a href="https://epicnesia.id/blog/making-multi-location-stock-transfers-atomic-with-room/">Making Multi-Location Stock Transfers Atomic with Room</a>, so I won’t repeat it here. The Physical Count case, where a stale count would cancel a legitimate Issue, is in the <a href="https://epicnesia.id/blog/why-offline-first-inventory-apps-are-harder-than-they-look/">first article</a>. Both lean on the same fact: for rows recorded under the current schema, the ledger has a reliable order, so “did anything move since then” is a question the database can answer. Rows migrated from database version 3 are the exception, as I note below.</p><h3>What the history does not guarantee</h3><p>This is where I’d rather be exact than reassuring.</p><p><strong>It is insert-only by API surface, not tamper-proof.</strong> StockMovementDao exposes an insert, reads, and no update or delete for normal operation. Its own documentation says this is &quot;enforced by omission rather than a DB trigger&quot;. There is one deliberate exception: demo reset deletes the ledger rows of the demo products. So I call it insert-only in the app&#39;s normal flow, not an immutable ledger. Anyone with access to the SQLite file can change it.</p><p><strong>Nothing in the app checks that the history adds up to the balance.</strong> I looked for it. The only place the ledger is replayed against balances is DemoFixtureValidator, which checks the built-in demo dataset. For real data the agreement comes from the write paths all using one transaction, not from a reconciliation job. I can&#39;t point you to a test that sums stored movements and compares them with stored balances after a sequence of real operations. That would be a reasonable test to add.</p><p><strong>Old rows keep their old order.</strong> A schema migration (database version 3 to 4, the one that added ledgerSequence) rebuilt the table. Its notes say every row was copied unchanged and none deleted or edited. Rows that existed before it were numbered in the earlier device-time order, so a clock anomaly in those rows can&#39;t be reconstructed.</p><p><strong>I haven’t run the instrumented tests for this article.</strong> Most of the tests I cite live in the Android instrumented ( androidTest) source set, which needs a device or emulator. I read them and describe what they assert; I&#39;m not claiming device-tested results.</p><p><strong>It is local.</strong> One device, one Room database. No cloud sync, no multi-device conflict handling, and no claim of an audit trail that would satisfy a regulator. The timestamps come from the device clock, which is exactly why they don’t decide the order.</p><h3>What I learned</h3><p>The balance and the history answer different questions, and it helps to stop expecting one to do the other’s job. The balance answers “how many”. The movement history answers “what changed, where, and in what order”. When a note is available, it can also help explain why. Keeping both is a cost I’d pay again, as long as every write path pays it in one transaction.</p><p>The other lesson was about order. Anything a user reads as “what happened first” needs an order the device clock can’t disturb. A database-assigned sequence is boring, and boring was the point.</p><p>I built this into Epicnesia Inventory Kit, a source-code Android inventory foundation in Kotlin and Jetpack Compose. If you want to see how the movements, balances and history screen fit together, the <a href="https://epicnesia.id/inventory-kit/">product page</a> has the details.</p><p><em>Originally published at </em><a href="https://epicnesia.id/blog/why-a-stock-number-needs-a-movement-history/"><em>https://epicnesia.id</em></a><em> on October 27, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9972cb473dc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Scan, Many Frames: Handing a Barcode to the App Once]]></title>
            <link>https://medium.com/@taufikfredipratama/one-scan-many-frames-handing-a-barcode-to-the-app-once-38ae73bbb378?source=rss-3b22395fd2aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ae73bbb378</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[barcode-scanner]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Taufik Fredi Pratama]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 00:00:06 GMT</pubDate>
            <atom:updated>2026-10-25T05:54:32.869Z</atom:updated>
            <content:encoded><![CDATA[<p>A camera can surface the same barcode across frames. How a small gate and a generation guard keep one scan cycle from becoming duplicate or stale results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IpAYa82IcHZID7jc.png" /></figure><p>When I hold a barcode in front of the camera, I have scanned once. The scanner pipeline sees something different. The camera produces consecutive frames, and the decoder can find the same logical barcode in more than one of them. From the app’s side, a single scan can arrive as several candidate results.</p><p>The question for the Inventory Kit scanner was how to turn those candidates into one result the app acts on, without picking a delay and hoping. Two small pieces do that: a class called ScanGate, and a generation counter in ScannerViewModel. This article walks through both, and through what their tests do and don&#39;t show.</p><h3>Why not just wait a moment</h3><p>The obvious fix is a timer: ignore detections for some number of milliseconds after the first one. I didn’t build that, because a time window can’t answer the questions that matter. It doesn’t know whether the app has finished with the previous result. It doesn’t know whether the barcode is still in front of the camera. And it doesn’t know whether the user has started a new scan.</p><p>The documentation on ScanGate says this directly. Its two-signal re-arm path waits for the host to acknowledge the result and for the barcode to be absent, and the docs state it plainly: &quot;Neither condition is time-based.&quot; The app as shipped ends a cycle with an explicit reset() when the user taps Scan Another, which I come back to below. I call it a single-consumption gate: it hands the app one accepted barcode per scan cycle, and a cycle ends when the app says so.</p><h3>A gate with two states</h3><p>The gate is a small state machine. It is either ready, or locked on a barcode. These are the types, from ScanGate.kt, lines 10 to 17, with the shared source indentation removed:</p><pre>sealed interface ScanGateState {<br>    data object Ready : ScanGateState<br>    data class Locked(<br>        val barcode: DecodedBarcode,<br>        val acknowledged: Boolean,<br>        val absent: Boolean,<br>    ) : ScanGateState<br>}</pre><p>Locked carries the barcode that took the lock and two flags I&#39;ll come back to. One AtomicReference holds this whole state, and acceptance is a single compare-and-set on it ( ScanGate.kt, lines 58 to 61, same indentation treatment):</p><pre>fun tryAcquire(barcode: DecodedBarcode): DecodedBarcode? {<br>    val locked = ScanGateState.Locked(barcode, acknowledged = false, absent = false)<br>    return if (current.compareAndSet(ScanGateState.Ready, locked)) barcode else null<br>}</pre><p>If the state is still Ready, the caller swaps in Locked and gets the barcode back. Otherwise the call returns null. A detection that arrives while the gate is locked is rejected whether it carries the same value or a different one, so a second code drifting into view can&#39;t take over the cycle.</p><p>BarcodeImageAnalyzer also looks at the gate before it decodes a frame. If the state isn&#39;t Ready, it closes the frame and returns. That check saves work, and I don&#39;t count on it for correctness. Decoding is asynchronous, so a frame can be in flight when the gate locks and finish afterwards. Its result still goes through tryAcquire and is rejected there like any other detection made while locked.</p><p>One more rule sits in front of the gate. If a single frame yields two or more distinct barcodes, the analyzer acquires nothing, because picking one would let the decoder’s internal ordering decide which product gets processed. Identical results within a frame collapse into one.</p><figure><img alt="State diagram of the shipped scan cycle: Ready to Locked when one of many callers wins tryAcquire(), later candidates rejected while Locked, and Scan Another calling reset() back to Ready. A separate dashed panel shows a tested re-arm capability, not wired into the current app flow, where acknowledge() and previousBarcodeBecameAbsent() return Locked to Ready once both have arrived, in either order." src="https://cdn-images-1.medium.com/max/1024/1*TgMNltSFoNexj0QIb6h-Bg.png" /></figure><h3>What the concurrency test shows</h3><p>The claim I most wanted a test for is that concurrent callers can’t both win. This is concurrentFrames_allowExactlyOneThroughPerArmedCycle, from ScanGateTest.kt, lines 152 to 174, shown with the shared source indentation removed:</p><pre>@Test<br>fun concurrentFrames_allowExactlyOneThroughPerArmedCycle() {<br>    val threads = 8<br>    val cycles = 3_000<br>    withPool(threads) { pool -&gt;<br>        val gate = ScanGate()<br>        repeat(cycles) { cycle -&gt;<br>            val accepted = AtomicInteger(0)<br>            val start = CyclicBarrier(threads)<br>            val done = CountDownLatch(threads)<br>            repeat(threads) {<br>                pool.execute {<br>                    start.await()<br>                    if (gate.tryAcquire(barcodeA) != null) accepted.incrementAndGet()<br>                    done.countDown()<br>                }<br>            }<br>            assertTrue(done.await(10, TimeUnit.SECONDS))<br>            assertEquals(&quot;cycle $cycle: exactly one frame may pass&quot;, 1, accepted.get())<br>            gate.reset()<br>        }<br>    }<br>}</pre><p>Eight real threads wait on a CyclicBarrier, then all call tryAcquire at once. The test counts how many get a barcode back, asserts that the count is one, resets the gate and goes again, 3,000 times. There are no sleeps. A check-then-act race in the gate could show up as two winners in a cycle.</p><p>What that shows is narrow: concurrent callers reaching the gate resolve to one winner per cycle. The app’s analysis executor has a single thread, so the test pushes harder than that setup does. The decoder’s results come back through ML Kit’s task listeners, and I haven’t pinned down which thread those run on, so I didn’t want the gate to depend on it. The test says nothing about how CameraX schedules frames on any particular phone. It also can’t tell me how often a real camera produces repeated detections. The gate is designed to stay safe when repeated candidates reach it.</p><h3>The second race is a late answer</h3><p>The gate decides who may start a scan result. It has nothing to say about whether that result is still wanted when the product lookup finishes.</p><p>The lookup is asynchronous. Say the lookup for code A is running and the user taps Scan Another, or types a code by hand. Lookup B starts. If A’s repository call returns after that, it must not overwrite what B is doing.</p><p>ScannerViewModel handles this with a generation counter. Starting a lookup, tapping Scan Another and submitting a manual code each advance it, under a lock that guards only that bookkeeping. Every lookup remembers the generation it started with, and publishing checks it. This is publishIfCurrent, from ScannerViewModel.kt, lines 143 to 148, with the shared source indentation removed:</p><pre>private fun publishIfCurrent(lookupGeneration: Long, outcome: ScannerStatus) {<br>    synchronized(lock) {<br>        if (lookupGeneration != generation) return<br>        setState { it.copy(status = outcome) }<br>    }<br>}</pre><p>If the numbers differ, the result is dropped. Success, not found, ambiguous and error outcomes all pass through this same check. I don’t rely on cancelling the old job for correctness. A comment in the code notes that a repository call can complete despite cancellation, so the generation check is what makes a stale answer harmless.</p><p>Two ownership rules sit alongside it. Camera detections are accepted only while the screen is in its Ready status, so a detection can&#39;t take over a pending lookup or replace a result already on screen. A manual submission is a deliberate user action, so it takes over: it cancels the pending lookup and invalidates it. The concurrency tests complete each lookup by hand, in an order the test picks, which makes these races deterministic. They show that the ordering rules hold. They aren&#39;t a measurement of real timing.</p><h3>What the app does after a scan</h3><p>This is where the shipped behaviour differs from what the gate can do. In the current Inventory Kit scanner, the first accepted barcode locks the gate, and it stays locked until the user taps Scan Another. That handler calls viewModel.onNewScanRequested() and then scanGate.reset(), which returns the gate to Ready unconditionally.</p><p>ScanGate also supports a two-signal re-arm path. The host calls acknowledge() once it has handled the result, and whatever owns presence tracking for the camera and decoder calls previousBarcodeBecameAbsent() when the barcode has left. The gate doesn&#39;t observe absence itself. When both signals have arrived, in either order, it goes back to Ready. The tests cover each signal alone being insufficient, both orders, and the two signals arriving from different threads. Production code supplies neither signal today, so reset() is the path the app takes, and the two-signal re-arm is a tested capability of the gate.</p><h3>What this doesn’t establish</h3><p>The gate’s own state is thread-safe: one AtomicReference holds it, and every transition is a compare-and-set apart from reset(), which sets the value directly. One concurrent attempt wins Ready to Locked. The ViewModel rejects stale lookup results using generations. JVM unit tests exercise all of that.</p><p>That is the extent of it. A gate and a generation counter don’t establish that a barcode can never be acted on twice somewhere further downstream. CameraX scheduling, decoder timing, camera hardware and differences between phones are outside what these tests cover, and JVM tests can’t stand in for trying the scanner on real hardware. Nothing here describes how any particular device behaves.</p><p>Scanning is the visible part of this feature in Inventory Kit. The part I find worth writing down sits behind it: who is allowed to start a result, and what happens to an answer that arrives after the question has changed. Those rules are small enough to read in one sitting, which is also what makes them testable.</p><p><em>Originally published at </em><a href="https://epicnesia.id/blog/one-scan-many-frames-barcode-gate/"><em>https://epicnesia.id</em></a><em> on October 20, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38ae73bbb378" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Multi-Location Stock Transfers Atomic with Room]]></title>
            <link>https://medium.com/@taufikfredipratama/making-multi-location-stock-transfers-atomic-with-room-0727b598ed43?source=rss-3b22395fd2aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/0727b598ed43</guid>
            <category><![CDATA[database-transaction]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[room-database]]></category>
            <dc:creator><![CDATA[Taufik Fredi Pratama]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 00:00:54 GMT</pubDate>
            <atom:updated>2026-10-12T13:13:25.078Z</atom:updated>
            <content:encoded><![CDATA[<p>A Room stock transfer is more than two balance updates. Here’s how I keep its checks, movement rows, and writes inside one transaction.</p><figure><img alt="Making Multi-Location Stock Transfers Atomic with Room." src="https://cdn-images-1.medium.com/max/1024/0*MwC4aVNA3N4vFGFx.png" /></figure><p>A stock transfer looks like subtracting in one place and adding in another. The hard part is making sure the checks, movement history, and balance updates share one transaction boundary.</p><p>Say Main Warehouse holds 10 units of a product and Retail Store holds 3. Someone transfers 4. The first version of this operation that comes to mind is two lines:</p><pre>source -= 4<br>destination += 4</pre><p>Now let the first write succeed and the second one fail. Main Warehouse says 6. Retail Store still says 3. Four units have entered another dimension.</p><p>The dangerous part is that the resulting data can still look plausible. That was the failure state I wanted the transfer operation to make impossible. This article walks through the Kotlin and Room code I used, and the test I use to check it.</p><h3>The half-finished transfer</h3><p>The failure needs no exotic cause. Any exception between the two writes will do. In my case a transfer also has to leave a history trail, so it is more than two numbers changing. It produces ledger entries and updates balances, and all of it has to agree.</p><p>The guarantee I wanted is easy to say: a transfer either happens completely or leaves nothing behind. No debit without a credit. No ledger row without the balance change that goes with it.</p><h3>One transfer, two signed rows</h3><p>First the data model. I record one transfer as two movement rows:</p><ul><li>TRANSFER_OUT with quantityDelta = -quantity, at the source location</li><li>TRANSFER_IN with quantityDelta = +quantity, at the destination location</li></ul><p>Both rows share one transferGroupId and one timestamp, and each keeps its own id. The movement history screen can collapse the pair into a single &quot;Main Warehouse → Retail Store&quot; entry, but underneath there are two rows. In normal application flow, movement rows are treated as insert-only history.</p><p>Here is the code that creates them, from InventoryRepositoryImpl.kt, lines 144 to 171, shown with the shared source indentation removed for readability:</p><pre>val now = System.currentTimeMillis()<br>// One transfer is two signed ledger rows sharing transferGroupId -<br>// both committed inside this same transaction, never independently.<br>val transferGroupId = UUID.randomUUID().toString()<br>stockMovementDao.insert(<br>    StockMovementEntity(<br>        id = UUID.randomUUID().toString(),<br>        productId = productId,<br>        locationId = sourceLocationId,<br>        type = MovementType.TRANSFER_OUT,<br>        quantityDelta = -quantity,<br>        note = note,<br>        transferGroupId = transferGroupId,<br>        createdAt = now<br>    )<br>)<br>stockMovementDao.insert(<br>    StockMovementEntity(<br>        id = UUID.randomUUID().toString(),<br>        productId = productId,<br>        locationId = destinationLocationId,<br>        type = MovementType.TRANSFER_IN,<br>        quantityDelta = quantity,<br>        note = note,<br>        transferGroupId = transferGroupId,<br>        createdAt = now<br>    )<br>)</pre><h3>The transaction boundary</h3><p>Here is where the transaction starts, and what happens before anything is written (lines 131 to 142):</p><pre>return try {<br>    database.withTransaction {<br>        val sourceQuantity = inventoryBalanceDao.getBalance(productId, sourceLocationId)?.quantity ?: 0L<br>        if (quantity &gt; sourceQuantity) return@withTransaction TransferResult.InsufficientStock<br><br>        val destinationQuantity = inventoryBalanceDao.getBalance(productId, destinationLocationId)?.quantity ?: 0L<br>        val newDestinationQuantity = try {<br>            Math.addExact(destinationQuantity, quantity)<br>        } catch (overflow: ArithmeticException) {<br>            return@withTransaction TransferResult.QuantityOverflow<br>        }<br>        val newSourceQuantity = sourceQuantity - quantity</pre><p>That snippet stops before the closing braces on purpose. The try and the withTransaction block keep going. Right after it come the two movement inserts shown above, then two balance upserts, one for the source and one for the destination. Those four writes sit inside the same withTransaction. The block then builds a TransferResult.Transferred and returns it.</p><p>A catch for SQLiteConstraintException sits outside the block and maps to TransferResult.Failed. A catch for SQLiteConstraintException sits outside the block and maps that database constraint failure to TransferResult.Failed. An exception escaping the transaction causes Room to roll it back; only SQLiteConstraintException is converted to Failed here.</p><figure><img alt="Comparison of separate stock-transfer writes with one atomic Room transaction containing validation, movement inserts, and balance updates." src="https://cdn-images-1.medium.com/max/1024/1*Hpp8mRR8Q_m0v7mZpFvc3A.png" /></figure><p><em>Left: two independent writes with a failure in between. Right: the same work inside one Room transaction, which commits all of it or rolls back all of it.</em></p><h3>Why the stock check lives inside</h3><p>Validation is split on purpose.</p><p>Outside the transaction, in the use case and again in the repository, are the checks that depend only on the arguments: the quantity has to be above zero, and the source has to differ from the destination. The repository repeats those checks so direct repository calls are still guarded.</p><p>Inside the transaction are the checks that depend on stored data: the source balance, the insufficient-stock check, the destination balance, and the overflow check. Quantities are stored as Long values scaled by 1000, and the overflow check uses Math.addExact.</p><p>The source check belongs inside because a balance read performed before entering the transaction creates a time-of-check/time-of-use window: the value can change before the write. Reading inside the transaction makes the read, the check and the write one unit. For that reason, the use case deliberately leaves the stored-balance check to the repository transaction.</p><p>Transfer and Issue reject a result that would go negative. Adjustment is the correction tool and can legitimately produce negative stock, so I only claim these two operations refuse to create it.</p><h3>Testing the rollback path</h3><p>The rollback test uses a destination location that doesn’t exist. The source side is valid, so validation passes and the TRANSFER_OUT row is inserted first. The TRANSFER_IN insert then references the missing location, and the locationId foreign key rejects that insert.</p><p>The test runs against a real in-memory Room database. Quantities are scaled Long values, so 5_000L means 5 units and 2_000L means 2 units.</p><p>Excerpted from the test; an outdated comment in the source is omitted here.</p><pre>fun transfer_destinationLocationDoesNotExist_rollsBackEntireTransactionAtomically() = runBlocking {<br>    inventoryRepository.receive(productId, locationId, quantity = 5_000L, note = null)<br><br>    val result = inventoryRepository.transfer(productId, locationId, &quot;missing-location&quot;, quantity = 2_000L, note = null)<br><br>    assertEquals(TransferResult.Failed, result)<br>    assertEquals(5_000L, database.inventoryBalanceDao().getBalance(productId, locationId)?.quantity)<br>    assertNull(database.inventoryBalanceDao().getBalance(productId, &quot;missing-location&quot;))<br>    assertNoTransferMovementsExist()<br>}</pre><p>The source starts with 5 units, and the test tries to move 2 to a destination that doesn’t exist. The TRANSFER_OUT insert runs first. The TRANSFER_IN insert then fails and the repository returns Failed.</p><p>The assertions check four things. The result is Failed. The source balance is still 5 units. No balance row exists for the missing destination. And assertNoTransferMovementsExist() counts zero TRANSFER_OUT or TRANSFER_IN rows in the ledger.</p><p>The last one carries the claim. The TRANSFER_OUT row had already been inserted when the next insert failed, and it is not in the table afterwards. The already-executed TRANSFER_OUT row was rolled back when the next insert failed.</p><h3>What that test proves, and what it doesn’t</h3><p>The failure happens at the second insert, before the two balance upserts are reached. So this test directly proves rollback of the earlier movement insert. It does not directly demonstrate a balance upsert being rolled back.</p><p>The source balance reads 5 units because that upsert never ran. Because the balance upserts sit inside the same transaction, the transaction boundary covers them too. This particular test simply never reaches that path, so it does not demonstrate their rollback directly.</p><h3>Two transfers, one source</h3><p>There is one more test for this. The source starts with 5 units, and two 3-unit transfers are started together. One succeeds. The other returns InsufficientStock. The source ends at 2 units, with exactly one TRANSFER_OUT row.</p><p>The test uses runBlocking with async, so it does not demonstrate thread-level parallel execution. It shows that the second transfer is rejected instead of pushing the source below zero.</p><h3>The boundary of the guarantee</h3><p>Everything above is local. It shows Room and SQLite atomicity inside one application process, against one local database, on one device.</p><p>It says nothing about multi-device atomicity or distributed transactions. V1 has no cloud sync and no backend conflict resolution. And I have no crash or power-loss test: nothing here kills the process mid-write and checks the result.</p><h3>The reusable lesson</h3><p>When several reads and writes together define one business invariant, keep the read, the validation and the write inside one transaction boundary. Here the invariant is that stock moves from one place to another or doesn’t move at all. The checks, both ledger rows and both balances belong in the same unit, so none of them can be left half done.</p><p>I built this for Epicnesia Inventory Kit, an Android project written in Kotlin and Jetpack Compose.</p><p><em>Originally published at </em><a href="https://epicnesia.id/blog/making-multi-location-stock-transfers-atomic-with-room/"><em>https://epicnesia.id</em></a><em> on October 12, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0727b598ed43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Offline-First Inventory Apps Are Harder Than They Look]]></title>
            <link>https://medium.com/@taufikfredipratama/why-offline-first-inventory-apps-are-harder-than-they-look-6eb0253c0cac?source=rss-3b22395fd2aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eb0253c0cac</guid>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Taufik Fredi Pratama]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 00:00:50 GMT</pubDate>
            <atom:updated>2026-10-04T06:18:04.156Z</atom:updated>
            <content:encoded><![CDATA[<p>A quantity looked simple until transfers and physical counts started overlapping. Notes from building a local-first Android inventory foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6h8Sdzw2-g72vEF.png" /></figure><p>The first version of an inventory app fits in one table:</p><pre>product_id<br>location_id<br>quantity</pre><p>Receive stock, add to the quantity. Issue stock, subtract. It works beautifully in a demo, which is where most inventory apps are at their most convincing.</p><p>I’m building Epicnesia Inventory Kit, an Android inventory foundation in Kotlin, Jetpack Compose and Room. This is the first piece in a series I’m calling <em>Building Offline-First Inventory</em>, and it’s an overview: the decisions that surprised me, not a tour of the code. That table lasted until the first time I asked it a question it couldn’t answer: <em>why is the number 22?</em></p><h3>A number needs a history</h3><p>A bare quantity tells you what the stock is. It can’t tell you how it got there, and in inventory the second question is the one people actually ask.</p><p>So every stock change leaves a movement behind. There are five types:</p><p>In the normal application flow, movement history is append-only: nothing edits or deletes a row to make the numbers look better. That’s a statement about how the app behaves, not a claim that the database is tamper-proof. Anyone with a debugger and enough free time can do what they like to a SQLite file.</p><p>I also store the balance for each product and location. I don’t replay the history to work out the current quantity. The balance is written alongside the movement that changed it, so reading stock stays cheap and the history is there for the “how did we get here” question. The price is two things that must always agree. Every write path has to update both or neither, and a surprising amount of the rest of the work is just making sure of that.</p><h3>Transfers: two rows, one transaction</h3><p>A transfer looks like one action to the person doing it. In the data it’s two movements: TRANSFER_OUT at the source location and TRANSFER_IN at the destination, linked by a shared transfer identifier.</p><p>Both rows and both balance updates go into a single local Room/SQLite transaction. Either everything commits or nothing does. Without that, a crash between the two writes sends your units off to join the missing socks in another dimension.</p><p>The guarantee is a local one: one device, one database, both sides or neither. I’m not claiming anything grander than that, and I’ll come back to why.</p><h3>Then reality shows up</h3><p>So far, every operation happened inside the database.</p><p>Physical counting introduces something databases are surprisingly bad at controlling: reality.</p><blockquote>“The map is not the territory.”</blockquote><blockquote>- Alfred Korzybski</blockquote><p>The database says 24. The shelf says 22.</p><h3>Physical Count</h3><p>Physical Count is a workflow, not a sixth movement type. You pick a location and start a count, and the app snapshots the expected quantity for every product there. Then you walk the shelves and enter what you actually find.</p><p>While the count is a draft, nothing changes. Balances stay where they are and no movements are written. You can save, leave and come back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aUiLr89jD_bwdTbw.jpg" /></figure><p><em>Expected, counted and variance stay visible before anything is completed. (Demo data.)</em></p><p>Completing the count is where the stock changes. Each non-zero variance becomes an ADJUSTMENT and the balance moves to the counted quantity. A line with zero variance, like the Webcam above, creates no movement at all. The count itself stays persisted as evidence of what was found.</p><p>The point is that a count never silently overwrites a balance. If the shelf disagrees with the database, the disagreement shows up as a movement you can read later.</p><h3>The edge case that changed the design</h3><p>While hardening the count flow I found an edge case that the straightforward path doesn’t expose.</p><p>Say a count starts for a product, and the app records what it expects:</p><pre>Expected 10 <br>Counted 10</pre><p>Everything matches. Before the count is completed, someone issues 4 units. The live balance is now 6.</p><p>Then the count is completed. A naive reconciliation compares the counted 10 against the live balance of 6 and concludes there’s a variance of <strong>+4</strong>:</p><pre>Expected         10<br>Counted          10<br>Issue            -4<br>Live balance      6<br>Naive adjustment +4</pre><p>That +4 quietly cancels a perfectly legitimate Issue. The count was right about the shelf at the moment someone looked at it. Completing it later made the computer confidently correct about the wrong moment in time.</p><p>The fix is to give the count a baseline in the stock history when it starts. At completion, the app checks whether anything relevant happened at that location after the baseline. If a counted product had a movement since then, including one that netted out to zero, or if its live balance no longer matches the snapshot, completion is rejected and nothing is written.</p><p>The recovery is explicit. The person restarts the count, which takes a fresh baseline, re-snapshots every line from the current balances and clears the counted quantities. Asking someone to count again is annoying. Letting the database politely lie to them is worse.</p><h3>What the history shows</h3><p>When a count does complete cleanly, the result lands in Movement History like any other stock change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-uHAPrm0-xv4YsBg.jpg" /></figure><p><em>Count adjustments appear in Movement History next to the transfers they sit among. (Demo data.)</em></p><p>The USB-C Cable shows its −2, tagged with the reason and the count session it came from. The same count found two Laptop Stands where the database expected none, so that one shows +2. Below them are the earlier transfers between the two locations. Nobody had to explain what happened, because the history says so.</p><h3>What “offline-first” means here</h3><p>The core inventory workflow runs entirely on a local database. Room is the local source of truth, and everything above (receiving, issuing, transferring, counting) works without a network connection, because it never needed one.</p><p>That makes the correctness guarantees local ones: this device, this database. Version 1 doesn’t ship a sync layer or a production backend. I’m not claiming it solves multiple devices, multiple users or distributed transactions, and I’m not making promises about what survives a reinstall or a device swap. Those are real problems with their own designs, and pretending a local transaction covers them is how you end up with a very confident bug.</p><h3>Where Inventory Kit fits</h3><p>Epicnesia Inventory Kit is a reusable, local-first Android inventory foundation: multi-location stock, movement history, transfers and physical count, built to be extended. It isn’t an ERP, a production backend or a multi-tenant SaaS, and it isn’t a finished answer for every client project. I’m trying very hard not to accidentally build an ERP.</p><p>Later pieces in the series go deeper into how these pieces are implemented in Room.</p><p><em>Originally published at </em><a href="https://epicnesia.id/blog/why-offline-first-inventory-apps-are-harder-than-they-look/"><em>https://epicnesia.id</em></a><em> on October 4, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eb0253c0cac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>