Skip to content

posixfs: 'opencloud posixfs scan' leaves the server's in-memory metadata cache stale: wrong sizes, truncated downloads, wrong tree sizes #3804

Open

Description

@pbleser-oc

With the posix driver and the default in-memory file metadata cache (STORAGE_USERS_FILEMETADATA_CACHE_STORE=memory), running opencloud posixfs scan while the server is running leaves the server's cache stale for every file the scan updates. The server then:

  • reports the old size and checksums of files changed outside OpenCloud;
  • serves truncated downloads: Content-Length is the cached old size, but the bytes come from the real file;
  • keeps the old etag of the parent directories, so clients that compare etags from the top down don't find the change;
  • writes wrong tree sizes to disk: its next propagation starts from the cached tree size and overwrites the one the scan wrote. That persists after a restart and affects the quota.

It stays that way until the cache entry expires (24 h by default, STORAGE_USERS_FILEMETADATA_CACHE_TTL) or the server writes that node itself.

Running the scan while the server is stopped is not affected: the server starts with an empty cache and reads the scan's results from disk (scenario F below). But nothing tells admins to do that: neither opencloud posixfs scan --help nor the documentation of the command (Scanning resources on PosixFS, so far only in the docs for the next version) says whether the server may run during the scan. The documentation recommends the scan "during migrations, or when collaborative mode is disabled"; the posix page says that in non-collaborative mode the files must not be changed while OpenCloud is running, but in collaborative mode (watch_fs) they may, and that's where the cases in the watch_fs section below apply. And with the single binary, the scan can't run while the server is stopped: NATS runs inside the server, and the scan waits for it forever (see below). So in the default deployment, the scan always runs next to a running server.

With the server stopped, the scan waits for NATS forever

With the single binary stopped, opencloud posixfs scan never starts scanning (scenario E below): it connects to NATS first (event.NewStream in scanCmd), nothing listens on 127.0.0.1:9233, and it retries forever with an exponential backoff, logging one error per attempt:

{"level":"error","error":"error connecting to nats cluster opencloud-cluster: error connecting to nats at 127.0.0.1:9233 with tls enabled (false): nats: no servers available for connection",...,"message":"can't connect to nats (jetstream) server, retrying in 1m27.47239962s"}

It also ignores SIGTERM and SIGQUIT; only SIGKILL ended it (after 11 minutes in the test). It would help to fail after a few attempts, with a message that the scan needs NATS, i.e. a running server or a separate NATS.

Cause

opencloud posixfs scan (opencloud/pkg/command/posixfs.go, scanCmd) does not ask the running server to scan: it starts a posix driver of its own in its own process, with the same configuration. With the memory store, that driver has its own cache, and nothing tells the server's cache that the scan changed a node:

  • the scan re-assimilates files whose mtime on disk differs from user.oc.mtime (WarmupIDCache, pkg/storage/fs/posix/tree/assimilation.go, isChanged), and moved or renamed items: it writes their new size, blob ID, mtime and checksums, propagates the change to the parents, and writes the tree size of every directory it walks;
  • the server's metadata backend answers reads from its cache without checking the disk (HybridBackend.All and Get, pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go);
  • the propagator reads the parent's tree size through the same cache, even while holding the node's file lock (LockAndReadNode in pkg/storage/pkg/decomposedfs/tree/propagator/sync.go), and writes the stale size plus the difference back to disk;
  • the download takes Content-Length from the cached size and copies exactly that many bytes from the real file (pkg/rhttp/datatx/utils/download/download.go);
  • the file's own etag does change, because posix takes the mtime from os.Stat (pkg/storage/fs/posix/timemanager), while size and checksums come from the cache.

With a shared cache (nats-js-kv or redis-sentinel), the scan updates the shared entries while it holds each node's file lock, and all of the above is correct (see the control below).

watch_fs reduces it, but not completely

