Protect offline IMAP state when UIDVALIDITY changes. Test mailbox-scoped cache reset, reused UIDs, failed pending markers and stale responses with SQLite.

Author: PracHub

Published: 11/30/2026

Mail Sync Interview: Can an Offline Client Reuse Saved Message IDs After a Mailbox Is Rebuilt?

November 30, 2026

Quick Overview

An original SQLite cache isolates account, mailbox, UIDVALIDITY and UID. It tests that a rebuilt inbox cannot inherit an old read marker, verifies other scopes remain intact and exercises local reset rollback and reopen.

Software EngineerFree

An offline client remembers UID 7 as an unread invoice and queues a read marker for it. The server rebuilds the mailbox while the client is disconnected. On reconnect, UID 7 exists again, but it belongs to a different message. Applying the old marker by UID number alone changes the wrong object.

The identity boundary is the mailbox’s UIDVALIDITY together with its UID, under the correct account and server context. A changed validity requires invalidating the old UID mapping before replaying UID-bound work. A cache refresh that downloads new rows but keeps the old pending actions is incomplete.

Practise this boundary in the Outlook-style email-service design. This article uses IMAP specifications and an original SQLite cache fixture. It reads no real email, connects to no mail server and sends no IMAP commands or messages.

UID7 from an old inbox generation cannot identify UID7 in its rebuilt replacement

Identify the message in its namespace

Official RFC 9051 defines UID identity within a mailbox and UIDVALIDITY context. Message sequence numbers are positions that can change after expunges; they are not durable offline identifiers. A UID also cannot be treated as globally unique across mailboxes or accounts.

For this original application schema, use account, mailbox, UIDVALIDITY and UID as the message key. The account label includes the appropriate server and login context. It is not an email address casually parsed from a message header.

The mailbox field in the fixture is a simple selected name. Production software must apply its protocol and naming rules and handle rename or mailbox-identity extensions deliberately. This article does not implement universal mailbox canonicalization or infer that names never change.

UIDVALIDITY is not a content version or a timestamp to compare against a message’s Date header. It protects the interpretation of UIDs in the mailbox. A newer-looking message body does not make a saved UID mapping valid after that namespace changes.

The model’s epoch column is its short name for the recorded UIDVALIDITY value. Numbers 101 and 202 are synthetic valid positive values, not real server response transcripts or evidence about the age of a mailbox.

Fail old UID-bound work before fetching replacements

RFC 4549’s disconnected-client guidance says that a validity change invalidates the mailbox cache and pending actions referring to its old UIDs. It is an informational synchronization document, while RFC 9051 supplies the current protocol identity definition. The fixture preserves failed-action evidence locally instead of replaying it.

That separation is important for user intent. A queued read marker describes a particular old message, not a wish to mark whichever future message receives the same number. Failing the old operation is safer than silently retargeting it.

The model stores failed_uidvalidity on the pending operation. That is an original local status label, not an IMAP response code. It allows a UI or support tool to explain why the offline action did not reach its intended remote object.

Do not erase independent offline work merely because one inbox reset. A locally composed draft or upload without a server-assigned UID has a different identity and recovery contract. The published schema does not model those operations, so its reset applies only to represented UID-bound markers.

Likewise, do not invent a correspondence using subject or sender. Two messages can share those fields. Even a Message-ID header serves a different purpose from the mailbox UID namespace, and this fixture implements no automatic remapping heuristic.

Use overlapping UIDs to test isolation

The original dataset has three messages, all with UID 7. Alice’s INBOX has validity 101, Alice’s Archive has validity 80 and Bob’s INBOX has validity 101. Their bodies and owners differ despite the shared number.

ScopeBefore reconnectAfter Alice’s inbox rebuild
Alice, INBOXvalidity 101, UID 7, old invoicevalidity 202, UID 7, different message
Alice, Archivevalidity 80, UID 7, archived messageUnchanged
Bob, INBOXvalidity 101, UID 7, Bob’s messageUnchanged

Only Alice’s rebuilt inbox loses its old cache mapping. Her queued old-invoice marker becomes failed. After fetching the new UID 7 under validity 202, that new row remains unread.

Alice’s Archive marker is still eligible because its validity did not change. Bob’s message remains unread and untouched. These controls catch both an overly broad account-wide purge and a dangerously narrow UID-only update.

The example does not claim that a mailbox rebuild must reuse UID 7. It deliberately chooses reuse because that makes an incorrect key visibly harmful. The same rule applies when the new UID list overlaps only partially or not at all.

Execute the local SQLite cache fixture

The program uses Python’s standard library and a disposable SQLite file. It simulates selecting a mailbox, accepting fetched messages and applying a queued marker to local cache state. No remote STORE command is sent, and applied means only this local simulation.

import sqlite3
from tempfile import TemporaryDirectory

