Skip to content

Export: bounded retry + skip on transient fetch failure - #243

Open
rickhuizinga wants to merge 1 commit into
Z-Hub:developfrom
rickhuizinga:upstream-pr-export-loop-retry-skip
Open

rickhuizinga wants to merge 1 commit into
Z-Hub:developfrom
rickhuizinga:upstream-pr-export-loop-retry-skip

Conversation

@rickhuizinga

@rickhuizinga rickhuizinga commented Nov 14, 2026 •

Copy link
Copy Markdown

Fixes #241

Problem

In ExportChangesDiff::Synchronize(), a transient StatusException from the StatMessage/GetMessage pair propagates out of the method before $this->step++ runs. The sync loop in request/sync.php then calls Synchronize() again for the same step, retrying the same message until the request-loop guard (5,000 iterations) aborts the request: HTTP 500, no sync state written, full re-export from the top on the next open. One transient fetch failure could therefore livelock a large folder (each aborted pass re-trips the server rate limiter, so the immediate retry passes fail item-by-item against the cooldown too).
Observed in production (multi-device ActiveSync deployment): a ~1,300-message folder produced 11 consecutive failed full exports, each dying at item position ~150–225 with an identical signature (~5,000 code-15 "message not found" log lines in ~1 s, then the guard abort, then 500).

Changes

src/lib/default/diffbackend/exportchangesdiff.php, Synchronize() only:

  • A StatusException with code SYNC_ITEMOPERATIONSSTATUS_INVALIDATT (15) from the StatMessage/GetMessage pair is now retried once after a short backoff (the message is re-read from scratch).
  • If the retry fails again, the message is logged as skipped for this pass and the step advances — the rest of the export completes and sync state is written without the flaky item. The item self-heals: it is not in the new state, so the next pass re-diffs it as an addition and fetches it again.
  • Any other exception code propagates unchanged — no behavior change for real errors (server errors, invalid folder, …).

Why this is safe

  • The skip is only for code 15 (the "message not found/transient" code the IMAP backend raises for a one-off failed fetch). A message skipped here is re-announced on the next sync pass, so nothing is lost — worst case the client briefly lacks one item.
  • No change to the diff computation, state format, or change types.
  • The bounded retry (exactly one) cannot reintroduce the livelock: the step always advances after at most two attempts.

Test evidence

Behavioral harness (attached as harness-export-loop-retry-skip.php) driving the real ExportChangesDiff::Synchronize() export loop with a scripted backend stub (real DiffState/StateObject; runs with php -n). Captured output on the candidate branch:

[T1 transient code-15 failure: one retry succeeds -> message exported]
  ok   loop terminated without exception
  ok   both messages exported
  ok   new state contains both messages
  ok   backoff was honored (>=2.8s)
[T2 persistent code-15 failure: message skipped, export continues]
  ok   loop terminated without exception
  ok   healthy message 2 still exported
  ok   message 1 NOT exported
  ok   new state holds only message 2
  ok   skip was logged (WARN)
[T3 non-15 code (3) propagates out of Synchronize()]
  ok   StatusException propagated
  ok   code preserved (3)
[T4 regression: clean export, no backoff sleep]
  ok   loop terminated without exception
  ok   both messages exported
  ok   new state complete
  ok   no backoff sleep (<0.5s)
[T5 diff layer: saved state [1,2,3] vs empty list = 3 deletes]
  ok   loop terminated without exception
  ok   3 deletions imported
  ok   new state empty
ALL CHECKS PASSED

On unmodified develop, T1/T2 do not terminate cleanly (the step never advances past a throwing message) — the same mechanism that produced the production livelock.
The harness below is self-contained — php -n -d display_errors=1 <file> /path/to/checkout:

<?php
/*
 * Behavioral harness — ExportChangesDiff bounded retry/skip fix
 * (candidate PR 2 for the Z-Push upstream)
 *
 * Run from any directory, pointing at a checkout of the candidate
 * branch:
 *
 *   php -n -d display_errors=1 harness-export-loop-retry-skip.php /path/to/z-push
 *
 * The real code under test is ExportChangesDiff::Synchronize() (the
 * export loop) with the Z-Push framework (ZLog, StatusException,
 * ContentParameters, DiffState). The backend is a scripted stub;
 * only its StatMessage/GetMessage pair is driven per scenario.
 *
 * Scenarios:
 *   T1  transient code-15 failure, retry succeeds -> message exported
 *   T2  code-15 failure persists -> message skipped, step advances,
 *       the rest of the export completes
 *   T3  non-15 exception code propagates unchanged (behavior preserved)
 *   T4  regression: no failures -> normal export, no backoff sleep
 *   T5  diff-layer tie-in: saved state [1,2,3] vs empty list = 3 deletes
 *       (why the companion fail-closed fix matters)
 */
error_reporting(E_ALL);
ini_set('display_errors', '1');
// ---------------------------------------------------------------------------
// Z-Push bootstrap (any checkout of the candidate branch)
// ---------------------------------------------------------------------------
$repo = (isset($argv[1]) && $argv[1] !== '') ? rtrim($argv[1], '/') : getcwd();
require $repo . '/src/vendor/autoload.php'; // classmap + zpushdefs constants
// Pre-inject a no-op logger so ZLog::Write never touches config/Request.
class HarnessNoopLog {
    public function SetUser($u) {}
    public function SetAuthUser($u) {}
    public function SetSpecialLogUsers($a) {}
    public function SetDevid($d) {}
    public function SetPid($p) {}
    public function AfterInitialize() {}
    public function Log($level, $msg) {}
    public function HasSpecialLogUsers() { return false; }
}
$lr = new ReflectionProperty('ZLog', 'logger');
$lr->setAccessible(true);
$lr->setValue(null, new HarnessNoopLog());
// ---------------------------------------------------------------------------
// Scripted backend + importer stubs
// ---------------------------------------------------------------------------
class StubExportBackend {
    public $messageList = array();   // what GetMessageList() returns
    public $failCode = null;         // null = OK, int = StatusException code
    public $failCountdown = array(); // id => remaining failures (0/absent = never)
    public function GetMessageList($folderid, $cutoffdate) {
        return $this->messageList;
    }
    public function StatMessage($folderid, $id) {
        return array('id' => $id, 'mod' => 1000 + $id, 'flags' => 0);
    }
    public function GetMessage($folderid, $id, $contentparameters) {
        if ($this->failCode !== null) {
            if (!isset($this->failCountdown[$id])) {
                $this->failCountdown[$id] = 999; // fail forever
            }
            if ($this->failCountdown[$id] > 0) {
                $this->failCountdown[$id]--;
                throw new StatusException("scripted fetch failure (code {$this->failCode}) on message $id", $this->failCode);
            }
        }
        return new stdClass();
    }
}
class StubImporter {
    public $imported = array();
    public $deletions = array();
    public function ImportMessageChange($id, $message) { $this->imported[] = $id; return true; }
    public function ImportMessageDeletion($id) { $this->deletions[] = $id; return true; }
    public function ImportMessageReadFlag($id, $flags) { return true; }
    public function ImportMessageMove($id, $parent) { return true; }
    public function ImportFolderChange($folder) { return true; }
    public function ImportFolderDeletion($folder) { return true; }
}
// ---------------------------------------------------------------------------
// Harness helpers
// ---------------------------------------------------------------------------
$FAILURES = 0;
$SCENARIO = '?';
function check($name, $cond, $detail = '') {
    global $FAILURES, $SCENARIO;
    if ($cond) {
        echo "  ok   $name\n";
    }
    else {
        $FAILURES++;
        echo "  FAIL $name" . ($detail !== '' ? " -- $detail" : '') . "\n";
    }
}
function scenario($name) {
    global $SCENARIO;
    $SCENARIO = $name;
    echo "[$name]\n";
}
function mk_msg($id, $mod = null) {
    $m = array('id' => $id, 'flags' => 0);
    if ($mod !== null) $m['mod'] = $mod;
    return $m;
}
// Runs the full export loop. Returns array($exporter, $importer) or throws.
function run_export(StubExportBackend $backend, array $savedState = array()) {
    $importer = new StubImporter();
    $exporter = new ExportChangesDiff($backend, 'f00d0001');
    $exporter->Config($savedState);
    $exporter->ConfigContentParameters(new ContentParameters());
    $exporter->InitializeExporter($importer);
    $iter = 0;
    while (true) {
        $prog = $exporter->Synchronize();
        if ($prog === false) break;
        if (++$iter > 200) {
            throw new Exception('harness: export loop did not terminate (livelock)');
        }
    }
    return array($exporter, $importer);
}
// ---------------------------------------------------------------------------
// T1 — transient code-15 failure, retry succeeds
// ---------------------------------------------------------------------------
scenario('T1 transient code-15 failure: one retry succeeds -> message exported');
$backend = new StubExportBackend();
$backend->messageList = array(mk_msg(1), mk_msg(2));
$backend->failCode = SYNC_ITEMOPERATIONSSTATUS_INVALIDATT; // 15
$backend->failCountdown = array(1 => 1, 2 => 0);
$t0 = microtime(true);
$thrown = null;
try {
    list($exporter, $importer) = run_export($backend);
}
catch (Exception $e) {
    $thrown = $e->getMessage();
}
$elapsed = microtime(true) - $t0;
check('loop terminated without exception', $thrown === null, (string) $thrown);
check('both messages exported', $importer !== null && $importer->imported === array(1, 2), var_export($importer ? $importer->imported : null, true));
check('new state contains both messages', $exporter !== null && count(array_filter($exporter->GetState(), function ($s) { return in_array($s['id'], array(1, 2)); })) === 2);
check('backoff was honored (>=2.8s)', $elapsed >= 2.8, 'elapsed=' . round($elapsed, 2));
// ---------------------------------------------------------------------------
scenario('T2 persistent code-15 failure: message skipped, export continues');
$backend = new StubExportBackend();
$backend->messageList = array(mk_msg(1), mk_msg(2));
$backend->failCode = SYNC_ITEMOPERATIONSSTATUS_INVALIDATT;
$backend->failCountdown = array(1 => 999, 2 => 0);
$thrown = null;
try {
    list($exporter, $importer) = run_export($backend);
}
catch (Exception $e) {
    $thrown = $e->getMessage();
}
check('loop terminated without exception', $thrown === null, (string) $thrown);
check('healthy message 2 still exported', $importer !== null && $importer->imported === array(2), var_export($importer ? $importer->imported : null, true));
check('message 1 NOT exported', $importer !== null && !in_array(1, $importer->imported));
check('new state holds only message 2', $exporter !== null && count($exporter->GetState()) === 1 && $exporter->GetState()[0]['id'] === 2, var_export($exporter ? $exporter->GetState() : null, true));
check('skip was logged (WARN)', strpos((string) ZLog::GetLastMessage(LOGLEVEL_WARN), 'skipping it for this pass') !== false, (string) ZLog::GetLastMessage(LOGLEVEL_WARN));
// ---------------------------------------------------------------------------
scenario('T3 non-15 code (3) propagates out of Synchronize()');
$backend = new StubExportBackend();
$backend->messageList = array(mk_msg(1));
$backend->failCode = SYNC_ITEMOPERATIONSSTATUS_SERVERERROR; // 3
$thrown = null;
try {
    run_export($backend);
}
catch (StatusException $e) {
    $thrown = $e->getCode();
}
catch (Exception $e) {
    $thrown = 'wrong-exception:' . $e->getMessage();
}
check('StatusException propagated', is_int($thrown), var_export($thrown, true));
check('code preserved (3)', $thrown === SYNC_ITEMOPERATIONSSTATUS_SERVERERROR);
// ---------------------------------------------------------------------------
scenario('T4 regression: clean export, no backoff sleep');
$backend = new StubExportBackend();
$backend->messageList = array(mk_msg(1), mk_msg(2));
$t0 = microtime(true);
$thrown = null;
try {
    list($exporter, $importer) = run_export($backend);
}
catch (Exception $e) {
    $thrown = $e->getMessage();
}
$elapsed = microtime(true) - $t0;
check('loop terminated without exception', $thrown === null, (string) $thrown);
check('both messages exported', $importer !== null && $importer->imported === array(1, 2), var_export($importer ? $importer->imported : null, true));
check('new state complete', $exporter !== null && count($exporter->GetState()) === 2);
check('no backoff sleep (<0.5s)', $elapsed < 0.5, 'elapsed=' . round($elapsed, 2));
// ---------------------------------------------------------------------------
scenario('T5 diff layer: saved state [1,2,3] vs empty list = 3 deletes');
$backend = new StubExportBackend();
$backend->messageList = array();
$thrown = null;
try {
    list($exporter, $importer) = run_export($backend, array(mk_msg(1, 100), mk_msg(2, 200), mk_msg(3, 300)));
}
catch (Exception $e) {
    $thrown = $e->getMessage();
}
check('loop terminated without exception', $thrown === null, (string) $thrown);
check('3 deletions imported', $importer !== null && $importer->deletions === array(1, 2, 3), var_export($importer ? $importer->deletions : null, true));
check('new state empty', $exporter !== null && count($exporter->GetState()) === 0);
// ---------------------------------------------------------------------------
echo "\n" . ($FAILURES === 0 ? "ALL CHECKS PASSED" : "$FAILURES CHECK(S) FAILED") . "\n";
exit($FAILURES === 0 ? 0 : 1);

Production note

These changes have been running in production on a multi-device ActiveSync deployment since early November 2026. Since deployment: the livelock signature (guard abort + HTTP 500 on a full-folder export) has not recurred, the affected folder completed its export and now syncs normally, and transient fetch failures log a single skip-and-continue line instead of aborting the request.

Checklist

  • php -l clean
  • No change to non-code-15 exception propagation (T3)
  • Step always advances after at most two attempts — livelock impossible
  • CI green

In ExportChangesDiff->Synchronize(), the step counter only advances
when no exception propagates. A single transient StatusException from
the backend's StatMessage/GetMessage pair (e.g. a one-off empty FETCH
response from the IMAP server on an otherwise healthy folder) therefore
made the export loop retry the same message every iteration until the
WBXML loop guard aborted the whole request (HTTP 500), discarding all
progress of the sync. Aborted requests tend to trigger further
server-side rate limiting, so the next open re-ran the same doomed
export from scratch.

A code-15 (SYNC_ITEMOPERATIONSSTATUS_INVALIDATT) StatusException from
the StatMessage/GetMessage pair is now retried once after a short
backoff; if the retry fails again, the message is logged as skipped and
the step advances, so the rest of the export continues and the item
self-heals on the next sync pass. Any other exception code still
propagates unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Export loop livelocks on one transient fetch failure — HTTP 500, no state written, full re-export on every retry

1 participant