With STORAGE_USERS_POSIX_WATCH_FS=true, the server assimilates a change itself after scan_debounce_delay, refreshing its own cache, and a later scan finds nothing to do. But:

  • the scan can win the race: if it runs between the change and the server's own assimilation, the server's queued item finds the mtime already matching (assimilate re-reads it from disk and returns _errSkipAlreadyKnown) and skips the file without refreshing its cache: stale for up to 24 h (scenario C below);
  • changes the watcher doesn't see are exactly the ones admins run the scan for: changes on a network file system made from another host, lost inotify events (queue overflow, max_user_watches), changes without CLOSE_WRITE (truncate(2), mmap, touch -m);
  • the inotify watcher doesn't subscribe to ATTRIB, so the scan's metadata writes don't produce events in the server.

Reproduction

opencloud main (8acaef2), vendored reva 7983cec1cd3a, single binary, STORAGE_USERS_DRIVER=posix, PROXY_ENABLE_BASIC_AUTH=true, everything else default (in particular STORAGE_USERS_FILEMETADATA_CACHE_STORE=memory, watch_fs off). Fresh data directory for each scenario.

  1. Upload report.txt with the content C0-original (11 bytes) through WebDAV.
  2. PROPFIND report.txt and the space root, so that the server caches their metadata.
  3. Replace the file on disk, outside OpenCloud, with C1-changed-outside-opencloud (28 bytes, a newer mtime).
  4. Run opencloud posixfs scan <space root> with the same configuration.
  5. PROPFIND report.txt and the space root again, then GET report.txt.
  6. Upload other.txt (5 bytes) into the same space, and compare the space root's user.oc.treesize on disk with the files' sizes.
A: default (memory) B: nats-js-kv (control) C: memory, watch_fs, scan within the debounce delay D: memory, watch_fs, no scan (control)
xattrs on disk after step 4 blobsize=28, root treesize=28 same same same (by the server's watcher)
report.txt size, step 5 11 28 11 28
report.txt checksums, step 5 the old ones the new ones the old ones the new ones
report.txt etag, step 5 changed changed changed changed
space root etag, step 5 unchanged changed unchanged changed
GET report.txt Content-Length: 11, C1-changed- 28 bytes, complete Content-Length: 11, C1-changed- 28 bytes, complete
root treesize on disk after step 6 (files: 33) 16 33 16 33

Scenario C: STORAGE_USERS_POSIX_WATCH_FS=true, STORAGE_USERS_POSIX_SCAN_DEBOUNCE_DELAY=15s, the scan right after step 3, then 20 s of waiting before step 5, so that the server's own debounced assimilation has run.

With the server stopped between steps 2 and 5:

  • E: the server stopped, nothing else running: the scan hangs, waiting for NATS (see above). After killing it and starting the server again, all values are correct, because the server's own scan at startup (scan_fs) picks up the change.
  • F: the server stopped, only NATS running (opencloud nats server): the scan completes, and after starting the server again, all values are correct (28 bytes, new checksums, complete download, tree size 33).
The script used for the scenarios
#!/usr/bin/env bash
# Run one reproduction scenario against a fresh data directory.
#
# Usage: scenario.sh NAME [VAR=VALUE ...]
#   A: scenario.sh A
#   B: scenario.sh B STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv
#   C: scenario.sh C STORAGE_USERS_POSIX_WATCH_FS=true STORAGE_USERS_POSIX_SCAN_DEBOUNCE_DELAY=15s WAIT=20
#   D: scenario.sh D STORAGE_USERS_POSIX_WATCH_FS=true STORAGE_USERS_POSIX_SCAN_DEBOUNCE_DELAY=15s SCAN=no WAIT=20
#   E: scenario.sh E STOPPED=yes          (the scan hangs: stopped by a 120 s timeout, kill -9 if needed)
#   F: scenario.sh F STOPPED=yes NATS=yes
#
#   NAME          a label for the log file
#   VAR=VALUE     extra environment for both the server and the scan, e.g.
#                 STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv
#
# Scenario variables (not passed to opencloud):
#   SCAN=no       don't run `opencloud posixfs scan` (control)
#   WAIT=SECONDS  wait that long after the scan, e.g. for the watcher's debounce
#   STOPPED=yes   stop the server before changing the file, start it again after the scan
#   NATS=yes      with STOPPED=yes: run only NATS (`opencloud nats server`) while the server is stopped
set -euo pipefail

dir=$(cd "$(dirname "$0")" && pwd)
name=$1
shift
scan=yes
wait=0
stopped=no
nats=no
natspid=
for kv in "$@"; do
  case $kv in
    SCAN=*) scan=${kv#SCAN=} ;;
    WAIT=*) wait=${kv#WAIT=} ;;
    STOPPED=*) stopped=${kv#STOPPED=} ;;
    NATS=*) nats=${kv#NATS=} ;;
    *) export "${kv?}" ;;
  esac
