Skip to content

Reduce peak memory during native folder adoption - #2035

Merged
callumalpass merged 1 commit into
mainfrom
sprint-w9-daemon-10k-perf
Nov 28, 2026
Merged

callumalpass merged 1 commit into
mainfrom
sprint-w9-daemon-10k-perf

Conversation

@callumalpass

Copy link
Copy Markdown
Member

Change

The native adoption reader reserved 16 MiB plus one byte for every note in both passes that build the initial sync snapshot. The second pass retained all those buffers in the current bucket. Start with a 16 KiB read, grow the bound by 16 on a full read, and trim each accepted document before the bucket retains it. Even a file at the admission limit takes at most four reads.

Each read starts at offset zero on a confined regular file. A short read proves EOF on that handle. At the admission limit, the final request reads up to 16 MiB plus one byte to distinguish an exact fit from an oversized file. The existing digest check between inventory and sealing still detects changed contents. A regression test replaces the file between reads and checks exact-length and over-limit inputs.

Private adoption on 10,000 Markdown files

Measurements compare 9e58e4578 with its adoption patch before rebase (c2f89aee6). The PR reapplies the same adoption change to 6d9f7cc95 (head 60092dff8). Linux x86-64 on a Ryzen 9 7940HS. Each run created a fresh collection and a loopback memory log. The release-profile rehearsal enabled debug assertions only for the daemon test credential backend. The fixture held 12,262,780 bytes of Markdown and one 50,000-byte attachment. Both builds used the same four-CPU affinity, two Tokio workers and allocator instrumentation within each series. Filesystem caches were left warm. Each cell is the median of three alternating A/B pairs. The allocation counter sums requested bytes over the life of the adopter process. Peak RSS measures resident memory.

Adopter metric Baseline Candidate
ext4 time to confirm all 10,000 record IDs (s) 56.97 59.43
ext4 adopter peak RSS (MiB) 103.78 87.68
ext4 cumulative requested allocation (GiB) 315.37 3.23
tmpfs time to confirm all 10,000 record IDs (s) 8.16 6.23
tmpfs adopter peak RSS (MiB) 103.14 87.41
tmpfs cumulative requested allocation (GiB) 315.40 3.16

Individual ext4 confirmation times in seconds were A [78.46, 56.97, 32.80] and B [53.20, 59.43, 61.86]. Shared-disk load varied during the run. Linux wait4 supplied process peak RSS. A glibc interposer counted bytes requested through malloc, calloc and realloc, including repeated reservations. Each baseline made 20,000 requests of exactly 16 MiB plus one byte. Each candidate made zero.

Subsequent stages on tmpfs Baseline Candidate
Warm reopen through confirmed ID inventory (s) 0.39 0.40
256 edited notes through settle, including 10 s quiet window (s) 11.00 11.03
Warm and bulk process peak RSS (MiB) 48.39 48.20
Fresh Private replica through ID and byte verification (s) 11.45 8.66
Fresh replica process peak RSS (MiB) 130.29 131.12

The workload checked source bytes after adoption, all 256 confirmed revisions after the edit burst, an empty pending queue, all 10,000 original IDs, and a byte-identical second folder including the attachment. All six final tmpfs runs finished with zero holds and zero unresolved conflicts. The read change runs during adoption. The warm, bulk and second-replica rows describe adjacent behavior.

Read profile

The new rehearsal subcommand times the inventory pass and then holds each production-sized generation-zero bucket of documents while it reads that bucket. Nine alternating A/B pairs used a fixed plan for each corpus. The two-pass time is the median of the per-run sums. Sorting and sealing are outside these timers.

Corpus Inventory ms A → B Bucket ms A → B Two-pass ms A → B Largest bucket of returned string capacities A → B
10k fixture notes, ext4 88 → 93 167 → 105 253 → 196 5,653,922,129 → 428,618 B
10k notes with 12 KiB appended, tmpfs 126 → 129 223 → 135 336 → 264 570,425,378 → 460,910 B
10k notes with larger outliers, tmpfs 184 → 207 327 → 312 523 → 554 889,192,501 → 4,844,323 B

The mixed corpus put 900 files just over 16 KiB, 90 just over 256 KiB, and 10 just over 4 MiB. It exposes the extra reads at growth boundaries. The mixed two-pass median increased, even though bucket reservations fell.

A separate strace run of the authenticated headless daemon on 10,000 Markdown files measured a 13.97 s local-only first scan. The whole traced request path made 43,014 statx calls and 33,074 openat calls. In the traced Private workload, the warm watcher delivered 262 queued events in 24 batches and performed one debounced observation. Fresh-replica verification and materialization made 486,177 pwrite64 calls, 10,514 renameat2 calls and 1,110 fsync calls. Trace timings include instrumentation overhead. The numbers describe local synthetic workloads. Production startup and settle timings need a separate retest.

Five separately instrumented reads of both passes on the fixture spent a median 12.8 ms hashing the returned bytes with SHA-256. The whole traced local daemon spent 4.60 aggregate syscall seconds in futex across 687 calls. That aggregate includes ordinary sleeping threads and does not identify a contended lock.

Verification

  • 567 daemon and CLI tests passed with zero ignored on the identical runtime tree. Clippy passed for all daemon targets with warnings denied.
  • The final-head daemon E2E passed sign-in, folder registration, record read, create, update, sign-out and refusal after sign-out.
  • All path-selected pnpm ci:local steps passed except the initial pnpm test invocation. Two fake-CLI canary deadlines expired. All 331 root tests passed when run with --test-concurrency=1, and all 208 Desktop tests passed. One shared UI focus test timed out during the first recursive run. All remaining workspace package suites passed with --workspace-concurrency=1 and VITEST_MAX_WORKERS=2, including all 506 shared UI tests. These reruns used the original test deadlines and normal database-dependent skips.

Reproduction

Run from the PR root on Linux with glibc, Python 3, a C compiler and the pinned Rust toolchain. The commands build both measured variants from the original base and copy the PR's rehearsal into both. Place bench on ext4. Each adoption uses a new plan, collection, state directory and loopback log server. The focused comparison reuses a single plan within each corpus. Replace the CPU lists with available CPUs on your machine.

set -eu
bench=$(mktemp -d "$PWD/../adoption-bench.XXXXXX")
unset CARGO_TARGET_DIR
example=runtime/crates/daemon/examples/adopt_rehearsal.rs
source_file=runtime/crates/daemon/src/adopt.rs
for variant in A B; do
  tree="$bench/tree-$variant"
  git worktree add --detach "$tree" 9e58e4578
  cp "$example" "$tree/$example"
  if [ "$variant" = B ]; then cp "$source_file" "$tree/$source_file"; fi
  (cd "$tree/runtime" && cargo build --release --locked \
    --config 'profile.release.package.mdbn-daemon.debug-assertions=true' \
    -p mdbn-daemon --example adopt_rehearsal)
  cp "$tree/runtime/target/release/examples/adopt_rehearsal" "$bench/$variant"
done
(cd "$bench/tree-A/runtime" && cargo build --locked --release -p mdbn-log-server)
cp "$bench/tree-A/runtime/target/release/mdbn-log-server" "$bench/"

Save the two blocks below as $bench/alloc.c and $bench/run.py. Set W9_VOLUME to a new directory on each filesystem. For ext4 the driver stops after validating the initial adoption. On tmpfs it also edits 256 files, checks the confirmed revisions and verifies materialization.

Allocation counter and measurement driver
#define _GNU_SOURCE
#include <stdatomic.h>
#include <stdio.h>
#include <stddef.h>
extern void *__libc_malloc(size_t);
extern void *__libc_calloc(size_t,size_t);
extern void *__libc_realloc(void *,size_t);
static _Atomic unsigned long long total, cap, calls;
static void count(size_t n) {
 atomic_fetch_add_explicit(&total,n,memory_order_relaxed);
 atomic_fetch_add_explicit(&calls,1,memory_order_relaxed);
 if(n==16777217) atomic_fetch_add_explicit(&cap,1,memory_order_relaxed);
}
void *malloc(size_t n){count(n); return __libc_malloc(n);}
void *calloc(size_t n,size_t m){count(n*m); return __libc_calloc(n,m);}
void *realloc(void *p,size_t n){count(n); return __libc_realloc(p,n);}
__attribute__((destructor)) static void report(void){fprintf(stderr,"ALLOC bytes=%llu calls=%llu cap=%llu\n",atomic_load(&total),atomic_load(&calls),atomic_load(&cap));}
import os, pathlib, sys, subprocess as sp, tempfile, time, socket, json, re, hashlib, sqlite3
P=pathlib.Path
home=P(__file__).parent
label=sys.argv[1]
exe=home/label[0]
run=P(os.environ.get('W9_VOLUME',home))/label
run.mkdir()
baseenv=dict(os.environ,MDBASE_ENV='test',MDBASE_SECRET_BACKEND='insecure-test-file',TOKIO_WORKER_THREADS='2',RUST_LOG='mdbn_daemon::runtime=info')
def cmd(*args):
 return [str(exe),*args,'--dir',str(run)]
with socket.socket() as sock:
 sock.bind(('127.0.0.1',0))
 addr='127.0.0.1:'+str(sock.getsockname()[1])
log=sp.Popen([str(home/'mdbn-log-server'),'--listen',addr,'--testkit-cp','conformance','--insecure-test-keys'],env=baseenv,stderr=(run/'logsvc.log').open('w'))
def measure(phase,action,edit=False):
 logfile=run/(phase+'.log')
 with logfile.open('w') as out:
  proc=sp.Popen(cmd(*action),env=dict(baseenv,LD_PRELOAD=str(home/'alloc.so')),stdout=out,stderr=out)
  start=time.monotonic()
  result={}
  try:
   while True:
    pid,code,ru=os.wait4(proc.pid,os.WNOHANG)
    if pid:
     proc.returncode=os.waitstatus_to_exitcode(code)
     assert proc.returncode==0,(phase,logfile.read_text()[-2500:])
     result.update(wall=time.monotonic()-start,peak_kib=ru.ru_maxrss,cpu_user=ru.ru_utime,cpu_system=ru.ru_stime,voluntary=ru.ru_nvcsw,involuntary=ru.ru_nivcsw)
     break
    assert time.monotonic()-start<900,(phase,'timeout')
    if edit and 'ADOPTED ' in logfile.read_text() and 'bulk_start' not in result:
     result['bulk_start']=time.monotonic()-start
     before=json.loads((run/'before.json').read_text())
     blobs={}
     for path in sorted(before):
      if path.endswith('.md') and len(blobs)<256:
       data=(run/'a'/path).read_bytes()+b'\nBulk marker W9.\n'
       (run/'a'/path).write_bytes(data)
       blobs[path]=hashlib.sha256(data).digest()
       before[path]=blobs[path].hex()
     (run/'before.json').write_text(json.dumps(before))
     assert len(blobs)==256
    time.sleep(.1)
  finally:
   if proc.returncode is None:
    proc.kill(); proc.wait()
 out=logfile.read_text()
 for key in ('OPEN','ADOPTED','SETTLED'):
  m=re.search(r'^'+key+r' (\d+)ms',out,re.M)
  if m: result[key.lower()+'_ms']=int(m[1])
 for k,v in re.findall(r'(bytes|calls|cap)=(\d+)',out.split('ALLOC ')[-1]): result['alloc_'+k]=int(v)
 if edit:
  with sqlite3.connect('file:'+str(run/'a-state/index.sqlite')+'?mode=ro',uri=True) as db:
   rows=db.execute('select path_key,row from st_rec where path_key between ? and ?', (min(blobs),max(blobs))).fetchall()
   assert len(rows)==256 and all(blobs[p] in b for p,b in rows)
   assert db.execute('select count(*) from st_pending').fetchone()[0]==0
  result['bulk_with_quiet_s']=result['settled_ms']/1000-result['bulk_start']
 print(label,phase,result,flush=True)
 with (home/'results.jsonl').open('a') as f: f.write(json.dumps(dict(label=label,phase=phase,**result))+'\n')
def hashes():
 return {p.relative_to(run/'a').as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for d in ('notes','assets') for p in (run/'a'/d).glob('*') if p.is_file()}
try:
 for i in range(60):
  try:
   with socket.create_connection(tuple([addr.split(':')[0],int(addr.split(':')[1])]),.3): break
  except OSError: time.sleep(.1)
 sp.run(cmd('setup','--docs','10000','--log','http://'+addr),env=baseenv,check=True,timeout=120)
 measure('cold',['adopt','--exit-when-done'])
 assert hashes()==json.loads((run/'before.json').read_text())
 if os.getenv('W9_COLD_ONLY') != '1':
  measure('warm',['adopt','--exit-when-done'],True)
  measure('materialize',['verify'])
finally:
 log.terminate(); log.wait()
cc -O2 -shared -fPIC "$bench/alloc.c" -o "$bench/alloc.so"
ram=$(mktemp -d /dev/shm/adoption.XXXXXX)
mkdir "$bench/ext4"
for i in 1 2 3; do
  for variant in A B; do
    W9_VOLUME="$bench/ext4" W9_COLD_ONLY=1 taskset -c 12-15 \
      python3 "$bench/run.py" "$variant$i"
  done
done
for i in 1 2 3; do
  for variant in A B; do
    W9_VOLUME="$ram" taskset -c 8-11 python3 "$bench/run.py" "$variant$i"
  done
done

# Reuse the ext4 fixture for the focused reads. Prepare two tmpfs corpora.
python3 - "$bench/ext4/A1" "$ram" <<'PYTHON'
from pathlib import Path
import shutil, sys
src, ram = map(Path, sys.argv[1:])
for kind in ('large', 'mixed'):
    dest = ram / kind
    (dest / 'a/notes').mkdir(parents=True)
    shutil.copy(src / 'plan.json', dest)
    for i in range(10_000):
        name = f'a/notes/n{i:05}.md'
        if kind == 'large':
            data = (src / name).read_bytes() + b'x' * 12288
        else:
            n = (4194305 if i % 1000 == 0 else 262145 if i % 100 == 0
                 else 16385 if i % 10 == 0 else 800 + i % 2400)
            data = b'x' * n
        (dest / name).write_bytes(data)
PYTHON
for corpus in "$bench/ext4/A1" "$ram/large" "$ram/mixed"; do
  for i in $(seq 1 9); do
    for variant in A B; do
      TOKIO_WORKER_THREADS=2 LD_PRELOAD="$bench/alloc.so" \
        taskset -c 4-5 "$bench/$variant" read --dir "$corpus"
    done
  done
done

Refs #752 (introduced the bounded native adoption read).

@callumalpass
callumalpass added this pull request to the merge queue Nov 28, 2026
Merged via the queue into main with commit 48fd1d5 Nov 28, 2026
45 checks passed
@callumalpass
callumalpass deleted the sprint-w9-daemon-10k-perf branch November 28, 2026 12:44
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.

1 participant