Repository navigation
fix(activesync): keep sync state of two devices apart after a device change - #116
Merged
Merged
Conversation
…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.
🔍 CI ResultsOverall: ❌ 12/12 lanes failed TL;DR: ❌ Quality issues: PHP-CS-Fixer: 51 files. Summary by PHP Version
Quality Metrics
❌ Failed Lanesphp8.1-dev
php8.1-stable
php8.2-dev
php8.2-stable
php8.3-dev
php8.3-stable
php8.4-dev
php8.4-stable
php8.5-dev
php8.5-stable
php8.6-dev
php8.6-stable
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.
2 of 3 tasks
ralflang
approved these changes
Nov 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
StateGone(key mismatch status) and resyncs the folder with a key series of its own.State_Sql) or removes (State_Mongo) state of another device, andState_Sqlrecovers from a failedINSERTon 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
UPDATEmatched nothing (othersync_devid), itsINSERTviolated 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 asStateGone._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 failedINSERTthe 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 makepollForChanges()drop the folder from the PING set, so nothing would trigger the SYNC that resets it._isOwnStateRow()._saveSyncStateRow()logs through the injected logger instead of the staticHorde::log(). That class belongs to horde/core, which this package does not depend on; without it a failed save ended inClass "Horde" not foundinstead ofHorde_ActiveSync_Exception.lib/Horde/ActiveSync/State/Mongo.php_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 asHorde_ActiveSync_Exception); failedINSERT(handled as described above).MongoException(State_Mongo): the same three places. The insert catch was narrowed fromException.Tests
test/unit/Horde/ActiveSync/StateTest/Sql/DeviceChangeTest.php: 8 tests on SQLite. The fixture adds a unique index onsync_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 legacyMongoCollectionAPI.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_Mongoshowed 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._stateRowLockQuery()reads$this->_collection['id'], which is not set for FOLDERSYNC.Test plan
StateTest/Sql/DeviceChangeTest.php: 8 tests passStateTest/Mongo/DeviceChangeTest.php: 8 tests pass (in-memory stand-in, no MongoDB server)test/unitsuite inside a Horde deployment: 425 tests, no new failures (4 existing, unrelated failures inAppointmentTest,FindRequestTest,Rfc822Test)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 onFRAMEWORK_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.