done
# expects an `opencloud` binary next to this script, and a config from
# `opencloud init --insecure true --admin-password admin --config-path "$dir/config"`
export OC_CONFIG_DIR=$dir/config
export OC_BASE_DATA_PATH=$dir/data
export OC_URL=https://localhost:9200
export OC_INSECURE=true
export OC_LOG_LEVEL=warn
export STORAGE_USERS_DRIVER=posix
export PROXY_ENABLE_BASIC_AUTH=true

dav=https://localhost:9200/remote.php/dav/files/admin
auth=(-u admin:admin)

step() { printf '\n== %s\n' "$*"; }

propfind() {
  curl -sk "${auth[@]}" -X PROPFIND -H 'Depth: 0' "$dav/$1" \
    --data '<?xml version="1.0"?><d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"><d:prop><d:getcontentlength/><oc:size/><d:getetag/><oc:checksums/></d:prop></d:propfind>' |
    grep -oE '<d:getcontentlength>[^<]*|<oc:size>[^<]*|<d:getetag>[^<]*|<oc:checksum>[^<]*' |
    sed -E 's/<(d:getcontentlength|oc:size|d:getetag|oc:checksum)>/\1 /; s/^/    /' || true
}

upload() { # NAME CONTENT
  printf '%s' "$2" > "$dir/upload.txt"
  curl -sk "${auth[@]}" -T "$dir/upload.txt" "$dav/$1" -o /dev/null -w "  PUT $1 (${#2} bytes): HTTP %{http_code}\n"
}

xattr() { getfattr --only-values -n "user.oc.$1" "$2" 2>/dev/null || echo "-"; }

rm -rf "$OC_BASE_DATA_PATH"
log="$dir/server-$name.log"
server=
start_server() {
  "$dir/opencloud" server >> "$log" 2>&1 &
  server=$!
  for i in $(seq 1 120); do
    code=$(curl -sk -o /dev/null -w '%{http_code}' "${auth[@]}" -X PROPFIND "$dav/" || true)
    [[ $code == 207 ]] && break
    sleep 1
  done
  [[ $code == 207 ]] || { echo "server not ready (HTTP $code), see $log"; exit 1; }
}
stop_server() {
  kill "$server" 2>/dev/null || true
  wait "$server" 2>/dev/null || true
  server=
  pkill -f "^inotifywait .*$OC_BASE_DATA_PATH" 2>/dev/null || true # the watcher's child outlives the server
}
trap stop_server EXIT
: > "$log"
start_server
echo "### scenario $name: $* (server ready after ${i}s)"

step "1. upload report.txt through WebDAV"
upload report.txt 'C0-original'

step "2. PROPFIND report.txt and the space root: the server caches their metadata"
echo "  report.txt:"; propfind report.txt
echo "  space root:"; propfind ""

file=$(find "$OC_BASE_DATA_PATH/storage/users/users" -name report.txt -not -path '*/.oc-nodes/*')
space=$(dirname "$file")
if [[ $stopped == yes ]]; then
  step "2b. stop the server"
  stop_server
  curl -sk -o /dev/null -w '  WebDAV now: HTTP %{http_code}\n' "${auth[@]}" -X PROPFIND "$dav/" || echo "  WebDAV now: not reachable"
  if [[ $nats == yes ]]; then
    "$dir/opencloud" nats server >> "$log" 2>&1 &
    natspid=$!
    for i in $(seq 1 30); do
      (exec 3<>/dev/tcp/127.0.0.1/9233) 2>/dev/null && break
      sleep 1
    done
    echo "  started NATS alone (port 9233 open after ${i}s)"
  fi
fi
step "3. replace report.txt on disk, outside OpenCloud"
sleep 1.1 # a strictly newer mtime than the upload's (coarse timestamps)
printf 'C1-changed-outside-opencloud' > "$file"
echo "  on disk: $(stat -c %s "$file") bytes: $(cat "$file")"

if [[ $scan == yes ]]; then
  step "4. opencloud posixfs scan of the space, in its own process"
  start=$(date +%s)
  rc=0
  out=$(timeout 120 "$dir/opencloud" posixfs scan "$space" 2>&1) || rc=$?
  sed 's/^/  /' <<<"$out"
  echo "  (exit status $rc, $(( $(date +%s) - start ))s)"
else
  step "4. (no scan)"
fi
if [[ -n $natspid ]]; then
  kill "$natspid"; wait "$natspid" 2>/dev/null || true
  echo "  stopped NATS"
fi
if [[ $stopped == yes ]]; then
  step "4b. start the server again"
  start_server
  echo "  ready after ${i}s"
fi
if (( wait > 0 )); then
  echo "  waiting ${wait}s"
  sleep "$wait"
fi
echo "  on disk: report.txt blobsize=$(xattr blobsize "$file"), space root treesize=$(xattr treesize "$space") tmtime=$(xattr tmtime "$space")"

step "5. PROPFIND again"
echo "  report.txt:"; propfind report.txt
echo "  space root:"; propfind ""

step "6. GET report.txt"
curl -sk "${auth[@]}" "$dav/report.txt" -D "$dir/get.headers" -o "$dir/get.body" || true
echo "  $(grep -i '^content-length' "$dir/get.headers" | tr -d '\r'), body: $(cat "$dir/get.body") ($(stat -c %s "$dir/get.body") bytes)"

step "7. upload other.txt into the same space, then compare the space's tree size with the files on disk"
upload other.txt '12345'
sleep 2
actual=$(find "$space" -maxdepth 1 -type f -name '*.txt' -printf '%s\n' | paste -sd+ | bc)
echo "  on disk: space root treesize=$(xattr treesize "$space"), sum of the files: $actual"
echo "  space root:"; propfind ""

Possible fixes

Not mutually exclusive:

  1. Revalidate cache hits in the posix metadata backend: store the file's ctime with the cache entry and compare it with os.Stat on a hit. Every xattr write and every content change updates the ctime, whichever process makes it, and posix already calls os.Stat for the mtime. Caveat: two changes within the same coarse timestamp tick would not be told apart.
  2. Let the CLI scan through the running server (e.g. a request to storage-users) instead of starting a second driver, at least when one is running.
  3. Refresh the cache when assimilation skips an item (_errSkipAlreadyKnown): drop or reload the cache entry, so that the server heals in the watch_fs race above.
  4. Don't propagate from a cached tree size: read it from disk while holding the lock, so that a stale cache can't persist wrong sizes.
  5. Documentation and defaults: say in the documentation and in --help whether the server may run during the scan, and require a shared file metadata cache when it does, or make a shared cache the default for posix.
  6. Fail fast without NATS: stop retrying after a few attempts, with a message that the scan needs a running server or a separate NATS, and react to SIGTERM/SIGINT.

Related: opencloud-eu/reva#913 (the in-memory metadata cache has no size limit).

Activity

  1. pbleser-oc commented on Oct 25, 2026

    @pbleser-oc
    MemberAuthor

    A correction to the section "With the server stopped, the scan waits for NATS forever": it doesn't wait forever. reva's stream.Nats retries with a default exponential backoff, whose MaxElapsedTime is 15 minutes: in a second test, the scan gave up after 962 s (19 retries) with exit status 1 and Failed to create event stream for posix driver: error connecting to nats cluster opencloud-cluster: …. I had killed it after 11 minutes in the first test.

    It also ignores Ctrl+C (SIGINT), not only SIGTERM and SIGQUIT: the root command catches these signals with signal.NotifyContext, but the scan never looks at the context.

    Both are now tracked separately in #3805, so that this issue can stay about the stale cache.

  2. moved this from Qualification to Prio <= 3 in OpenCloud Team Boardon Oct 28, 2026
  3. NickWalters commented on Nov 2, 2026

    @NickWalters
    Contributor

    I opened opencloud-eu/reva#962 for proposed fixes 3 and 4. Propagation now reads the tree size from disk under the lock. When the watcher skips an item that the scan already assimilated, it now drops the stale cache. Scenario A (memory cache without watch_fs) is still open.

  4. added theissue type on Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions