Skip to content

Text never releases its file lock when an editing session ends abnormally #9042

Open

Description

@eric-lemesre

Describe the bug

When a document is opened in Text, the app acquires a lock through files_lock. If the editing session ends abnormally — tab closed without a clean teardown, browser crash, session expiry — the lock is never released.

The failure is silent. A desktop client holding a newer local copy retries the upload and gets HTTP 423 Locked forever, with no actionable error surfaced in the web UI or in the client. Files whose local copy happens to be unchanged simply stop syncing in both directions, with no visible sign at all.

Orphan rows are also left behind in oc_text_sessions, with last_contact frozen at the moment the session died. Every stale lock we found had exactly one matching stale session, which suggests both are leaked by the same teardown path.

To Reproduce

  1. Open a Markdown file in Text.
  2. Kill the session abruptly (close the tab while editing, or let the session expire).
  3. Inspect oc_files_lock: a row remains, with owner = "Text" and a negative ttl.
  4. On a desktop client syncing that folder, modify the same file locally.
  5. Watch the web server access log: PUT /remote.php/dav/files/<user>/<path> → 423, repeating indefinitely.

Expected behavior

The lock is released when the editing session ends, or at the latest when the stale session is garbage-collected.

Observed on a production instance

  • 8 stale locks accumulated over 3 weeks, all owner = "Text", the oldest 20 days old.
  • Each had a matching orphan row in oc_text_sessions.
  • One file had a newer local copy: its desktop client issued a PUT every 2 hours and received 423 each time, for 19 consecutive days.
  • The 7 other files were silently out of sync — discovered only while investigating the first one.

Why nothing cleans this up

files_lock ships a cleanup job, OCA\FilesLock\Cron\Unlock, but with default settings it is a no-op:

  • ConfigService defaults lock_timeout to '-1';
  • FileLock::ETA_INFINITE === -1;
  • LockService::getDeprecatedLocks() returns [] when the timeout equals ETA_INFINITE, so the job deletes nothing.

Setting a finite timeout re-arms the job and is an effective workaround:

occ config:app:set files_lock lock_timeout --value=1440

This bounds the damage but does not fix the leak: the lock is still orphaned, and the file stays unsyncable until the job runs.

Possible second issue, in files_lock

Even with a finite lock_timeout, expiry does not track activity. LocksRequest::update() — the "extending existing lock" path — writes token, ttl, user_id, owner and scope, but not creation, while LocksRequest::getLocksOlderThan() filters on creation. A lock actively extended by an ongoing session can therefore be purged based on its original creation time, so a long editing session may lose its lock mid-edit. This is why we chose a deliberately large timeout above.

Happy to split this into a separate issue against files_lock if you prefer.

Server details:

  • Nextcloud version: 34.0.3 (also observed on 32.x and 33.x before upgrading)
  • PHP Version: 8.4
  • Database: PostgreSQL 17.10 and MariaDB 11.8.6 — two separate instances, both affected
  • files_lock: 34.0.1

Client details:

  • OS: Debian (server), Linux desktop
  • Desktop sync client: 33.0.7
  • Browser: Firefox

Activity

  1. fuckoffwiththisshitistaken commented on Sep 8, 2026

    @fuckoffwiththisshitistaken

    thanks for reporting this issue, my workaround was to disable the text app.

  2. sallyhaj commented on Oct 1, 2026

    @sallyhaj

    It seems this issue affects Notes to sync between devices, make locks.
    When I edit/create a note via Nextcloud website, after that I opened my Android device/Notes app, I get this error:

    App Version: 35.0.0
    App Version Code: 350000090
    App Flavor: play
    
    Files App Version Code: 350000090 (PROD)
    
    ---
    
    OS Version: 6.6.127-android15-8-gd00dbafe5604-ab16030312-4k(16091614)
    OS API Level: 37
    Device: blazer
    Manufacturer: Google
    Model (and Product): Pixel 10 Pro (blazer)
    
    ---
    
    java.lang.Exception: {"errorType":"Exception"}
    [com.nextcloud.android.sso.InputStreamBinder.processRequestV2(InputStreamBinder.java:440), com.nextcloud.android.sso.InputStreamBinder.performNextcloudRequestAndBodyStreamV2(InputStreamBinder.java:113), com.nextcloud.android.sso.InputStreamBinder.performNextcloudRequestV2(InputStreamBinder.java:96), com.nextcloud.android.sso.aidl.IInputStreamService$Stub.onTransact(IInputStreamService.java:112), android.os.Binder.execTransactInternal(Binder.java:1323), android.os.Binder.execTransact(Binder.java:1282)]
    	at it.niedermann.owncloud.notes.persistence.NotesServerSyncTask.pushLocalChanges(NotesServerSyncTask.java:150)
    	at it.niedermann.owncloud.notes.persistence.NotesServerSyncTask.run(NotesServerSyncTask.java:99)
    	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:520)
    	at java.util.concurrent.FutureTask.run(FutureTask.java:328)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1100)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	at java.lang.Thread.run(Thread.java:1571)
    
    
    • Versions: Nextcloud server 35.0.0.10, files_lock 35.0.0, Notes Android 35.0.0.
    • Steps: edit a note in the web editor, close the tab, then sync an Android device that has its own
      unsent edit to the same note.
    • Result: PUT /apps/notes/api/v1/notes/<id> returns 423 with OCP\Lock\ManuallyLockedException, and the
      app only shows {"errorType":"Exception"}.
    • Workarounds: occ text:reset <fileId> clears it at once. Setting files_lock lock_timeout to 30 makes
      the lock expire by itself, but the device still fails for up to 30 minutes.
  3. sallyhaj commented on Oct 15, 2026

    @sallyhaj

    That #9355 fixes only the Files-list icon, not the leaked lock, so the issue should stay open. This matters because maintainers might close #9042 thinking #9355 fixed it.

  4. LucaBoschetto commented on Oct 21, 2026

    @LucaBoschetto

    Confirming this on Nextcloud 34.0.4 (AIO), Text 8.0.0, files_lock 34.0.1, Notes 6.1.0, and adding one finding: it is not limited to crashed tabs. A normal, clean tab close never releases the lock either.

    Reproduction (watching oc_text_sessions and oc_files_lock while doing it):

    1. Open a note in Notes in the browser: a Text session and a Text lock appear.
    2. Type a character, wait for the autosave, then close the browser tab normally.
    3. Result: the file content is saved, but the session row and the lock both stay. Writers other than Text (the Notes API, mobile apps) then get 423 Locked (OCP\Lock\ManuallyLockedException in the log).
    4. Control: closing the editor inside the page (switching to another note in Notes) does delete the session and releases the lock, as expected.

    Why, as far as I can read the shipped bundles:

    • The only beforeunload handler is saveBeforeUnload, registered only while the document is dirty. It sends a navigator.sendBeacon to /apps/text/session/{id}/save (with requesttoken in the JSON body).
    • POST /apps/text/session/{id}/close is only sent through a normal request when the editor component is torn down in the page. Nothing sends it on beforeunload/pagehide, so a closed tab behaves exactly like a crashed one.
    • The orphaned session then also blocks later clean closes for SESSION_VALID_TIME (5 min): ApiService::close() unlocks only if getActiveSessions() is empty, and the orphan still counts as active. We hit this during testing: a clean in-page close 4 min 54 s after a closed tab did not unlock.
    • Nothing cleans up afterwards: the Cleanup job never unlocks, and files_lock's Unlock job is a no-op with the default lock_timeout of -1. Orphaned sessions that hold steps survive up to 90 days (removeOldSessions). We found Text locks dating back a month.

    Possible fixes: send the close as a beacon on pagehide (the save beacon shows the CSRF token can travel in the body), and/or have the cleanup job release Text's lock for documents with no active session.

  5. MK796 commented on Nov 11, 2026

    @MK796

    I can confirm that this issue is still occurring on a current Nextcloud AIO installation, despite the iOS fix from nextcloud/ios#4342 already being included.

    I have been experiencing this intermittently since April 2026. Before then, the same workflow released the file locks correctly.

    Observed behavior

    After opening a Markdown or plain-text file in the Nextcloud iOS app and subsequently leaving or closing the editor, the file can remain “Locked by Text” indefinitely. The exact client-side exit path of the latest occurrence was not captured.

    Environment

    • Nextcloud: 35.0.2.2 (AIO)
    • Text: 9.0.1
    • files_lock: 35.0.1
    • PHP: 8.4.27
    • Database: PostgreSQL 18.6
    • Nextcloud iOS: 35.2.2

    Read-only database findings

    There are currently four stale locks owned by the text app:

    • 2 × text/markdown
    • 2 × text/plain
    • three locks are approximately 63–68 days old and have ttl = -60
    • the newest lock is approximately 23 hours old and has ttl = 0

    Both non-positive TTL values are treated as infinite by files_lock.

    Each lock has exactly one corresponding stale row in oc_text_sessions. The session's last_contact and the creation time of its lock differ by no more than 102 seconds in all four cases. This indicates that the Text sessions and their locks were abandoned together.

    files_lock.lock_timeout is not explicitly configured on this instance, so the default value of -1 applies. Consequently, the cleanup job does not expire these locks.

    Correlation with iOS 35.2.2

    The newest lock was created at 2026-11-10 16:58:40 UTC. At 16:59:18 UTC, the Nextcloud log contains a POST to the Text API with this user agent:

    Mozilla/5.0 (iOS) Nextcloud-iOS/35.2.2
    

    This is a timestamp correlation rather than a complete client-side request trace. However, it confirms that the latest occurrence happened during an iOS 35.2.2 Text session. This release already contains nextcloud/ios#4342, so that client-side fix does not prevent every path that can leave a Text session and its lock behind.

    No file paths, file IDs, user IDs, session tokens, or lock tokens are included in this report.

    Please let me know if any additional privacy-safe diagnostics from this instance would be useful.

  6. PeterPablo commented on Nov 14, 2026

    @PeterPablo

    The caller does close the session — and the server answers 403, so the lock survives

    Adding a datapoint that points at a different teardown failure than "the tab vanished", because it changes where the fix belongs.

    Environment: Nextcloud 35.0.2 (Docker, Apache), text + files_lock shipped versions, Nextcloud Notes for Android (F-Droid, it.niedermann.owncloud.notes 35.0.0) as the only client. The Notes app opens a note through Direct Editing, which starts a Text session in its WebView.

    Server access log for one note, one afternoon (client is the Notes app in every line):

    15:51:46  POST /apps/notes/api/v1/notes                        200   ← note created
    15:51:47  POST /ocs/v2.php/apps/files/api/v1/directEditing/open 200
    15:51:48  POST /apps/text/session/152010011938480129/sync       200
    15:52:56  POST /apps/text/session/152010011938480129/close      403   ← the teardown call
    16:18:16  POST /apps/text/session/152010011938480129/close      403
    16:33:07  POST /apps/text/session/152010011938480129/close      403
    

    oc_files_lock afterwards (unchanged by the failed closes):

    id  user_id  file_id  type  owner  ttl   created
    77  text     958914   1     Text   0     2026-11-14 15:32:52
    

    type = 1 is ILock::TYPE_APP, the row apps/text/lib/Service/LockService::lock() creates with owner Application::APP_NAME. Five such rows had accumulated over six days on .md/.txt/.html notes; none was ever released.

    Why the close returns 403 — the same client gets 200 on sync, push and save (95/59/16 calls that day), so this is not CSRF and not a client that fails to authenticate. Only close fails, and the reason is in the controller:

    #[NoAdminRequired]
    #[PublicPage]
    public function close(string $documentId, int $sessionId, string $sessionToken): DataResponse {
        $user = $this->userSession->getUser();
        if ($user === null) {
            throw new InvalidSessionException();
        }
        return $this->apiService->close($documentId, $sessionId, $sessionToken, $user);
    }

    with SessionMiddleware::afterException() mapping InvalidSessionException → Http::STATUS_FORBIDDEN. The close endpoint is the only session endpoint that requires an IUser: sync/push/save are satisfied by the document session token plus loginSessionUser(). A client that drives a document session by token — which is exactly what a mobile app does — therefore cannot close it, and the lock is never released.

    Two consequences worth separating, because they need different fixes:

    1. close should not require a logged-in user. The session row already carries the owner (oc_text_sessions.user_id), so the user can be derived from (documentId, sessionId, sessionToken) — the token is the authorization. If no session matches, closeSession() already swallows DoesNotExistException and could simply return 204/200 instead of 403; a teardown call is idempotent by nature.
    2. The lock release should not depend on that request at all. FileContext::cleanup() is only reached via ApiService::close() → getActiveSessions() === 0. A stale session row (there were 11 of 15 older than an hour here, with last_contact frozen — matching your note about orphaned sessions) keeps that count non-zero, so even a successful close cannot unlock. Releasing the lock from the Session::close path, plus an expiry that also covers app locks, would make the outcome independent of the client's manners.

    Reproduced 3/3 with the Notes app; not reproduced from the browser, which sends the request token and has a user session.

    Workaround running here meanwhile: a systemd timer that unlocks type = 1 locks owned by Text older than 45 minutes via occ files:lock --unlock <fileid> <storage-owner> — deliberately narrow, because it deletes state. Not offered as a fix.

    The second point in that list (a successful close still not releasing the lock) turned out to be a third defect; it is in my later comment below and now has a draft PR: #9603.

    #AI-ASSISTED

  7. PeterPablo commented on Nov 14, 2026

    @PeterPablo

    After the fixes: the same note, an hour later

    Following up on my datapoint above. Three separate defects were involved, and the third one only became visible once the first two were patched — which is why the loop looked identical from the client each time.

    1. close() returning 403 — fixed on main by 599abe6 (already noted). Backported here to the shipped 9.0.1, then:

    POST /apps/text/session/…/close   →  200     (was 403, 4/4 before)
    PUT  /apps/notes/api/v1/notes/958914  →  500 OCP\Files\NotPermittedException
                                              "Could not move …/Neue Notiz.md to …/tasks 2026.md"
    

    2. That 500 was files_lock, not text: LockWrapper::rename() checks PERMISSION_UPDATE & PERMISSION_READ = 2 & 1 = 0, and checkPermissions(…, 0) returns false for a locked path, so a rename never reached the branches that raise ManuallyLockedException. Reported separately: nextcloud/files_lock#1437. With that fixed the failure became an honest 423 Locked.

    3. With the close succeeding and the rename answering 423, the lock was still there — and this is the text-side bug this issue is about:

    17:0x  POST /apps/text/session/…/close  200
    17:0x  PUT  /apps/notes/api/v1/notes/958914  423   "…is locked, existing lock on file: files_lock/0f01f381-…"
    

    ApiService::close() only cleans up the context when getActiveSessions() is empty, and that counts every session row younger than SESSION_VALID_TIME (5 min). One note had six rows, one per reload of the editor — all the same user, the newest 13 s old when its own close ran. So the close succeeded, deleted its own row, and still saw "an active session", skipping context->cleanup() → the lock survived. Note that a close whose row cannot be matched leaves its row behind too, so the same gate fails for a second reason.

    The rule that fixed it, and that I would suggest for upstream: the lock protects other people, so ask whether another user is still active — not whether any row is left:

    // SessionService
    public function hasRecentSessionsOfOtherUsers(string $documentId, ?string $userId, int $graceSeconds = 60): bool {
        $threshold = time() - $graceSeconds;
        foreach ($this->sessionMapper->findAll($documentId) as $session) {
            if ($session->getLastContact() < $threshold || $session->isGuest()) {
                continue;
            }
            if ($userId === null || $session->getUserId() !== $userId) {
                return true;
            }
        }
        return false;
    }
    
    // ApiService::close()
    $this->sessionService->closeSession($documentId, $sessionId, $sessionToken);
    $this->sessionService->removeInactiveSessionsWithoutSteps($documentId);
    $activeSessions = $this->sessionService->getActiveSessions($documentId);
    $closer = $auth instanceof IUser ? $auth->getUID() : null;
    $othersEditing = $this->sessionService->hasRecentSessionsOfOtherUsers($documentId, $closer, 60);
    if (count($activeSessions) === 0 || !$othersEditing) {
        … $context->cleanup();
    }

    60 s because a live editor pushes every few seconds — that window separates "somebody is typing" from "these rows are leftovers". A maintainer may prefer another mechanism (release on close plus an expiry that also covers app locks); I am not attached to this shape, only to the outcome.

    Result on the same device, same app, unpatched client:

    POST /apps/text/session/…/close     200
    PUT  /apps/notes/api/v1/notes/958914 200     ← rename through
    oc_files_lock                        0 rows
    

    Rename after an edit now works repeatedly, and no lock is left behind.

    Opened as a draft PR: #9603 — two helpers and one condition. It is a draft on purpose: the rule ("nobody else has been active in the last 60 s") is a judgement call, and I would rather hear whether that shape fits before polishing tests around a mechanism you may want to replace — the alternative I can see is releasing on close plus an expiry that also covers app locks.

    #AI-ASSISTED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions