From fb45d7c4f716020e69eb681b511e8686c14309d6 Mon Sep 17 00:00:00 2001 From: Jonas Date: Wed, 4 Nov 2026 12:19:58 +0100 Subject: [PATCH 1/3] fix(sync): avoid false conflicts between overlapping saves A save request loads the document before checking for outside changes. If another save by Text finished in between, the file checksum no longer matched the loaded document and the save was rejected with 409, which now shows the conflict dialog. Before reporting a conflict, reload the document and only treat the change as outside if the stored checksum still differs from the file. Continue with the reloaded document so the following checks see the version saved in the meantime. Signed-off-by: Jonas Assisted-by: ClaudeCode:claude-opus-5-5 --- lib/Service/DocumentService.php | 14 ++++-- tests/unit/Service/DocumentServiceTest.php | 53 ++++++++++++++++++++++ 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/lib/Service/DocumentService.php b/lib/Service/DocumentService.php index fe37d17bdd4..bf922a4e9f1 100644 --- a/lib/Service/DocumentService.php +++ b/lib/Service/DocumentService.php @@ -371,9 +371,13 @@ public function autosave(Document $document, IContext $context, int $version, st if ($lastMTime > 0 && !$force && !$this->cache->get('document-save-lock-' . $document->id)) { try { $context->updateDocument($document); - if (!empty($document->getUpdatedFields())) { - // Content was overwritten in the meantime and content changed. - if (isset($document->getUpdatedFields()['checksum'])) { + if (isset($document->getUpdatedFields()['checksum'])) { + // Another save by Text may have finished after this request loaded the document. + $stored = $this->getDocument($document->id); + if ($stored === null) { + throw new NotFoundException('Document was reset in the meantime'); + } + if ($stored->getChecksum() !== $document->getChecksum()) { $content = $context->loadContent(); if ($content === null) { // Keep the stored checksum so the next save detects the outside change again. @@ -382,9 +386,11 @@ public function autosave(Document $document, IContext $context, int $version, st } throw new DocumentSaveConflictException($content); } - $lastMTime = $document->getLastSavedVersionTime(); + $document = $stored; + } elseif (!empty($document->getUpdatedFields())) { $this->documentMapper->update($document); } + $lastMTime = $document->getLastSavedVersionTime(); } catch (LockedException) { // The file is being written right now, check again with the next save. return $document; diff --git a/tests/unit/Service/DocumentServiceTest.php b/tests/unit/Service/DocumentServiceTest.php index 5ad1c93f693..91c489349ba 100644 --- a/tests/unit/Service/DocumentServiceTest.php +++ b/tests/unit/Service/DocumentServiceTest.php @@ -13,10 +13,13 @@ use OCA\Text\Db\DocumentMapper; use OCA\Text\Db\SessionMapper; use OCA\Text\Db\StepMapper; +use OCA\Text\Exception\DocumentSaveConflictException; use OCA\Text\Service\DocumentService; +use OCP\AppFramework\Db\DoesNotExistException; use OCP\DirectEditing\IManager; use OCP\Files\IAppData; use OCP\Files\IRootFolder; +use OCP\Files\NotFoundException; use OCP\ICache; use OCP\ICacheFactory; use OCP\IConfig; @@ -173,4 +176,54 @@ public function testResetsDocumentWhenFileChangedOutside(): void { $built = $this->createBuiltDocument('changed outside'); self::assertSame($built, $this->documentService->getOrCreateDocument($built)); } + + public function testNoConflictIfTextSavedInTheMeantime(): void { + $document = $this->createDocument('etag1', 1000, 'old content'); + $document->setLastSavedVersion(3); + $document->resetUpdatedFields(); + $stored = $this->createDocument('etag2', 1010, 'saved by text'); + $stored->setLastSavedVersion(5); + $context = $this->createMock(FileContext::class); + $context->method('updateDocument')->willReturnCallback( + static fn (Document $document) => $document->setChecksum(DocumentService::computeCheckSum('saved by text')) + ); + $this->documentMapper->method('find')->with($document->id)->willReturn($stored); + $this->stepMapper->method('getLatestVersion')->willReturn(5); + $context->expects(self::never())->method('save'); + + $result = $this->documentService->autosave($document, $context, 4, 'new content', 'doc state'); + self::assertSame($stored, $result); + } + + public function testConflictIfFileChangedOutside(): void { + $document = $this->createDocument('etag1', 1000, 'old content'); + $document->resetUpdatedFields(); + $stored = $this->createDocument('etag1', 1000, 'old content'); + $context = $this->createMock(FileContext::class); + $context->method('updateDocument')->willReturnCallback( + static fn (Document $document) => $document->setChecksum(DocumentService::computeCheckSum('outside content')) + ); + $context->method('loadContent')->willReturn('outside content'); + $this->documentMapper->method('find')->with($document->id)->willReturn($stored); + $context->expects(self::never())->method('save'); + + $this->expectException(DocumentSaveConflictException::class); + $this->documentService->autosave($document, $context, 1, 'new content', 'doc state'); + } + + public function testNotFoundIfDocumentWasResetInTheMeantime(): void { + $document = $this->createDocument('etag1', 1000, 'old content'); + $document->resetUpdatedFields(); + $context = $this->createMock(FileContext::class); + $context->method('updateDocument')->willReturnCallback( + static fn (Document $document) => $document->setChecksum(DocumentService::computeCheckSum('outside content')) + ); + $this->documentMapper->method('find')->with($document->id) + ->willThrowException(new DoesNotExistException('Document was reset')); + $context->expects(self::never())->method('loadContent'); + $context->expects(self::never())->method('save'); + + $this->expectException(NotFoundException::class); + $this->documentService->autosave($document, $context, 1, 'new content', 'doc state'); + } } From 8ec4e476f9ad4b11a9cf8da27cd72307ebc87708 Mon Sep 17 00:00:00 2001 From: Jonas Date: Wed, 4 Nov 2026 12:32:51 +0100 Subject: [PATCH 2/3] fix(sync): store the checksum of the saved content After writing the file, the checksum was computed by reading the file again and stored only after the document state. A lock on the file or a failure while writing the state left the previous checksum behind, so every following save was rejected as a conflict. Reading the file again could also pick up an outside change written right after the save and hide the conflict. Compute the checksum from the content Text just wrote and store it right after writing the file. Signed-off-by: Jonas Assisted-by: ClaudeCode:claude-opus-5-5 --- lib/Context/FileContext.php | 5 ++++- lib/Service/DocumentService.php | 6 +++-- tests/unit/Service/DocumentServiceTest.php | 26 ++++++++++++++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/lib/Context/FileContext.php b/lib/Context/FileContext.php index b62c13b74ff..42cd6904392 100644 --- a/lib/Context/FileContext.php +++ b/lib/Context/FileContext.php @@ -24,6 +24,8 @@ use Psr\Log\LoggerInterface; class FileContext implements IContext { + /** Content written by save(), so updating the document afterwards does not read the file again */ + private ?string $savedContent = null; public function __construct( private readonly FileService $fileService, @@ -132,7 +134,7 @@ public function updateDocument(Document $document): void { } $file = $this->getFile(); - $fileChecksum = $this->computeCheckSum(); + $fileChecksum = $this->computeCheckSum($this->savedContent); $this->logger->debug('computed checksum', ['checksum' => $fileChecksum]); $document->setChecksum($fileChecksum); @@ -147,6 +149,7 @@ public function loadContent(): ?string { public function save(string $content, callable $afterSave): void { $this->lockService->runInScope($this->getFile(), function () use ($content, $afterSave): void { $this->getFile()->putContent($content); + $this->savedContent = $content; $afterSave(); }); } diff --git a/lib/Service/DocumentService.php b/lib/Service/DocumentService.php index bf922a4e9f1..d24c1890665 100644 --- a/lib/Service/DocumentService.php +++ b/lib/Service/DocumentService.php @@ -447,10 +447,12 @@ public function autosave(Document $document, IContext $context, int $version, st $this->cache->set('document-save-lock-' . $document->id, true, 60); $this->saveFromText = true; try { - $context->save($autoSaveDocument, function () use ($document, $documentState): void { + $context->save($autoSaveDocument, function () use ($context, $document, $documentState): void { + // Store the new checksum first so a failure below cannot leave it outdated. + $context->updateDocument($document); + $this->documentMapper->update($document); $this->writeDocumentState($document->id, $documentState); }); - $context->updateDocument($document); $document->setLastSavedVersion($version); $this->documentMapper->update($document); } catch (LockedException) { diff --git a/tests/unit/Service/DocumentServiceTest.php b/tests/unit/Service/DocumentServiceTest.php index 91c489349ba..6b907f31263 100644 --- a/tests/unit/Service/DocumentServiceTest.php +++ b/tests/unit/Service/DocumentServiceTest.php @@ -226,4 +226,30 @@ public function testNotFoundIfDocumentWasResetInTheMeantime(): void { $this->expectException(NotFoundException::class); $this->documentService->autosave($document, $context, 1, 'new content', 'doc state'); } + + public function testUpdatesDocumentRightAfterWritingTheFile(): void { + $document = $this->createDocument('etag1', 1000, 'old content'); + $document->resetUpdatedFields(); + $context = $this->createMock(FileContext::class); + $saving = false; + $updatedWhileSaving = []; + $context->method('updateDocument')->willReturnCallback( + static function () use (&$saving, &$updatedWhileSaving): void { + $updatedWhileSaving[] = $saving; + } + ); + $context->method('loadContent')->willReturn('old content'); + $context->method('save')->willReturnCallback( + static function (string $content, callable $afterSave) use (&$saving): void { + $saving = true; + $afterSave(); + $saving = false; + } + ); + $this->stepMapper->method('getLatestVersion')->willReturn(1); + + $this->documentService->autosave($document, $context, 1, 'new content', 'doc state'); + self::assertSame([false, true], $updatedWhileSaving); + self::assertSame(1, $document->getLastSavedVersion()); + } } From 50d1b0f800e694958287a2e2cf608611c97f9951 Mon Sep 17 00:00:00 2001 From: Jonas Date: Wed, 4 Nov 2026 12:42:04 +0100 Subject: [PATCH 3/3] perf(sync): throttle autosaves before checking for conflicts The conflict check reads the whole file to compute its checksum, also for autosaves that are then dropped because the last save was less than AUTOSAVE_MINIMUM_DELAY seconds ago. Return early for those autosaves before checking for conflicts. They do not write anything, so skipping the check cannot overwrite outside changes. Manual saves are not throttled and are still checked. Signed-off-by: Jonas Assisted-by: ClaudeCode:claude-opus-5-5 --- lib/Service/DocumentService.php | 11 ++++----- tests/unit/Service/DocumentServiceTest.php | 27 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/lib/Service/DocumentService.php b/lib/Service/DocumentService.php index d24c1890665..575d42f73af 100644 --- a/lib/Service/DocumentService.php +++ b/lib/Service/DocumentService.php @@ -367,7 +367,12 @@ public function autosave(Document $document, IContext $context, int $version, st throw new NotPermittedException('Read-only permission cannot save document changes. Please reload the page.'); } + // Only save once every AUTOSAVE_MINIMUM_DELAY seconds $lastMTime = $document->getLastSavedVersionTime(); + if ($lastMTime > time() - self::AUTOSAVE_MINIMUM_DELAY && $manualSave === false) { + return $document; + } + if ($lastMTime > 0 && !$force && !$this->cache->get('document-save-lock-' . $document->id)) { try { $context->updateDocument($document); @@ -390,7 +395,6 @@ public function autosave(Document $document, IContext $context, int $version, st } elseif (!empty($document->getUpdatedFields())) { $this->documentMapper->update($document); } - $lastMTime = $document->getLastSavedVersionTime(); } catch (LockedException) { // The file is being written right now, check again with the next save. return $document; @@ -412,11 +416,6 @@ public function autosave(Document $document, IContext $context, int $version, st return $document; } - // Only save once every AUTOSAVE_MINIMUM_DELAY seconds - if ($lastMTime > time() - self::AUTOSAVE_MINIMUM_DELAY && $manualSave === false) { - return $document; - } - if (empty($autoSaveDocument)) { $file = $context->getFile(); $this->logger->warning('Saving empty document', [ diff --git a/tests/unit/Service/DocumentServiceTest.php b/tests/unit/Service/DocumentServiceTest.php index 6b907f31263..02e489bf683 100644 --- a/tests/unit/Service/DocumentServiceTest.php +++ b/tests/unit/Service/DocumentServiceTest.php @@ -252,4 +252,31 @@ static function (string $content, callable $afterSave) use (&$saving): void { self::assertSame([false, true], $updatedWhileSaving); self::assertSame(1, $document->getLastSavedVersion()); } + + public function testThrottledAutosaveSkipsConflictCheck(): void { + $document = $this->createDocument('etag1', time(), 'content'); + $document->resetUpdatedFields(); + $context = $this->createMock(FileContext::class); + $context->expects(self::never())->method('updateDocument'); + $context->expects(self::never())->method('save'); + + $result = $this->documentService->autosave($document, $context, 1, 'new content', 'doc state'); + self::assertSame($document, $result); + } + + public function testManualSaveChecksForConflictsWithinAutosaveDelay(): void { + $document = $this->createDocument('etag1', time(), 'old content'); + $document->resetUpdatedFields(); + $stored = $this->createDocument('etag1', time(), 'old content'); + $context = $this->createMock(FileContext::class); + $context->method('updateDocument')->willReturnCallback( + static fn (Document $document) => $document->setChecksum(DocumentService::computeCheckSum('outside content')) + ); + $context->method('loadContent')->willReturn('outside content'); + $this->documentMapper->method('find')->with($document->id)->willReturn($stored); + $context->expects(self::never())->method('save'); + + $this->expectException(DocumentSaveConflictException::class); + $this->documentService->autosave($document, $context, 1, 'new content', 'doc state', false, true); + } }