SCHEMA = """
CREATE TABLE IF NOT EXISTS mailbox(
 account TEXT, box TEXT, epoch INTEGER, PRIMARY KEY(account,box));
CREATE TABLE IF NOT EXISTS message(
 account TEXT, box TEXT, epoch INTEGER, uid INTEGER, body TEXT, seen INTEGER,
 PRIMARY KEY(account,box,epoch,uid));
CREATE TABLE IF NOT EXISTS pending(
 id TEXT PRIMARY KEY, account TEXT, box TEXT, epoch INTEGER, uid INTEGER, state TEXT);
"""

def select_box(db, account, box, epoch, fail=False):
    with db:
        old=db.execute("SELECT epoch FROM mailbox WHERE account=? AND box=?",
                       (account,box)).fetchone()
        if old and old[0] != epoch:
            db.execute("UPDATE pending SET state='failed_uidvalidity' "
                       "WHERE account=? AND box=? AND state='queued'",(account,box))
            db.execute("DELETE FROM message WHERE account=? AND box=?",(account,box))
            if fail:
                raise RuntimeError("injected before epoch commit")
        db.execute("INSERT OR REPLACE INTO mailbox VALUES(?,?,?)",(account,box,epoch))

def ingest(db, account, box, epoch, uid, body):
    with db:
        current=db.execute("SELECT epoch FROM mailbox WHERE account=? AND box=?",
                           (account,box)).fetchone()
        if current != (epoch,):
            return False
        db.execute("INSERT INTO message VALUES(?,?,?,?,?,0)",(account,box,epoch,uid,body))
        return True

def mark_seen_locally(db, operation):
    # Local replay simulation only: no IMAP STORE is sent.
    with db:
        row=db.execute("SELECT account,box,epoch,uid,state FROM pending WHERE id=?",
                       (operation,)).fetchone()
        account,box,epoch,uid,state=row
        if state != "queued":
            return False
        current=db.execute("SELECT epoch FROM mailbox WHERE account=? AND box=?",
                           (account,box)).fetchone()
        if current != (epoch,):
            return False
        n=db.execute("UPDATE message SET seen=1 WHERE account=? AND box=? "
                     "AND epoch=? AND uid=?",(account,box,epoch,uid)).rowcount
        if n:
            db.execute("UPDATE pending SET state='applied' WHERE id=?",(operation,))
        return bool(n)

with TemporaryDirectory(prefix="prachub-imap-cache-") as root:
    path=root+"/cache.sqlite"; db=sqlite3.connect(path);db.executescript(SCHEMA)
    for account,box,epoch,body in [("alice","INBOX",101,"old invoice"),
            ("alice","Archive",80,"archived message"),("bob","INBOX",101,"bob message")]:
        select_box(db,account,box,epoch);assert ingest(db,account,box,epoch,7,body)
    with db:
        db.execute("INSERT INTO pending VALUES('old','alice','INBOX',101,7,'queued')")
        db.execute("INSERT INTO pending VALUES('archive','alice','Archive',80,7,'queued')")
    before=list(db.iterdump())
    try:
        select_box(db,"alice","INBOX",202,fail=True)
        raise AssertionError("Missing injected failure")
    except RuntimeError:
        assert list(db.iterdump())==before
    select_box(db,"alice","INBOX",202)
    assert ingest(db,"alice","INBOX",202,7,"different new message")
    assert not ingest(db,"alice","INBOX",101,8,"late stale response")
    assert not mark_seen_locally(db,"old")
    assert db.execute("SELECT seen FROM message WHERE account='alice' AND box='INBOX'").fetchone()==(0,)
    select_box(db,"alice","Archive",80)  # Same epoch preserves cache and work.
    assert mark_seen_locally(db,"archive")
    assert not mark_seen_locally(db,"archive")
    assert db.execute("SELECT seen FROM message WHERE account='bob'").fetchone()==(0,)
    db.close();db=sqlite3.connect(path)
    assert db.execute("SELECT state FROM pending WHERE id='old'").fetchone()==('failed_uidvalidity',)
    assert db.execute("SELECT body,seen FROM message WHERE account='alice' AND box='INBOX'").fetchone()==('different new message',0)
    assert db.execute("SELECT COUNT(*) FROM message").fetchone()==(3,)
    print("scoped reset; reusedUID7 safe; stale response rejected; rollback/reopen passed")
    print("sqlite",sqlite3.sqlite_version)
    db.close()

The run verifies the overlapping identities, scoped reset, unchanged Archive, unchanged Bob row and unread replacement message. A callback tagged with the old inbox validity is rejected rather than inserted into the new cache.

It also injects a failure after cache deletion but before updating the mailbox validity. SQLite rolls the transaction back: the mailbox, messages and queued actions match the complete pre-reset dump. The real database transaction is tested; a distributed mail-server transaction is not.

