Repository navigation
fix: [OCISDEV-855] handle transient/InternalError storage failures in receivedsharecache retry path - #751
Conversation
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
c027295 to
3a05968
Compare
e203388 to
f8409e9
Compare
2403905
left a comment
There was a problem hiding this comment.
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
- Silent data loss —
retryPersistreports success on an exhausted budget (receivedsharecache.go:307). Proven; also the cause of the failing spec above. - Permanent wedge in
Disk.Upload—filelocksleaks its_localLocksentry on a failedTryLock, so the first failure makes that path unwritable for the process lifetime, at ~6.3s per attempt. Combined withInternalErrornow 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, andmetadata.CS3returns raw*status.Error/*url.Error, soUnavailable/DeadlineExceeded/connection-reset abort on the first attempt — while a permanentCODE_UNAUTHENTICATEDis retried 10 times (receivedsharecache.go:269). InternalErroris being made retryable to paper over a missing status mapping.internal/grpc/services/storageprovider/storageprovider.go:443has noAborted/AlreadyExistscase, so a lost CAS race arrives asCODE_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/Getupload, and hard-fail when the upload is refused — the PR's own spec codifiesPermissionDenied→Listerrors. 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 returnsnilwith an emptySpacesinstalled, soListreports 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.Uploadalso 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 inpkg/utils/ldap/pool.goandpkg/events/stream/nats.go. ItsWithMaxTries+Permanentwould 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.
bddbd22 to
72ab7b3
Compare
|
The test shows that the code is flaky |
2403905
left a comment
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
[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:
- G1 holds the lock on inode I.
- G2 (admitted by the
Load-then-Storerace at:69) spins in theTryLockloop holding an open fd on I — gofrs/flock v0.13 only callssetFhwhenf.fh == nil(flock_unix.go:149), so it never reopens. - G2 exhausts its budget and, with this change, clears the map entry.
- G1 finishes:
Unlock,os.Remove(path)unlinks I, deletes entry. - G3 arrives, misses the cleared entry, opens the path with
O_CREATEgetting a new inode J, locks it. - 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).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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() { |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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)) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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 != "" { |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, "") | |||
There was a problem hiding this comment.
[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 whenIfNoneMatchequals the current etag. If apersistfails withAborted/PreconditionFailedfrom 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 equalcalcEtag),needsResyncis cleared andpersistFuncretries unchanged. That repeats untilpersistAttemptshits 20, thenAddreturns the originalAbortedto 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.etagmeanspersistat:462keeps taking therss.etag != ""branch instead of theIfNoneMatch: *bootstrap. Ifreceived.jsonwas removed (space reprovisioned, admin cleanup, restore from backup), that write silently succeeds againstDiskbecause of the absent-file IfMatch hole atdisk.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) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
2cd2ec8 to
cf559f4
Compare
|
Ran the k6 load test against this branch and against plain
Both runs hit the same 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.
…IfStale bootstrap
9d033e3 to
ef1dab0
Compare
… 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]>
… 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]>
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]>
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]>
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]>
…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]>
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]>
…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]>
… receivedsharecache retry path (#751)
… 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.
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.
…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.
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-313for 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).