Skip to content

fix(posix): stale metadata cache after 'opencloud posixfs scan' - #962

Open
NickWalters wants to merge 6 commits into
opencloud-eu:mainfrom
NickWalters:fix/posix-scan-stale-cache
Open

NickWalters wants to merge 6 commits into
opencloud-eu:mainfrom
NickWalters:fix/posix-scan-stale-cache

Conversation

@NickWalters

@NickWalters NickWalters commented Nov 2, 2026 •

Copy link
Copy Markdown

Part of opencloud-eu/opencloud#3804 (proposed fixes 3 and 4). Fixes #1006.

With the default memory metadata cache, opencloud posixfs scan changes metadata on disk that the running server does not see.

  • Propagation started from the cached tree size and overwrote the one the scan wrote. LockAndReadNode now drops the cache entry after it locks the node, and propagateSizeDiff reads the old tree size from disk.
  • With watch_fs, the server skipped a file the scan had assimilated and kept its old size, checksums and etag. The tree now compares the cached mtime of each known item with the one on disk. If they differ, or the entry is missing, it reloads the cache of the item and of its parents. In one scan walk each parent reloads only once (Pascal's patch).
  • posix: an overwriting upload can deadlock on its own node lock after a metadata cache miss #1006: PrepareUpload now reads an existing node under the lock it takes. Before, the read of a cold cache entry waited for that same lock.

InvalidateCache does nothing for nats-js-kv and redis, because shared stores do not go stale. Pascal measured a full rescan after touching 50,000 files at 214 s, against 188 s on main.

Tests: TestUploadWithColdMetadataCache for #1006, and "propagates from the tree size on disk" plus the specs under "changed by another process" for the scan. Each fails without its fix.

Not fixed: without watch_fs the server serves cached reads until the TTL (24h) runs out or it restarts.

@NickWalters

Copy link
Copy Markdown
Author

@pbleser-oc, you reported opencloud-eu/opencloud#3804. Could you review this PR when you have time?

It covers your proposed fixes 3 and 4. When the watcher skips an item that the scan already assimilated, it now drops the stale cache. Propagation now reads the tree size from disk under the lock. Scenario A (memory cache without watch_fs) is still open.

@pbleser-oc

Copy link
Copy Markdown
Member

Hi @NickWalters, thank you for picking this up, and sorry for the wait. I wanted to give it a proper look before answering.

I ran the scenarios from opencloud-eu/opencloud#3804 against your branch, and against its base (c7b9e31) for comparison:

  • C (watch_fs, scan within the debounce delay): fixed. Size, checksums, download and tree size are all correct now.
  • A (memory, no watch_fs): the tree size on disk is correct now (33 instead of 16). The reads stay stale until the TTL runs out, as you wrote.
  • B, D and F stay correct.

Your tests pass, and each of them fails when its fix is taken out. I also like that dropStaleCache compares the metadata mtime on disk, so it only fires when another process actually wrote metadata.

There's one thing that makes me want to hold off merging for now, though.

Dropping the cache entry of a node right after locking it means that more reads go to disk while the lock is held. On posix, a read that misses the cache takes the metadata lock, and that lock is tracked per node object, not per file: when a node is locked through one object and read through another one, the read waits for its own lock. That's also why posix refuses a noop file metadata cache (#650).

In a stress test (concurrent uploads, moves and deletes on a few files, plus opencloud posixfs scan in a loop), uploads got stuck that way on main as well, so it's not something your PR introduces. But with your change, such cache misses become more likely, and I'd rather not make that more frequent before it's fixed.

The upload path where this happens is being reworked right now, and more changes to it are coming in the next days and weeks. Once that has settled, I'll look at your PR again, also with the stress test, and we'll see what's needed to get it in. Most of it may well apply as it is.

About the cost with shared stores: your offer to limit the invalidation to process-local stores sounds good to me, since nats-js-kv and redis don't go stale in the first place. Not sure what the others think, though.

Thanks again, this is a really thorough PR, and opencloud-eu/opencloud#3804 is much better understood thanks to it.

@github-project-automation github-project-automation Bot moved this to Qualification in OpenCloud Team Board Nov 3, 2026
@NickWalters

NickWalters commented Nov 4, 2026 •

Copy link
Copy Markdown
Author

Thanks for the detailed testing. Invalidation now applies only to process-local caches, and stale entries reload under each node’s lock. I also reproduced the cold-cache upload deadlock on main and fixed that path with a lock-aware read. The regression, race-enabled mixed stress runs, lint, and platform vet checks pass. Some concurrent scan errors remain, so I’m not claiming this resolves every concurrency issue. Could you rerun your workload once the upload path rework is done?

@NickWalters
NickWalters force-pushed the fix/posix-scan-stale-cache branch from 1a17fcf to 601916f Compare November 16, 2026 08:19
@NickWalters

Copy link
Copy Markdown
Author

Rebased on main. The conflict came from a6864c7, which removed the legacy upload path and upload/store.go.

The lock-aware read for an existing upload node moved to PrepareUpload (pkg/storage/pkg/decomposedfs/prepare_upload.go). With the hybrid backend, an unlocked read of a cold cache entry waits for the node lock. When PrepareUpload already holds that lock, the upload blocks forever. It now reads the old node with LockAndReadNode and keeps that lock.

TestUploadWithColdMetadataCache now expires the cache entry in a loop while 50 overwrites run. Without the fix it fails 3 of 3 runs. With the fix it passes under -race. The stress test helper now clears the processing flag after commit, as the coordinator does.

Checked: go test -race on posix, decomposedfs, cache and upload. Also darwin and freebsd vet, and golangci-lint (0 issues).

@butonic could you approve the CI run and take a look? You wrote the coordinator change this builds on.

@pbleser-oc

Copy link
Copy Markdown
Member

@NickWalters, thanks for the rebase, and for moving the fix into PrepareUpload
I've just approved the CI run.

I opened #1006 for the upload deadlock, since it's a bug on main on its own.

Would you mind adding "Fixes #1006" to the description, so that it gets closed with this PR?

Thank you.

@pbleser-oc

Copy link
Copy Markdown
Member

One more point, about what reloadStaleCache costs. I measured it on your earlier head (1a17fcf); the rebase doesn't change that code, so it should still hold. Setup: 50,000 files three folders deep, the default memory cache, and opencloud posixfs scan in a separate process.

  • A rescan where nothing changed: no difference (18–19 s on both). The scan skips clean folders, and known items that didn't change never reach assimilate.
  • Uploads (k6, 8 clients) during a rescan, also during one that re-assimilates everything: no measurable difference in latency, and no failures.
  • A rescan after all 50,000 files changed on disk (a touch of all of them, like after an rsync or a restore): between 25% and 40% slower in my runs, e.g. a median of 261 s instead of 188 s.

The last one is because the scan process starts with an empty cache, so every changed file finds its entry missing and reloads itself and every parent up to the space root. The parents are shared by many files, so most of those reloads are repeats: about 150,000 instead of 551 here.

A suggestion: remember the nodes reloaded during one walk, and stop walking up at the first parent that was already reloaded, since its own parents were reloaded with it. Single watch events, outside of a walk, would behave as now. I tried that on top of your branch, and it brought the same rescan down to 214 s (+14% instead of +39%, 3 rounds each). Vet and the posix tests pass with it. It's only a sketch; feel free to take it, change it, or solve it differently:

Patch (made on 1a17fcf, applies cleanly to 601916f)
diff --git a/pkg/storage/fs/posix/tree/assimilation.go b/pkg/storage/fs/posix/tree/assimilation.go
index d61670072..bcbc4fc47 100644
--- a/pkg/storage/fs/posix/tree/assimilation.go
+++ b/pkg/storage/fs/posix/tree/assimilation.go
@@ -498,7 +498,7 @@ func (t *Tree) assimilate(item scanItem) error {
 			return err
 		}
 		// another process can have assimilated the item. Reload the stale cache before the code below reads from it.
-		t.reloadStaleCache(assimilationNode, mtime)
+		t.reloadStaleCache(assimilationNode, mtime, item.reloaded)
 
 		previousPath, err := t.lookup.GetCachedID(context.Background(), spaceID, id)
 		if previousPath == "" || err != nil {
@@ -916,6 +916,7 @@ assimilate:
 // WarmupIDCache warms up the id cache
 func (t *Tree) WarmupIDCache(root string, assimilate, onlyDirty bool) error {
 	root = filepath.Clean(root)
+	reloaded := newReloadedNodes()
 	spaceID := ""
 
 	scopeSpace := func(spaceCandidate string) error {
@@ -1065,7 +1066,7 @@ func (t *Tree) WarmupIDCache(root string, assimilate, onlyDirty bool) error {
 				if isCopy || (assimilate && (isMove || isChanged || t.metadataIsStale(path))) {
 					// a copy with a clashing id, a move or a change on disk -> re-assimilate.
 					// assimilate skips items whose path and mtime still match the metadata
-					err := t.assimilate(scanItem{Path: path})
+					err := t.assimilate(scanItem{Path: path, reloaded: reloaded})
 					if err != nil && !errors.Is(err, _errSkipAlreadyKnown) {
 						t.log.Error().Err(err).Str("path", path).Msg("could not assimilate item")
 					}
@@ -1077,7 +1078,7 @@ func (t *Tree) WarmupIDCache(root string, assimilate, onlyDirty bool) error {
 				}
 			}
 		} else if assimilate {
-			if err := t.assimilate(scanItem{Path: path}); err != nil {
+			if err := t.assimilate(scanItem{Path: path, reloaded: reloaded}); err != nil {
 				t.log.Error().Err(err).Str("path", path).Msg("could not assimilate item")
 			}
 		}
@@ -1143,7 +1144,9 @@ func (t *Tree) metadataIsStale(path string) bool {
 // Another process, e.g. 'opencloud posixfs scan', can assimilate the item with its own cache.
 // That process also changes the tree size and tree time of the parents.
 // The caller must hold the lock of n.
-func (t *Tree) reloadStaleCache(n *assimilationNode, mtime time.Time) {
+// Within one walk, reloaded remembers the nodes reloaded already: the parents are shared by many
+// items, and a parent reloaded before had its own parents reloaded with it, so the walk up stops there.
+func (t *Tree) reloadStaleCache(n *assimilationNode, mtime time.Time, reloaded *reloadedNodes) {
 	backend := t.lookup.MetadataBackend()
 	if cached, ok := backend.GetCached(context.Background(), n, prefixes.MTimeAttr); ok {
 		if cachedMtime, err := time.Parse(time.RFC3339Nano, string(cached)); err == nil && cachedMtime.Equal(mtime) {
@@ -1154,6 +1157,9 @@ func (t *Tree) reloadStaleCache(n *assimilationNode, mtime time.Time) {
 	t.log.Debug().Str("path", n.path).Msg("metadata cache is missing or stale, reloading the item and its parents")
 	an := n
 	for {
+		if !reloaded.add(an.nodeId) && an != n {
+			return
+		}
 		if err := t.reloadCache(an); err != nil {
 			t.log.Warn().Err(err).Str("path", an.path).Msg("could not reload the metadata cache")
 		}
@@ -1217,3 +1223,27 @@ func (t *Tree) isDirty(path string) (bool, error) {
 	}
 	return string(dirtyAttr) == "true", nil
 }
+
+// reloadedNodes is the set of nodes whose metadata cache a walk reloaded already.
+type reloadedNodes struct {
+	mu  sync.Mutex
+	ids map[string]struct{}
+}
+
+func newReloadedNodes() *reloadedNodes {
+	return &reloadedNodes{ids: map[string]struct{}{}}
+}
+
+// add records id and reports whether it is new. A nil set (outside of a walk) never remembers anything.
+func (r *reloadedNodes) add(id string) bool {
+	if r == nil {
+		return true
+	}
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	if _, ok := r.ids[id]; ok {
+		return false
+	}
+	r.ids[id] = struct{}{}
+	return true
+}
diff --git a/pkg/storage/fs/posix/tree/tree.go b/pkg/storage/fs/posix/tree/tree.go
index 072c96a9b..44bc2e3cd 100644
--- a/pkg/storage/fs/posix/tree/tree.go
+++ b/pkg/storage/fs/posix/tree/tree.go
@@ -92,6 +92,8 @@ type scanItem struct {
 	Path          string
 	Recurse       bool
 	RefreshParent bool
+	// reloaded remembers the nodes whose metadata cache a walk reloaded already. Nil outside of a walk.
+	reloaded *reloadedNodes
 }
 
 // Tree manages a hierarchical tree

What remains is the reload of each changed item itself, which comes from treating a missing entry like a stale one. In a process with a cold cache, a missing entry is read from disk anyway, so in principle only a cached entry with a different mtime would need the reload. As far as I can tell, the reload also makes sure the entry is in the cache while the lock is held, so that a later read under the same lock doesn't hit a miss. So I'd leave that as it is for now.

I'll also rerun the stress test on the rebased branch and report back.

@pbleser-oc

pbleser-oc commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

As promised, the stress test on the rebased branch: opencloud main built against reva main (3acb80d) and against this PR (601916f), single binary, posix with the default memory metadata cache. Each run: 300 s, 32 WebDAV clients (k6) doing random PUT, GET, PROPFIND, MOVE, COPY, DELETE and MKCOL on 15 files in nested folders, plus opencloud posixfs scan in a separate process in a loop. "watch" adds watch_fs and writes to the files on disk.

requests median p95 max stuck on a file lock (end / 20 s after)
main, plain 25,182 352 ms 605 ms 1.1 s 0 / 0
PR, plain 25,451 352 ms 601 ms 1.1 s 1 / 0
main, watch 26,280 335 ms 574 ms 1.3 s 0 / 0
PR, watch 26,767 331 ms 565 ms 1.4 s 0 / 0

No hang, no panic, no file left in processing, and no difference in latency. On the earlier upload code, the same test left goroutines stuck in flock for minutes; on current main it doesn't any more, so this load doesn't hit the deadlock path often enough to show it. The backend-level reproducer still hangs on main, and TestUploadWithColdMetadataCache covers the upload path, so the fix is still needed.

About half of the requests got 425, or 500 for COPY (which reports the 425 of a file in processing as 500), on both builds alike: with this many overwrites, the files are almost always in postprocessing. One run each, so small differences are noise.

How to run it

Build opencloud against the reva commit to test (e.g. a go.work with the reva checkout), then, next to the two scripts below, for each variant:

mkdir run-pr && cp opencloud run-pr/
cat > run-pr/env.sh <<'ENV'
export OC_CONFIG_DIR=$PWD/run-pr/config OC_BASE_DATA_PATH=$PWD/run-pr/data
export OC_URL=https://localhost:9200 OC_INSECURE=true OC_LOG_LEVEL=warn
export STORAGE_USERS_DRIVER=posix PROXY_ENABLE_BASIC_AUTH=true
ENV
(. run-pr/env.sh && IDM_ADMIN_PASSWORD=admin run-pr/opencloud init --insecure true)
DURATION=300 WORKERS=32 ./stress.sh pr plain   # or watch; needs k6, and inotifywait for watch

The results, server log and goroutine dumps go to stress-<variant>-<mode>/; summary.txt has the numbers above.

stress.sh
#!/usr/bin/env bash
# Stress test for the posix metadata cache and node locks: concurrent
# WebDAV clients on a small set of paths, plus changes on disk and `posixfs scan` runs in a
# process of their own, against a single binary server with the posix driver and the default
# `memory` file metadata cache. Detects a hang (no completed request for HANG_AFTER seconds)
# and takes goroutine dumps (on a hang, and at the end of every run).
#
# The WebDAV clients run in k6 (stress-clients.js next to this script).
# Usage: stress.sh <variant> plain|watch   (env: DURATION=300 WORKERS=32 HANG_AFTER=60)
#   <variant>  a folder run-<variant> next to this script, with the opencloud binary, its
#              config from `opencloud init`, and an env.sh with the server settings
#   plain  watch_fs off: the scan writes metadata the server doesn't know about
#   watch  watch_fs on, plus a writer that changes files on disk
set -uo pipefail

S=$(cd "$(dirname "$0")" && pwd)
variant=$1 mode=$2
duration=${DURATION:-300} workers=${WORKERS:-32} hang_after=${HANG_AFTER:-60}
d=$S/run-$variant
out=$S/stress-$variant-$mode
. "$d/env.sh"
export STORAGE_USERS_DEBUG_PPROF=true
if [ "$mode" = watch ]; then
  export STORAGE_USERS_POSIX_WATCH_FS=true STORAGE_USERS_POSIX_WATCH_TYPE=inotifywait STORAGE_USERS_POSIX_SCAN_DEBOUNCE_DELAY=1s
fi
dav=https://localhost:9200/remote.php/dav/files/admin
pprof=http://127.0.0.1:9159/debug/pprof/goroutine?debug=2
server= pids=()

cleanup() {
  for p in "${pids[@]}"; do kill "$p" 2>/dev/null; done
  wait "${pids[@]}" 2>/dev/null
  pkill -f "k6 run .*stress-clients.js" 2>/dev/null
  [ -n "$server" ] && { kill "$server" 2>/dev/null; sleep 2; kill -9 "$server" 2>/dev/null; wait "$server" 2>/dev/null; }
  pkill -f "^inotifywait .*$OC_BASE_DATA_PATH" 2>/dev/null
}
trap cleanup EXIT

rm -rf "$out" "$OC_BASE_DATA_PATH"; mkdir -p "$out"
"$d/opencloud" server > "$out/server.log" 2>&1 &
server=$!
for _ in $(seq 1 120); do
  [ "$(curl -sk -o /dev/null -w '%{http_code}' -u admin:admin -X PROPFIND "$dav/" || true)" = 207 ] && break
  sleep 1
done

dirs=(s s/a s/a/b s/c)
for dir in "${dirs[@]}"; do curl -sk -u admin:admin -X MKCOL "$dav/$dir" -o /dev/null; done
for dir in s/a s/a/b s/c; do
  for i in 0 1 2 3 4; do
    printf 'initial %s %s\n' "$dir" "$i" > "$out/initial.txt"
    curl -sk -u admin:admin -T "$out/initial.txt" "$dav/$dir/f$i.txt" -o /dev/null
  done
done
space=$(ls -d "$OC_BASE_DATA_PATH"/storage/users/users/*/ | head -1); space=${space%/}

# the WebDAV clients: k6, one CSV line per metric sample (http_reqs = one per request)
BASE=$dav DURATION=${duration}s WORKERS=$workers OUT=$out/k6-summary.txt \
  k6 run -q --out csv="$out/k6.csv" "$S/stress-clients.js" > "$out/k6.log" 2>&1 & pids+=($!)
reqs() { [ -f "$out/k6.csv" ] && awk -F, '$1=="http_reqs"{n++} END{print n+0}' "$out/k6.csv" || echo 0; }

# another process writing metadata: `posixfs scan` of the space, again and again
(
  end=$((SECONDS + duration))
  while [ $SECONDS -lt $end ]; do
    start=$SECONDS
    timeout 120 "$d/opencloud" posixfs scan "$space" > /dev/null 2>&1; rc=$?
    echo "scan rc=$rc $((SECONDS - start))s" >> "$out/scan.log"
    sleep 3
  done
) & pids+=($!)

# with watch_fs: changes on disk, outside OpenCloud
if [ "$mode" = watch ]; then
  (
    end=$((SECONDS + duration))
    while [ $SECONDS -lt $end ]; do
      f=$space/${dirs[$((RANDOM % 3 + 1))]}/f$((RANDOM % 5)).txt
      [ -f "$f" ] && head -c $((RANDOM % 4096 + 1)) /dev/urandom > "$f" 2>/dev/null
      sleep 0.2
    done
  ) & pids+=($!)
fi

# watchdog: completed requests every 10 s; a hang is no completed request for hang_after s
hang=no last=-1 still=0 end=$((SECONDS + duration))
while [ $SECONDS -lt $end ]; do
  sleep 10
  n=$(reqs)
  echo "$SECONDS s: $n requests" >> "$out/progress.log"
  if [ "$n" -eq "$last" ]; then still=$((still + 10)); else still=0; fi
  last=$n
  if [ $still -ge "$hang_after" ]; then
    hang=yes
    curl -s -m 30 "$pprof" > "$out/goroutines-hang.txt"
    break
  fi
done
curl -s -m 30 "$pprof" > "$out/goroutines-end.txt"
for p in "${pids[@]}"; do kill "$p" 2>/dev/null; done
wait "${pids[@]}" 2>/dev/null
# no load anymore: a goroutine still waiting on a file lock now is stuck
sleep 20
curl -s -m 30 "$pprof" > "$out/goroutines-idle.txt"

# summary
{
  echo "### $variant $mode: ${duration}s, $workers clients, hang: $hang"
  cat "$out/k6-summary.txt" 2>/dev/null
  # status by operation; status 0 = timeout or failed connection
  awk -F, 'NR==1{for(i=1;i<=NF;i++)h[$i]=i; next} $1=="http_reqs"{c[$h["method"]" "$h["status"]]++} END{for(k in c) printf "  %s: %d\n", k, c[k]}' "$out/k6.csv" | sort
  echo "scans: $(wc -l < "$out/scan.log" 2>/dev/null || echo 0), failed: $(grep -vc 'rc=0' "$out/scan.log" 2>/dev/null)"
  for g in "$out"/goroutines-*.txt; do
    [ -s "$g" ] || continue
    echo "$(basename "$g"): $(grep -c '^goroutine ' "$g") goroutines, waiting on a file lock (flock/lockedfile): $(awk 'BEGIN{RS=""} /syscall\.Flock|lockedfile\.|filelock\./{n++} END{print n+0}' "$g")"
  done
  echo "panics/fatal in the server log: $(grep -ciE 'panic|fatal error|deadlock' "$out/server.log")"
} | tee "$out/summary.txt"
stress-clients.js (k6)
// WebDAV clients for stress.sh: random operations on a small set of shared paths.
// Env: BASE (WebDAV root of admin's files), DURATION (e.g. 300s), WORKERS (VUs), OUT (summary file)
import http from 'k6/http';
import encoding from 'k6/encoding';
import { randomBytes } from 'k6/crypto';

const base = __ENV.BASE;
const dirs = ['s/a', 's/a/b', 's/c'];
const auth = { Authorization: 'Basic ' + encoding.b64encode('admin:admin') };

export const options = {
  vus: Number(__ENV.WORKERS || 32),
  duration: __ENV.DURATION || '300s',
  insecureSkipTLSVerify: true,
  summaryTrendStats: ['med', 'p(95)', 'max'],
  // a stuck request shows as a timeout (status 0)
  thresholds: {},
};

const pick = (a) => a[Math.floor(Math.random() * a.length)];
const file = () => `${base}/${pick(dirs)}/f${Math.floor(Math.random() * 5)}.txt`;

export default function () {
  const r = Math.floor(Math.random() * 10);
  const p = { headers: Object.assign({}, auth), timeout: '60s', tags: {} };
  let op;
  if (r <= 2) {
    op = 'PUT';
    p.tags.op = op;
    http.put(file(), randomBytes(Math.floor(Math.random() * 4096) + 1), p);
  } else if (r === 3) {
    op = 'GET';
    p.tags.op = op;
    http.get(file(), p);
  } else if (r <= 5) {
    op = 'PROPFIND';
    p.tags.op = op;
    p.headers.Depth = '1';
    http.request('PROPFIND', `${base}/${pick(dirs)}/`, null, p);
  } else if (r === 6 || r === 7) {
    op = r === 6 ? 'MOVE' : 'COPY';
    p.tags.op = op;
    p.headers.Destination = file();
    p.headers.Overwrite = 'T';
    http.request(op, file(), null, p);
  } else if (r === 8) {
    op = 'DELETE';
    p.tags.op = op;
    http.del(file(), null, p);
  } else {
    op = 'MKCOL';
    p.tags.op = op;
    http.request('MKCOL', `${base}/${pick(dirs)}/d${Math.floor(Math.random() * 3)}`, null, p);
  }
}

export function handleSummary(data) {
  const m = data.metrics;
  const d = m.http_req_duration.values;
  const lines = [
    `requests: ${m.http_reqs.values.count}, failed (status >= 400 or none): ${m.http_req_failed.values.passes}`,
    `duration: med ${d.med.toFixed(0)} ms, p95 ${d['p(95)'].toFixed(0)} ms, max ${(d.max / 1000).toFixed(1)} s`,
  ];
  return { [__ENV.OUT]: lines.join('\n') + '\n', stdout: lines.join('\n') + '\n' };
}

@pbleser-oc

Copy link
Copy Markdown
Member

The CI run fails in the lint step, on the new branch in PrepareUpload, so the tests didn't run:

pkg/storage/pkg/decomposedfs/prepare_upload.go:148:2: ifElseChain: rewrite if-else to switch statement (gocritic)

With three branches now, gocritic wants a switch. The CI runs golangci-lint v2.10.1 through make lint. With this patch, make lint passes (0 issues):

Patch on top of 601916f
diff --git a/pkg/storage/pkg/decomposedfs/prepare_upload.go b/pkg/storage/pkg/decomposedfs/prepare_upload.go
index 8f2bd137a..6afa19fbd 100644
--- a/pkg/storage/pkg/decomposedfs/prepare_upload.go
+++ b/pkg/storage/pkg/decomposedfs/prepare_upload.go
@@ -145,7 +145,8 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
 		unlock metadata.UnlockFunc
 		old    *node.Node
 	)
-	if create {
+	switch {
+	case create:
 		// Before the node exists: an upload interrupted while its blob is written
 		// must not leave a node without metadata behind, which blocks the name.
 		if inline {
@@ -160,7 +161,7 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
 			return nil, err
 		}
 		purge = true
-	} else if info.NodeExisted {
+	case info.NodeExisted:
 		// read under the lock we take: an unlocked read of a cold cache entry waits for that lock
 		var unlockOld metadata.UnlockFunc
 		old, unlockOld, err = node.LockAndReadNode(ctx, fs.lu, n.SpaceID, n.ID, "", false, n.SpaceRoot, false)
@@ -172,7 +173,7 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
 			n.SetLockHeld(false)
 			return unlockOld()
 		}
-	} else {
+	default:
 		unlock, err = fs.lu.MetadataBackend().Lock(n)
 		if err != nil {
 			return nil, err

@NickWalters

Copy link
Copy Markdown
Author

Thanks Pascal. I pushed two commits:

  • d406fab takes your reload set as it is, with you as co-author. I left the reload on a missing entry unchanged.
  • 2338a5b applies your switch suggestions, so the lint step passes again.

The description now has Fixes #1006 and no longer has the outdated cost note. Thanks for the stress run.

NickWalters and others added 6 commits November 18, 2026 10:13
…a cache

Callers of LockAndReadNode read, change and write the metadata of the
node. With the 'memory' cache another process, e.g. 'opencloud posixfs
scan', can have changed the metadata on disk. The propagator then
started from the cached tree size and overwrote the one on disk.

Add InvalidateCache to the metadata backends and drop the cache entry of
the node after it is locked.

Part of opencloud-eu/opencloud#3804
…imilated

When 'opencloud posixfs scan' assimilates a changed file, it writes the
new mtime to disk first. The fs watcher of the server then skips the
item as already known and keeps the old size, checksums and etag in its
cache.

On that skip, compare the cached mtime with the one on disk. If they
differ, drop the cache entries of the item and of its parents up to the
space root.

Part of opencloud-eu/opencloud#3804
The scan can assimilate a change and the file can change again before
the server gets the event. The mtimes then differ, so the server takes
the update path. It used the previous blob size from the stale cache and
counted the change of the scan twice in the tree size of the parents.

Drop the stale cache of every known item before the skip check. Also
read the old tree size from disk in propagateSizeDiff, give
InvalidateCache a context and log its errors at warn level.

Part of opencloud-eu/opencloud#3804
Preserve shared cache entries and refresh cached ancestors when a child entry is missing. Read scan size deltas from disk without evicting metadata.

Use a lock-aware read for existing upload nodes to avoid self-deadlock on cache misses. Add regression coverage and an opt-in mixed stress test.
gocritic (ifElseChain) fails the lint step on the three-branch if-else.
A scan starts with an empty cache, so every item reloaded all its parents
up to the space root. Remember the reloaded nodes for the walk and stop
walking up at the first parent that was reloaded already.

Co-authored-by: Pascal Bleser <[email protected]>
@NickWalters
NickWalters force-pushed the fix/posix-scan-stale-cache branch from d406fab to af3eae7 Compare November 18, 2026 02:15
@NickWalters

Copy link
Copy Markdown
Author

@pbleser-oc, I rebased on main again because #1019 moved the module path to reva/v3. The only conflicts were in import blocks. I also changed the four files this PR adds to import reva/v3. Apart from that, the code is the same as d406fab, and its last CI run (1815) passed. Could you approve the CI run again?

@codacy-production

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 2 critical

Alerts:
⚠ 2 issues (≤ 0 issues of at least minor severity)

Results:
2 new issues

Category Results
Security 2 critical

View in Codacy

🟢 Metrics 121 complexity · 10 duplication

Metric Results
Complexity 121
Duplication 10

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

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

Projects

Status: Qualification

Development

Successfully merging this pull request may close these issues.

posix: an overwriting upload can deadlock on its own node lock after a metadata cache miss

2 participants