Skip to content

fix(activesync): keep sync state of two devices apart after a device change - #116

Merged
ralflang merged 2 commits into
FRAMEWORK_6_0from
fix/state-device-change-key-series
Nov 13, 2026
Merged

ralflang merged 2 commits into
FRAMEWORK_6_0from
fix/state-device-change-key-series

Conversation

@TDannhauer

@TDannhauer TDannhauer commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Sync state now has an owner check: a device can only load, continue and save state that was stored for its own device id, user and folder.
  • A device that presents a sync key of another device, or whose key series was already continued by another device, gets StateGone (key mismatch status) and resyncs the folder with a key series of its own.
  • Saving never overwrites (State_Sql) or removes (State_Mongo) state of another device, and State_Sql recovers from a failed INSERT on PostgreSQL.

Fixes #115.

Motivation

An account that is moved to a new phone keeps its sync keys but reports a new DeviceId. If the old phone stays online, two device ids advance the same key series. State rows are keyed by sync key only, so the device that falls behind could never store its next state: its UPDATE matched nothing (other sync_devid), its INSERT violated the primary key, and on PostgreSQL the recovery ran in the aborted transaction. The request ended with HTTP 500 and the client repeated the same SYNC forever. In one deployment this produced about 146,000 duplicate key errors for 12 sync keys within six days.

Changes

lib/Horde/ActiveSync/State/Sql.php

  • _readStateRow() selects via the new _ownStateRowQuery() (sync key, device, user, folder). A key that exists for another device is logged as a device change (_logStateNotFound()) and reported as StateGone.
  • New _assertNextSyncKeyAvailable(), called by mutating loads: if the next key of the series is stored for another device, the requesting device is reset before anything is imported or sent.
  • _saveSyncStateRow(): after a failed INSERT the own transaction is rolled back and restarted, then _recoverFromFailedStateInsert() decides: own row → update it (concurrent insert), row of another device → leave it and fail, no row → report the insert failure. Replaces _syncStateExists().
  • _loadStateReadonly() (PING) is deliberately not restricted to the device: rejecting the peek would make pollForChanges() drop the folder from the PING set, so nothing would trigger the SYNC that resets it.
  • The reasoning is documented in the docblock of _isOwnStateRow().
  • The failure path of _saveSyncStateRow() logs through the injected logger instead of the static Horde::log(). That class belongs to horde/core, which this package does not depend on; without it a failed save ended in Class "Horde" not found instead of Horde_ActiveSync_Exception.

lib/Horde/ActiveSync/State/Mongo.php

  • Same three guards: _acquireStateRowLock() uses _ownStateRowQuery() for mutating loads, _loadState() calls _assertNextSyncKeyAvailable() before the document lock is taken, and a failed insert goes through _recoverFromFailedStateInsert(), which only replaces a document of the requesting device.

Caught exception types in new catch blocks:

  • Horde_Db_Exception (State_Sql): owner lookup for the log message (logged, generic message used instead); owner lookup for the next key (logged, rethrown as Horde_ActiveSync_Exception); failed INSERT (handled as described above).
  • MongoException (State_Mongo): the same three places. The insert catch was narrowed from Exception.

Tests

  • test/unit/Horde/ActiveSync/StateTest/Sql/DeviceChangeTest.php: 8 tests on SQLite. The fixture adds a unique index on sync_key, because the SQLite schema built by the migrations has none, and a mock adapter emulates PostgreSQL's aborted transaction.
  • test/integration/Horde/ActiveSync/StateTest/Mongo/DeviceChangeTest.php: 8 tests against an in-memory stand-in for the legacy MongoCollection API.

Not in scope

The Mongo changes were not run against a MongoDB server (none available here). While testing against the stand-in, two existing problems in State_Mongo showed up that this PR does not touch:

  • save() after a key advance fails with "Error saving state.": the document lock is held on key N, but the locked update looks for the document under the new key N+1.
  • FOLDERSYNC state cannot be loaded: _stateRowLockQuery() reads $this->_collection['id'], which is not set for FOLDERSYNC.

Test plan

  • StateTest/Sql/DeviceChangeTest.php: 8 tests pass
  • StateTest/Mongo/DeviceChangeTest.php: 8 tests pass (in-memory stand-in, no MongoDB server)
  • Full test/unit suite inside a Horde deployment: 425 tests, no new failures (4 existing, unrelated failures in AppointmentTest, FindRequestTest, Rfc822Test)
  • CI: no new test failures compared with FRAMEWORK_6_0. The Mongo tests and the three mock-based SQL tests pass; the five SQLite-backed SQL tests are skipped there like the other SQLite state tests. RowLockTest::testSaveRollsBackItsOwnTransactionOnFailure, which fails on FRAMEWORK_6_0, now passes. CI as a whole still fails for the existing reasons; PHP-CS-Fixer additionally lists the two new test files, as it does every existing test file in those two directories.
  • PostgreSQL deployment: a device presenting a sync key of another device gets a key mismatch, resyncs, and no duplicate key error follows
  • MongoDB deployment

…change

A client that is moved to a new phone keeps its sync keys but reports a
new DeviceId. Both device ids then advanced the same key series. Only
one state row can exist per sync key, so the device falling behind could
never store its next state and repeated its SYNC forever with HTTP 500
(duplicate key on horde_activesync_state).

- Mutating loads only accept state stored for the requesting device and
  user. A key of another device is reported as StateGone, so the client
  resyncs the folder and gets a key series of its own.
- Mutating loads also reset the device if the next key of the series
  already belongs to another device.
- Saving never overwrites (Sql) or removes (Mongo) state of another
  device. State_Sql rolls back the aborted transaction before it
  recovers from a failed INSERT, so the recovery works on PostgreSQL.
- Read-only (PING) loads stay unrestricted, so the folder is not dropped
  from the PING set before the next SYNC resets it.
@TDannhauer
TDannhauer requested a review from ralflang November 12, 2026 09:49
@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🔍 CI Results

Overall: ❌ 12/12 lanes failed

TL;DR: ❌ Quality issues: PHP-CS-Fixer: 51 files.

Summary by PHP Version

PHP dev stable
8.1 ❌ ❌
8.2 ❌ ❌
8.3 ❌ ❌
8.4 ❌ ❌
8.5 ❌ ❌
8.6 ❌ ❌

Quality Metrics

  • PHPUnit: did not run (12 lanes exited non-zero with no test output) ❌
  • PHPStan: No errors found ✅ — 8 advisories at level 2
  • PHP-CS-Fixer: 51 unique files with issues (of 240 checked) ⚠️
❌ Failed Lanes

php8.1-dev

  • PHPUnit: 0 failures, 0 errors

php8.1-stable

  • PHPUnit: 0 failures, 0 errors

php8.2-dev

  • PHPUnit: 0 failures, 0 errors

php8.2-stable

  • PHPUnit: 0 failures, 0 errors

php8.3-dev

  • PHPUnit: 0 failures, 0 errors

php8.3-stable

  • PHPUnit: 0 failures, 0 errors

php8.4-dev

  • PHPUnit: 0 failures, 0 errors
  • PHP-CS-Fixer: 51 files with issues

php8.4-stable

  • PHPUnit: 0 failures, 0 errors

php8.5-dev

  • PHPUnit: 0 failures, 0 errors

php8.5-stable

  • PHPUnit: 0 failures, 0 errors

php8.6-dev

  • PHPUnit: 0 failures, 0 errors

php8.6-stable

  • PHPUnit: 0 failures, 0 errors

CI powered by horde-components • View full results

The failure path of State_Sql::_saveSyncStateRow() called the static
Horde::log(). That class belongs to horde/core, which is not a
dependency of this package: where it is not installed, a failed save
ended in "Class Horde not found" instead of the intended
Horde_ActiveSync_Exception. Use the injected logger like the rest of
the class.
@ralflang
ralflang merged commit 5188a12 into FRAMEWORK_6_0 Nov 13, 2026
1 check failed
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.

State: two device ids share one sync key series after a device change, Sync loops with HTTP 500 (duplicate key on horde_activesync_state)

2 participants