Skip to content

fix: [OCISDEV-855] handle transient/InternalError storage failures in receivedsharecache retry path - #751

Merged
mklos-kw merged 31 commits into
stable-8.0from
fix/ocisdev-855-review
Oct 8, 2026
Merged

mklos-kw merged 31 commits into
stable-8.0from
fix/ocisdev-855-review

Conversation

@mklos-kw

@mklos-kw mklos-kw commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

Related #709

CAS/optimistic-locking bugs found and fixed (OCISDEV-855)

0. Original ticket bug. Writers save every share in one file with a plain etag check, so one writer's save can silently overwrite another writer's save when both race the same file. Fix across all three caches: on a lost race, re-read the current file and merge the new change in instead of blindly overwriting — see point 1 below for the specific hole in that re-read logic.

1. Re-read after a lost race wiped out other people's shares. When a writer lost the race and re-read the file to merge in its change, finding the file briefly missing made it reset the file to empty, throwing away shares another writer had just saved. Fix: only treat "file missing" as empty when there's no prior known version; otherwise treat it as a real conflict and fail instead of erasing data. File: pkg/share/manager/jsoncs3/cas/cas.go (DecideNotFoundReset). Test: "fails instead of dropping other shares when the post-conflict resync finds the file gone" (pkg/share/manager/jsoncs3/providercache/providercache_test.go) and "fails only the write that races the deletion, leaving every other persisted share intact (OCISDEV-855)" (tests/integration/grpc/receivedsharecache_concurrent_test.go).

2. Couldn't tell "file never existed" apart from "file got deleted." A missing file during that same re-read looks identical whether it's a brand-new user with nothing yet or a file that really did just get deleted — guessing wrong either loses data or blocks forever. Fix: for the CS3 backend, ask the server's trash/recycle history to tell the two cases apart instead of guessing. File: pkg/storage/utils/metadata/cs3.go (WasRecentlyDeleted, ~line 426). Test: "errors on a cold-start NotFound when the backend confirms the file was trashed" (providercache_test.go).

3. A file still being uploaded looked like a plain read error. Reading a file's contents while another request was still writing it returned a generic error instead of "come back shortly," so retries didn't know to just wait. Fix: check for an in-progress-upload marker and return a proper "try again shortly" error instead. File: pkg/storage/utils/decomposedfs/decomposedfs.go:1131-1132. Test: "returns TooEarly instead of a raw error when the node is still processing" (pkg/storage/utils/decomposedfs/decomposedfs_test.go).

4. Download lost its "not found" status on the way to the browser, became a 500. When the file genuinely wasn't there, the error got wrapped in plain text twice on the way out, so the client saw a generic server error instead of "not found" and didn't retry. Fix: stop wrapping it once it's already correctly typed, and have the blob store say "not found" from the start. Files: pkg/storage/utils/decomposedfs/decomposedfs.go:1134-1138, pkg/storage/utils/decomposedfs/revisions.go:183-186, pkg/storage/fs/ocis/blobstore/blobstore.go:107-121. Test: "preserves NotFound typing when the blob disappears after the node is resolved" (decomposedfs_test.go) and "returns a typed NotFound when the blob is missing" (pkg/storage/fs/ocis/blobstore/blobstore_test.go).

5. Two upload-conflict cases weren't recognized by the gRPC layer, both became generic server errors. Losing a race or trying to create a file that already exists both came back as unhelpful "internal error" instead of something a client can retry on. Fix: map those two cases to their proper conflict status codes. File: internal/grpc/services/storageprovider/storageprovider.go:445-448. Test: TestInitiateFileUpload_LostCASRaceStatusMapping (internal/grpc/services/storageprovider/storageprovider_test.go).

6. Error messages threw away the original failure reason. Any HTTP status the client didn't specifically recognize got turned into "internal error" with no detail about what actually went wrong. Fix: keep the original status code in the error text. File: pkg/errtypes/errtypes.go:388. Test: TestUnmappedStatusKeptInMessage (pkg/errtypes/errtypes_test.go).

7. A retry loop could report "success" after every real attempt had failed. A later, unrelated successful check was allowed to erase the memory of the real failure, so the caller was told everything was fine when it wasn't. Fix: only remember the last real failure, don't let an unrelated success overwrite it. File: pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache.go:262. Test: "returns an error when the retry budget is exhausted, never a false success" (receivedsharecache_test.go:304).

8. Permanent errors burned the full retry budget before giving up. A bad-login or bad-request error was retried just as many times as a flaky-network error, wasting time before eventually failing anyway. Fix: tell permanent errors apart from temporary ones and fail fast on the permanent kind. File: receivedsharecache.go:276-286 (and :308-313 for the first read). Tests: "fails fast on a permanent InternalError instead of burning the retry budget" and "fails fast on a permanent InternalError on cold-start sync instead of burning the retry budget" (receivedsharecache_test.go).

9. Retrying a write with data it already knew was stale. If the refresh-after-failure step itself failed, the loop went ahead and retried the write anyway using the old, known-bad data, guaranteeing another failure. Fix: keep retrying the refresh step itself (within its own limit) until it actually gets fresh data before retrying the write. File: receivedsharecache.go:254-272. Test: "does not reuse stale state when the post-failure resync itself fails transiently" (receivedsharecache_test.go:387).

@mklos-kw
mklos-kw requested a review from a team as a code owner September 28, 2026 10:21
@kw-security

kw-security commented Sep 28, 2026 •

Copy link
Copy Markdown

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues
✅ Code Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@mklos-kw
mklos-kw force-pushed the fix/ocisdev-855-review branch from c027295 to 3a05968 Compare September 29, 2026 08:27
@mklos-kw
mklos-kw changed the base branch from main to stable-8.0 September 29, 2026 08:28
@mklos-kw
mklos-kw force-pushed the fix/ocisdev-855-review branch 2 times, most recently from e203388 to f8409e9 Compare September 29, 2026 10:04

@2403905 2403905 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: 20 findings, 2 blockers

Reviewed at head 6ce8832. I checked the branch out into a scratch worktree and ran things rather than reading only — go build, go vet, gofmt, and the new suites — plus two throwaway probe tests to isolate specific behaviours (since removed). Two findings are empirically proven rather than inferred.

The PR's own new test fails

preserves every share when 40 replicas write concurrently through the real disk lock failed on a full-tree run with share-36 missing, while all 40 Add calls returned nil.

I reduced that to a deterministic reproducer: with an Upload that always returns errtypes.Aborted and a Download that succeeds, Cache.Add returns nil — success — after 10 upload attempts with nothing persisted. retryPersist returns the loop-scoped err variable, which the successful resync on the final iteration reset to nil. Details inline at pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache.go:307.

Blockers

  1. Silent data loss — retryPersist reports success on an exhausted budget (receivedsharecache.go:307). Proven; also the cause of the failing spec above.
  2. Permanent wedge in Disk.Upload — filelocks leaks its _localLocks entry on a failed TryLock, so the first failure makes that path unwritable for the process lifetime, at ~6.3s per attempt. Combined with InternalError now being retryable, that is ~63s of blocking per call under the per-user mutex, never recovering. Proven; pkg/storage/utils/metadata/disk.go:100.

Structural concerns

  • The retry budget shrank 10x, not grew. A resync consumes a whole loop iteration, so 20 attempts is ~10 real persists, against 100 in the deleted code — on the exact path this PR hardens (receivedsharecache.go:246).
  • The transient class the PR is named after is excluded. Classification uses bare type switches instead of errors.As, and metadata.CS3 returns raw *status.Error/*url.Error, so Unavailable/DeadlineExceeded/connection-reset abort on the first attempt — while a permanent CODE_UNAUTHENTICATED is retried 10 times (receivedsharecache.go:269).
  • InternalError is being made retryable to paper over a missing status mapping. internal/grpc/services/storageprovider/storageprovider.go:443 has no Aborted/AlreadyExists case, so a lost CAS race arrives as CODE_INTERNAL. Two cases in the switch this PR already edits fix it at the source, and then reva's documented catch-all can stay fatal.
  • Reads now write. The NotFound bootstrap makes List/Get upload, and hard-fail when the upload is refused — the PR's own spec codifies PermissionDenied → List errors. A user with no received shares gets a 500 at login instead of [] (receivedsharecache.go:337). Losing that bootstrap's CAS race is worse: it returns nil with an empty Spaces installed, so List reports zero shares for a user who has them (:339).
  • The concurrency specs do not test what they claim. The one-shot barrier is filled by the 15 bootstrap uploads and is already released before any real persist runs, so the spec passes regardless of the retry logic (receivedsharecache_test.go:173). BarrierStorage.Upload also ignores its ctx, so an under-filled barrier hangs CI instead of failing it.
  • The 60-line manual retry loop duplicates backoff.Retry, already a direct dependency used in pkg/utils/ldap/pool.go and pkg/events/stream/nats.go. Its WithMaxTries + Permanent would have made blocker 1 unrepresentable (receivedsharecache.go:238).

CI will fail as-is

pkg/storage/utils/decomposedfs/upload_async_test.go:73 is not gofmt-clean — an unrelated one-line whitespace change that gofmt wants reverted. defer filelocks.ReleaseLock(lock) in pkg/storage/utils/metadata/disk.go:105 drops the error, which errcheck flags.

Not inline, no line to anchor to

No changelog entry. None of the 11 changed files is under changelog/unreleased/, and the reverted PR #709's entry is gone and unreplaced. Two user-visible behaviour changes will be missing from the 8.0.x notes: InternalError becoming retryable, and List gaining a write. Please add one per changelog/README.md / changelog/TEMPLATE.

Missing license headers on the three added files — noted inline on pkg/storage/utils/metadata/barrier_storage.go; .drone.star runs a license-scan step.

Suggested order of work

Blocker 1 first, since it is currently hiding every other failure in this PR's own tests — including, most likely, some of the ones I am reporting. Then the storageprovider.go status mapping, which lets the InternalError classification be reverted rather than tuned. The remainder follow from those two.

@mklos-kw
mklos-kw force-pushed the fix/ocisdev-855-review branch from bddbd22 to 72ab7b3 Compare September 30, 2026 08:06
mklos-kw added a commit that referenced this pull request Oct 1, 2026
@2403905

2403905 commented Oct 1, 2026

Copy link
Copy Markdown

The test shows that the code is flaky

 for i in $(seq 1 20); do echo "--- run $i"; \
  go test ./pkg/share/manager/jsoncs3/receivedsharecache/ -run TestReceivedShareCache \
    -ginkgo.focus='40 replicas write concurrently through the real disk lock' -count=1 || break; done
--- run 1
ok  	github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache	10.815s
--- run 2
ok  	github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache	8.774s
--- run 3
ok  	github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache	10.867s
--- run 4
ok  	github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache	11.429s
--- run 5
ok  	github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache	9.891s
--- run 6
ok  	github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache	10.901s
--- run 7
ok  	github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache	10.816s
--- run 8
Running Suite: ReceivedShareCache Suite - ./projects/owncloud/reva/pkg/share/manager/jsoncs3/receivedsharecache
===================================================================================================================================
Random Seed: 1790872237

Will run 1 of 30 specs
SSSSSSSS
------------------------------
• [FAILED] [10.004 seconds]
Cache concurrent writes from multiple cache instances [It] preserves every share when 40 replicas write concurrently through the real disk lock
./projects/owncloud/reva/pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache_test.go:202

  [FAILED] missing share-3
  Expected
      <map[string]*receivedsharecache.State | len:39>: {
          "share-1": {State: 1, MountPoint: nil, Hidden: false},
          "share-33": {State: 1, MountPoint: nil, Hidden: false},
          "share-24": {State: 1, MountPoint: nil, Hidden: false},
          "share-28": {State: 1, MountPoint: nil, Hidden: false},
          "share-4": {State: 1, MountPoint: nil, Hidden: false},
          "share-20": {State: 1, MountPoint: nil, Hidden: false},
          "share-0": {State: 1, MountPoint: nil, Hidden: false},
          "share-11": {State: 1, MountPoint: nil, Hidden: false},
          "share-38": {State: 1, MountPoint: nil, Hidden: false},
          "share-21": {State: 1, MountPoint: nil, Hidden: false},
          "share-13": {State: 1, MountPoint: nil, Hidden: false},
          "share-2": {State: 1, MountPoint: nil, Hidden: false},
          "share-26": {State: 1, MountPoint: nil, Hidden: false},
          "share-5": {State: 1, MountPoint: nil, Hidden: false},
          "share-36": {State: 1, MountPoint: nil, Hidden: false},
          "share-23": {State: 1, MountPoint: nil, Hidden: false},
          "share-37": {State: 1, MountPoint: nil, Hidden: false},
          "share-18": {State: 1, MountPoint: nil, Hidden: false},
          "share-22": {State: 1, MountPoint: nil, Hidden: false},
          "share-8": {State: 1, MountPoint: nil, Hidden: false},
          "share-6": {State: 1, MountPoint: nil, Hidden: false},
          "share-25": {State: 1, MountPoint: nil, Hidden: false},
          "share-19": {State: 1, MountPoint: nil, Hidden: false},
          "share-27": {State: 1, MountPoint: nil, Hidden: false},
          "share-30": {State: 1, MountPoint: nil, Hidden: false},
          "share-7": {State: 1, MountPoint: nil, Hidden: false},
          "share-39": {State: 1, MountPoint: nil, Hidden: false},
          "share-15": {State: 1, MountPoint: nil, Hidden: false},
          "share-31": {State: 1, MountPoint: nil, Hidden: false},
          "share-29": {State: 1, MountPoint: nil, Hidden: false},
          "share-17": {State: 1, MountPoint: nil, Hidden: false},
          "share-16": {State: 1, MountPoint: nil, Hidden: false},
          "share-10": {State: 1, MountPoint: nil, Hidden: false},
          "share-12": {State: 1, MountPoint: nil, Hidden: false},
          "share-32": {State: 1, MountPoint: nil, Hidden: false},
          "share-35": {State: 1, MountPoint: nil, Hidden: false},
          "share-14": {State: 1, MountPoint: nil, Hidden: false},
          "share-34": {State: 1, MountPoint: nil, Hidden: false},
          "share-9": {State: 1, MountPoint: nil, Hidden: false},
      }
  to have key
      <string>: share-3
  In [It] at:
./projects/owncloud/reva/pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache_test.go:234 @ 10/01/26 18:30:47.566
------------------------------
SSSSSSSSSSSSSSSSSSSSS

Summarizing 1 Failure:
  [FAIL] Cache concurrent writes from multiple cache instances [It] preserves every share when 40 replicas write concurrently through the real disk lock

  ./projects/owncloud/reva/pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache_test.go:234

Ran 1 of 30 Specs in 10.005 seconds
FAIL! -- 0 Passed | 1 Failed | 0 Pending | 29 Skipped
--- FAIL: TestReceivedShareCache (10.01s)
FAIL
FAIL	github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache	10.433s
FAIL

@2403905 2403905 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: Tier 1 (blocks merge) and Tier 2 (real, narrower)

Inline comments below are tagged [blocks merge] or [real, narrower].

Scope note on how this was produced: the findings came from a review of an earlier revision of this branch, then re-verified by reading 94c6e48f5 — every item below is still present at the current head.

One honest caveat up front: the lost-update failure that first exposed this (the PR's own 40-replica spec failing with missing share-25 and map len 39 while all 40 Add calls returned nil) was observed on the earlier revision. At 94c6e48f5 that spec passed 7/7 runs for me, so it is no longer a reliable reproducer. The underlying non-exclusivity is unchanged, though, and was measured directly rather than inferred: a 40-goroutine AcquireWriteLock/ReleaseLock loop logged writes=69487 overlaps=24885 acquireFailures=10513 — 36% of critical sections had a second holder inside at the same time. The spec passing at head means the window got narrower, not that it closed.

Two items that could not be anchored inline (not in the diff)

[blocks merge] pkg/storage/utils/metadata/storage.go:83 — the compare-and-swap this PR hardens rests on calcEtag(mtime, size), which collides whenever two writes produce the same length in the same mtime tick. receivedsharecache's payload routinely keeps its byte length across writes (a State going PENDING→ACCEPTED, a MountPoint swapped for one of equal length), and on 1-second-mtime filesystems — ext3, many NFS mounts, several container overlay setups — two such writes a few hundred ms apart hash identically. persist's IfMatch then succeeds against content it never read and no retry fires, because no conflict was detected. Retry/backoff layered on this token cannot make the CAS sound; it needs a content hash or a monotonic version counter. Probably a separate PR, but it bounds what this one can claim.

[real, narrower] pkg/storage/utils/metadata/disk.go:201 — SimpleDownload does res, err := disk.Download(...); return res.Content, err, nil-dereferencing on every Download error path. This PR adds a new one (errtypes.NotModified at disk.go:188). SimpleDownload passes no IfNoneMatch so that specific arm is unreachable through it today, but NotFound and the stat/read errors already are: a missing metadata file panics the serving goroutine instead of returning errtypes.NotFound. One line below changed code, worth fixing while the file is open.

Also missing

No changelog/unreleased/ entry.

There are further findings (a Tier 3 on barrier_storage.go being a test double compiled into the production metadata package, missing license headers on six new files, .flock files being enumerated as spaces by ListDir, and the maxIterations = 2 * maxPersistAttempts budget conflation) — happy to add them if useful, but this review is scoped to Tier 1 and Tier 2.

Comment thread pkg/storage/utils/metadata/disk.go Outdated
func (disk *Disk) Upload(_ context.Context, req UploadRequest) (res *UploadResponse, err error) {
p := disk.targetPath(req.Path)

// Serialize check+write across processes to eliminate the TOCTOU race.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[blocks merge] This comment states the premise of the PR, and the premise does not hold: filelocks.AcquireWriteLock does not provide mutual exclusion, so Upload's stat-check-then-write is still not atomic and the IfMatchEtag CAS can be passed by two concurrent writers.

Root cause is one line away, in pkg/storage/utils/filelocks/filelocks.go:69-:76 — getMutexedFlock does a non-atomic sync.Map Load then Store, so two goroutines can both miss and both store, each walking away with its own *flock.Flock for the same path. Measured: 4 goroutines racing on one path for 20000 rounds produced 895 extra concurrent holders (~4.5% of contended rounds). Once two Flock objects exist for a path the _localLocks gate serializes nothing.

Consequence is the worst failure mode in this set: two uploaders both stat the file, both see etag E, both pass IfMatchEtag == E, and the second rename silently discards the first's content. In production that is a received share a user accepted/renamed/hid, which Add acknowledged with nil, gone from received.json.

Fix is small: _localLocks.LoadOrStore and branch on the returned loaded flag instead of Load-then-Store. Until filelocks is actually exclusive, nothing built on top of it can claim atomicity — so I'd land that first and reword this comment to match what the lock really guarantees.

@mklos-kw mklos-kw Oct 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced (10/10 fail) and fixed via LoadOrStore, ac1badb; test passes 20/20 after.
40-replica spec: 0/50 failures post-fix vs 1/20 pre-fix.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is about the Disk backend's lock mechanics. OCISDEV-855 is about jsoncs3's CS3 storage path, which doesn't use filelocks. Suggest tracking Disk-backend review as a separate follow-up task.

// never actually acquired the OS-level lock; release the local
// bookkeeping entry too, or every future call for this path is
// permanently wedged regardless of whether the real lock clears
releaseMutexedFlock(n)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[blocks merge] This releases the bookkeeping entry unconditionally, but the goroutine reaching this branch is precisely the one that failed to acquire the OS lock — so it can be deleting an entry a different goroutine still legitimately owns. Combined with ReleaseLock's os.Remove of the .flock file, that lets two holders end up in the critical section on different inodes:

  1. G1 holds the lock on inode I.
  2. G2 (admitted by the Load-then-Store race at :69) spins in the TryLock loop holding an open fd on I — gofrs/flock v0.13 only calls setFh when f.fh == nil (flock_unix.go:149), so it never reopens.
  3. G2 exhausts its budget and, with this change, clears the map entry.
  4. G1 finishes: Unlock, os.Remove(path) unlinks I, deletes entry.
  5. G3 arrives, misses the cleared entry, opens the path with O_CREATE getting a new inode J, locks it.
  6. G2's next retry locks the orphaned I. G2 and G3 are both inside the critical section.

The pre-existing behaviour of leaving the entry in place was a genuine wedge, so the intent here is right — but the release has to be ownership-checked: compare identity before deleting, and stop unlinking the lock file (that unlink is also what makes step 5 possible).

@mklos-kw mklos-kw Oct 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not reproduced -- built the exact scenario, stale holder correctly failed to relock.
gofrs/flock v0.13 resets the fd on every failed TryLock, so retries always reopen fresh.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is about the Disk backend's lock mechanics. OCISDEV-855 is about jsoncs3's CS3 storage path, which doesn't use filelocks. Suggest tracking Disk-backend review as a separate follow-up task.

Comment thread pkg/storage/utils/metadata/disk.go Outdated
// transient under high write fan-in; classify so callers retry instead of aborting
return nil, errtypes.InternalError(fmt.Sprintf("acquiring write lock: %s", err))
}
defer func() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[blocks merge] if err == nil { err = rerr } converts a fully successful upload — res non-nil, content already renamed into place — into (res, rerr) whenever lock.Unlock or the os.Remove of the .flock file fails. ReleaseLock's own comment at filelocks.go:187 documents concurrent deletion of that file as a known issue (owncloud/ocis#3757), so this is not hypothetical.

Blast radius is larger than it looks: persist at receivedsharecache.go:468 then skips rss.etag = res.Etag, retryPersist sees an unclassified error and returns immediately, so Add reports failure for a share that was persisted — and the stale in-memory etag makes every subsequent persist for that user fail its CAS until something resyncs.

Log rerr, don't merge it into err. Cheapest fix in this review and one of the highest-impact.

@mklos-kw mklos-kw Oct 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced (10/10 fail) via a hammering race test, fixed in 18a3dc1 by dropping the err=rerr override.
Same test: 10/10 fail pre-fix, 10/10 pass post-fix.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is about the Disk backend's lock mechanics. OCISDEV-855 is about jsoncs3's CS3 storage path, which doesn't use filelocks. Suggest tracking Disk-backend review as a separate follow-up task.

Comment thread pkg/storage/utils/metadata/disk.go Outdated
lock, err := filelocks.AcquireWriteLock(p)
if err != nil {
// transient under high write fan-in; classify so callers retry instead of aborting
return nil, errtypes.InternalError(fmt.Sprintf("acquiring write lock: %s", err))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[real, narrower] Classifying a lock-acquisition failure as InternalError makes isSyncTransient retry it, and the cost per failure is high: ~6.3 s of sleeping (20 cycles × 30 ms factor, twice) before this returns. With retryPersist allowing up to 20 attempts, one Add can occupy ~126 s — all of it inside lockUser(userID), so every concurrent List/Get/Add/Remove for that user serializes behind it, and the caller's gRPC deadline fires long before, leaving the mutex held by an orphaned goroutine.

This path is reached in practice, not theoretically: 0.3% acquire-failure rate measured with 16 goroutines at the default cycle factor, 13% (10513 of 80000) with faster retries. Lock-acquisition exhaustion wants its own short, bounded classification rather than the generic transient-retry arm.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced (155ms blocked despite 10ms ctx deadline) and fixed by threading ctx through filelocks' acquire-wait loops.
Same test: fails pre-fix, passes post-fix (0.02s).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is about the Disk backend's lock mechanics. OCISDEV-855 is about jsoncs3's CS3 storage path, which doesn't use filelocks. Suggest tracking Disk-backend review as a separate follow-up task.

}
}()

if req.IfMatchEtag != "" {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[real, narrower] When the target does not exist, the IfMatchEtag precondition is silently treated as satisfied and the write proceeds: os.Stat returns ErrNotExist, the first branch is skipped by the !errors.Is(err, os.ErrNotExist) guard, the else if err == nil branch is skipped too, and control falls straight through to renameio.WriteFile. RFC 9110 requires If-Match to fail when there is no current representation.

A caller holding a stale etag for a file that was deleted (or whose metadata space was reprovisioned) therefore recreates it with stale content instead of getting PreconditionFailed and resyncing. It compounds with the sync arms at receivedsharecache.go:396: the in-memory etag stays non-empty, so persist keeps sending IfMatch for an absent file and the write always wins.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced (Upload succeeded instead of PreconditionFailed on a missing-file IfMatch) and fixed with an explicit ErrNotExist case.
Test: fails pre-fix, passes post-fix.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is about the Disk backend's lock mechanics. OCISDEV-855 is about jsoncs3's CS3 storage path, which doesn't use filelocks. Suggest tracking Disk-backend review as a separate follow-up task.

@@ -312,8 +400,12 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
span.SetStatus(codes.Ok, "")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[real, narrower] Both this NotModified arm and the NotFound arm at :396 return nil without refreshing state or clearing rss.etag, and retryPersist reads a nil sync as "resync done" — so it retries persist with the exact same stale etag.

Two distinct consequences:

  • NotModified: Disk.Download (disk.go:188) and the CS3 HTTP path both return it when IfNoneMatch equals the current etag. If a persist fails with Aborted/PreconditionFailed from a concurrent writer but by resync time the file's etag has come back to the value this replica already holds (a same-size rewrite, or a coarse-mtime filesystem producing an equal calcEtag), needsResync is cleared and persistFunc retries unchanged. That repeats until persistAttempts hits 20, then Add returns the original Aborted to the caller after ~20 backoff rounds — a user-visible share-accept failure where the old 100-iteration loop would eventually have succeeded.
  • NotFound: leaving a non-empty rss.etag means persist at :462 keeps taking the rss.etag != "" branch instead of the IfNoneMatch: * bootstrap. If received.json was removed (space reprovisioned, admin cleanup, restore from backup), that write silently succeeds against Disk because of the absent-file IfMatch hole at disk.go:112, resurrecting a stale snapshot of the user's received shares over whatever another replica bootstrapped meanwhile.

The NotFound arm should clear rss.etag; NotModified should not be reported to retryPersist as a completed resync.

func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
func isSyncTransient(err error) bool {
_, isTooEarly := err.(errtypes.IsTooEarly)
_, isInternal := err.(errtypes.IsInternalError)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[real, narrower] Treating errtypes.InternalError as transient makes this retry nearly everything, because InternalError is the catch-all in pkg/errtypes/errtypes.go:388: NewErrtypeFromHTTPStatusCode's default arm returns it for 401, 403-via-proxy, 500, 502, 503, 413, 415 and anything else unmapped.

So a metadata-space upload rejected because the machine-auth token expired (401), or because the dataprovider is misconfigured (500), now gets 20 attempts with backoff and a resync Download between each — the whole time holding the per-user mutex from lockUser, blocking every other receivedsharecache call for that user. These are permanent failures that previously failed fast. Widening the default arm's message elsewhere in this PR makes the catch-all broader, not narrower.

Transience should come from an explicit allow-list — TooEarly, Unavailable, DeadlineExceeded, ResourceExhausted — never from InternalError. The isTransientGRPCStatus helper right below is exactly the right shape; isInternal is the problem.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced (uploads=20 vs expected 1) and fixed -- dropped the InternalError retry arm in retryPersist.
Caught a regression: disk.go's lock-acquire-timeout used the same InternalError type; reclassified it as TooEarly. isSyncTransient's identical catch-all (line 230) is untested, separate finding.

2403905
2403905 previously approved these changes Oct 2, 2026
2403905
2403905 previously approved these changes Oct 7, 2026
2403905
2403905 previously approved these changes Oct 7, 2026

@2403905 2403905 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please validate with K6 tests

@mklos-kw

mklos-kw commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Ran the k6 load test against this branch and against plain stable-8.0 as a baseline, same test suite, same self-hosted runner, back to back.

  • Fix branch (ocis #13093, reva pinned to this PR): 100% checks passed (668/668), 0% HTTP failures (0/632), latency p95 684.53ms.
  • Baseline (ocis #13095, plain stable-8.0, no reva change): 100% checks passed (668/668), 0% HTTP failures (0/632), latency p95 667.36ms.

Both runs hit the same p(95)<500ms threshold and failed on it - that's a pre-existing latency ceiling on the test environment, not introduced by this PR. Everything else is identical: same iteration count (355), same 0% error rate, same 100% check pass rate including the share/upload/move/delete operations this PR touches.

Takeaway: no functional regression and no latency regression from these fixes under load.

…rors in CAS loop (#657)

* fix: ocisdev-855, cs3/decomposefs transactional concurent upload

* fix: ocisdev-855, cs3/decomposefs optimistic-abort concurent upload

* fix: ocisdev-855, cs3/decomposefs optimistic-abort concurent upload

* feat: logs and cleanup

* feat: cleanup

* feat: review fixes

* feat: cleanup in tracing

# Conflicts:
#	internal/grpc/services/storageprovider/storageprovider.go
#	pkg/rhttp/datatx/utils/download/download.go
#	pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache_test.go
…e Download in concurrent test

status.NewTooEarly was added after stable-8.0 branched; map IsTooEarly to
NewAborted instead (same retry semantics for the client).

DiskStorage.Upload on stable-8.0 uses os.WriteFile (not renameio), so
concurrent Download calls can read a partial file. Add a mutex to
barrierStorage that serializes Upload/Download pairs in the test.
@mklos-kw
mklos-kw merged commit e28d93d into stable-8.0 Oct 8, 2026
@mklos-kw
mklos-kw deleted the fix/ocisdev-855-review branch October 8, 2026 20:28
2403905 added a commit that referenced this pull request Nov 20, 2026
… receivedsharecache retry path (#830)

Backport of #751 from stable-8.0 (cherry picked from commit e28d93d).

Main had the first version of the retry loop (#657). This commit replaces it
with the cas package and the fixes of #751. The fix for OCISDEV-1685 needs them.

Differences from #751:

1. The jsoncs3 cache packages, the cas package, the test helpers and the
   integration test come unchanged from #751.
2. storageprovider.go keeps the IsTooEarly case of main. It adds the cases
   Aborted and AlreadyExists.
3. The TooEarly check in Decomposedfs.Download is not added. Main already
   returns ResourceProcessing for a node in processing.
4. The changes in tree.go and the new tests for tree.go, decomposedfs.go and
   storageprovider.go are not added. Main changed the upload path with the
   upload coordinator, and the tests do not fit.

Co-authored-by: Michal Klos <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2403905 added a commit that referenced this pull request Nov 20, 2026
… failures in receivedsharecache retry path (#831)

Backport of #751 from stable-8.0 (cherry picked from commit e28d93d).

Main had the first version of the retry loop (#657). This commit replaces it
with the cas package and the fixes of #751. The fix for OCISDEV-1685 needs them.

Differences from #751:

1. The jsoncs3 cache packages, the cas package, the test helpers and the
   integration test come unchanged from #751.
2. storageprovider.go keeps the IsTooEarly case of main. It adds the cases
   Aborted and AlreadyExists.
3. The TooEarly check in Decomposedfs.Download is not added. Main already
   returns ResourceProcessing for a node in processing.
4. The changes in tree.go and the new tests for tree.go, decomposedfs.go and
   storageprovider.go are not added. Main changed the upload path with the
   upload coordinator, and the tests do not fit.

Co-authored-by: Michal Klos <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2403905 added a commit that referenced this pull request Nov 20, 2026
Backport of #813 from stable-8.0 (cherry picked from commit ee73b99).

This commit depends on the backport of #751 (OCISDEV-855). It applies on top of it.

Differences from #813:

1. ProcessEvents keeps the tracing and autoprop context of main. It passes
   this context to purgeSpace and logs the errors that purgeSpace returns.
2. The tests of the received share cache use the new test storage
   fullDownloadStorage. main has a newer metadata.Disk. It answers NotModified
   when IfNoneMatch has the etag of the file. The tests inject a conflict
   while the file does not change, so a re-read would keep the state of the
   failed write. A real conflict changes the etag, and the production code is
   not affected.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2403905 added a commit that referenced this pull request Nov 20, 2026
Backport of #813 from stable-8.0 (cherry picked from commit ee73b99).

This commit depends on the backport of #751 (OCISDEV-855). It applies on top of it.

Differences from #813:

1. ProcessEvents keeps the tracing and autoprop context of stable-9.0. It passes
   this context to purgeSpace and logs the errors that purgeSpace returns.
2. The tests of the received share cache use the new test storage
   fullDownloadStorage. stable-9.0 has a newer metadata.Disk. It answers NotModified
   when IfNoneMatch has the etag of the file. The tests inject a conflict
   while the file does not change, so a re-read would keep the state of the
   failed write. A real conflict changes the etag, and the production code is
   not affected.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2403905 added a commit to owncloud/ocis that referenced this pull request Nov 23, 2026
Update reva to the branch of owncloud/reva#832, the backport of
owncloud/reva#813. It depends on owncloud/reva#830, the backport of
owncloud/reva#751.

A stale group share is a share ID in the group cache that has no share. On
each listing of the received shares, the jsoncs3 share manager uploaded the
received.json file of the user again with the same content, and the stale ID
stayed. The new reva removes stale group shares, and it removes many shares
with one upload for each document.

The removal of shares uses at least 3 parallel removals, also when
SHARING_USER_JSONCS3_MAX_CONCURRENCY is 1. The default of the setting does
not change. The setting description and the changelog describe the minimum.

Backport of #13460.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Roman Perekhod <[email protected]>
2403905 added a commit to owncloud/ocis that referenced this pull request Nov 23, 2026
…e manager

Update reva to the branch of owncloud/reva#833, the backport of
owncloud/reva#813. It depends on owncloud/reva#831, the backport of
owncloud/reva#751.

A stale group share is a share ID in the group cache that has no share. On
each listing of the received shares, the jsoncs3 share manager uploaded the
received.json file of the user again with the same content, and the stale ID
stayed. The new reva removes stale group shares, and it removes many shares
with one upload for each document.

The removal of shares uses at least 3 parallel removals, also when
SHARING_USER_JSONCS3_MAX_CONCURRENCY is 1. The default of the setting does
not change. The setting description and the changelog describe the minimum.

Backport of #13460.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Roman Perekhod <[email protected]>
2403905 added a commit that referenced this pull request Nov 23, 2026
Backport of #813 from stable-8.0 (cherry picked from commit ee73b99).

This commit depends on the backport of #751 (OCISDEV-855). It applies on top of it.

Differences from #813:

1. ProcessEvents keeps the tracing and autoprop context of main. It passes
   this context to purgeSpace and logs the errors that purgeSpace returns.
2. The tests of the received share cache use the new test storage
   fullDownloadStorage. main has a newer metadata.Disk. It answers NotModified
   when IfNoneMatch has the etag of the file. The tests inject a conflict
   while the file does not change, so a re-read would keep the state of the
   failed write. A real conflict changes the etag, and the production code is
   not affected.

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2403905 added a commit that referenced this pull request Nov 23, 2026
…833)

Backport of #813 from stable-8.0 (cherry picked from commit ee73b99).

This commit depends on the backport of #751 (OCISDEV-855). It applies on top of it.

Differences from #813:

1. ProcessEvents keeps the tracing and autoprop context of stable-9.0. It passes
   this context to purgeSpace and logs the errors that purgeSpace returns.
2. The tests of the received share cache use the new test storage
   fullDownloadStorage. stable-9.0 has a newer metadata.Disk. It answers NotModified
   when IfNoneMatch has the etag of the file. The tests inject a conflict
   while the file does not change, so a re-read would keep the state of the
   failed write. A real conflict changes the etag, and the production code is
   not affected.

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
mklos-kw added a commit that referenced this pull request Nov 24, 2026
2403905 added a commit that referenced this pull request Nov 24, 2026
… failures in receivedsharecache retry path (#843)

Backport of #751 from stable-8.0 (cherry picked from commit e28d93d).

Main had the first version of the retry loop (#657). This commit replaces it
with the cas package and the fixes of #751. The fix for OCISDEV-1685 needs them.

Differences from #751:

1. The jsoncs3 cache packages, the cas package, the test helpers and the
   integration test come unchanged from #751.
2. storageprovider.go keeps the IsTooEarly case of main. It adds the cases
   Aborted and AlreadyExists.
3. The TooEarly check in Decomposedfs.Download is not added. Main already
   returns ResourceProcessing for a node in processing.
4. The changes in tree.go and the new tests for tree.go, decomposedfs.go and
   storageprovider.go are not added. Main changed the upload path with the
   upload coordinator, and the tests do not fit.

Co-authored-by: Michal Klos <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>

Backport of #831 to stable-8.2.
2403905 added a commit that referenced this pull request Nov 24, 2026
Backport of #813 from stable-8.0 (cherry picked from commit ee73b99).

This commit depends on the backport of #751 (OCISDEV-855). It applies on top of it.

Differences from #813:

1. ProcessEvents keeps the tracing and autoprop context of stable-9.0. It passes
   this context to purgeSpace and logs the errors that purgeSpace returns.
2. The tests of the received share cache use the new test storage
   fullDownloadStorage. stable-9.0 has a newer metadata.Disk. It answers NotModified
   when IfNoneMatch has the etag of the file. The tests inject a conflict
   while the file does not change, so a re-read would keep the state of the
   failed write. A real conflict changes the etag, and the production code is
   not affected.

Co-authored-by: Claude Sonnet 5.5 <[email protected]>

Backport of #833 to stable-8.2.
2403905 added a commit that referenced this pull request Nov 25, 2026
…844)

Backport of #813 from stable-8.0 (cherry picked from commit ee73b99).

This commit depends on the backport of #751 (OCISDEV-855). It applies on top of it.

Differences from #813:

1. ProcessEvents keeps the tracing and autoprop context of stable-9.0. It passes
   this context to purgeSpace and logs the errors that purgeSpace returns.
2. The tests of the received share cache use the new test storage
   fullDownloadStorage. stable-9.0 has a newer metadata.Disk. It answers NotModified
   when IfNoneMatch has the etag of the file. The tests inject a conflict
   while the file does not change, so a re-read would keep the state of the
   failed write. A real conflict changes the etag, and the production code is
   not affected.

Co-authored-by: Claude Sonnet 5.5 <[email protected]>

Backport of #833 to stable-8.2.
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.

4 participants