After the successful reset, the program closes and reopens the database. It reads back both the failed old action and the unread replacement message, and confirms that three scoped message rows remain. This establishes persistence for that completed local transaction.

Do not publish a half-reset cache

Updating the mailbox validity, removing old rows and failing old UID-bound actions belong to one local consistency boundary. If those steps commit independently, a crash can leave new rows combined with old queued actions or an empty cache still labeled with the old validity.

The fixture uses SQLite’s transaction context for that boundary. It performs no external request inside the transaction and makes no claim that a database rollback can undo a command already sent to a mail server.

For an application UI, also avoid showing old content under a new UID identity during refill. A loading state can preserve an explanation that the inbox is being rebuilt without presenting an old cached body as the newly fetched message.

The code deletes all cached generations for the selected account and mailbox when its validity changes. Pending history is retained with a failed status. That choice is convenient for the exercise; an actual product should define cache retention and failed-operation visibility according to its requirements.

Same-validity selection is a different path. It preserves represented cache rows and queued work instead of performing a full reset on every reconnect. Ordinary synchronization must then discover changed flags, new messages and removals, which this narrow fixture does not fully implement.

Reject late responses from the previous selection

A cache reset can race with asynchronous fetch responses. A response begun for the old mailbox generation may arrive after the new validity has been committed. If it is stored using only account, box and UID, it can repopulate the cache with stale content.

The ingest function accepts the validity associated with the response and compares it with the current selected mailbox record. An old 101 response cannot write into Alice’s 202 inbox, even when its UID has not appeared in the replacement cache yet.

That control assumes the application correctly tags the response’s selection context. It does not parse IMAP wire messages or prove that callbacks are associated with the right connection. A real client needs ownership of the selected session and response handling as well as the cache key.

Cancellation should retire the old request’s authority to update the current selection. Removing its loading spinner is insufficient if a callback still holds a reference to the cache writer. Test navigation between mailboxes and reconnect alongside the numeric validity change.

A retry of an old operation must also carry its original namespace. Replacing its saved validity with the current one merely to make validation pass converts a failed reference into an unrelated new request. That would defeat the very guard the schema was designed to enforce.

The reset transaction fails old queued work and clears only the changed mailbox namespace

Keep sequence numbers out of durable offline identity

An expunge can change a surviving message’s position without changing its UID within the same valid namespace. A UI row number or sequence position should therefore be refreshed from current mailbox state rather than stored as the target of an offline action.

For example, removing the first row can make the previous second row become first. Replaying “mark row two read” after reconnect can target a different message even without a mailbox rebuild. This is a separate positional-identity mistake from validity change.

The published database stores no sequence number, so its replay cannot accidentally use one. That design choice does not test every IMAP expunge response or command interleaving. It narrows the executable case to identity and local invalidation.

For actual flag synchronization, the client still needs the protocol’s current capabilities and conflict rules. A local seen bit is not evidence that the server accepted a change or that another device’s newer flag change was preserved.

Similarly, a successful remote response can arrive after a local timeout. Recovering that result requires the actual operation and session contract. UIDVALIDITY prevents one class of mistaken identity; it does not supply universal exactly-once execution for a disconnected client.

Explain recovery without guessing message equivalence

When old pending markers fail, report their failed status against the old cached identity. The user may choose a new action after the replacement messages are fetched, but the system should not silently pretend that their previous action succeeded.

If a product wants to help match old content to new content, treat that as a separate reconciliation feature with its own evidence and ambiguity policy. A subject match is especially weak, and duplicate Message-ID headers or copied messages can complicate stronger-looking heuristics.

The model intentionally does not migrate markers. Its decisive assertion is that the replacement UID 7 remains unread. That makes the failure mode inspectable without inventing a perfect content-matching service.

For observability, record the affected account/mailbox scope, old and new validity, failed queued operation count and reset completion. Use appropriate identifiers rather than logging message bodies. The demonstration bodies are fictional strings retained only in a temporary test database.

The five prompts below extend the same identity principle into offline sync, recreated files and reading progress. They are preparation exercises, not evidence that an employer uses this exact IMAP scenario.

PracHub questionWhat to practise
System design of an Outlook-style email service: delivery, sync and searchSeparate mailbox identity, cached content and pending operations
Design an Offline-First Client That Syncs Edits and Resolves Multi-Device ConflictsFail stale identity-bound edits before replay
Design a Cloud File Storage and Sync Service and Defend Your API and Latency ChoicesDistinguish a recreated name from the original object
Design an Offline Multi-Device E-Book ReaderBind offline read markers to the correct object identity
Design a temporary email serviceDefine mailbox expiry and replacement boundaries

Return to the email-service design with two mailboxes and two accounts sharing UID 7. Change one validity, replay its old marker and inject a late response. Show which local transaction commits, which operation fails and why every unaffected namespace remains intact.

Sources and Further Reading


Comments (0)