Skip to content

perf: match ZIP find paths by component prefix - #2519

Open
apex-mochen wants to merge 1 commit into
fsspec:masterfrom
apex-mochen:perf/zip-find-path-prefix
Open

apex-mochen wants to merge 1 commit into
fsspec:masterfrom
apex-mochen:perf/zip-find-path-prefix

Conversation

@apex-mochen

Copy link
Copy Markdown
Contributor

ZipFileSystem.find() splits every archive member path into components for every directory lookup. glob() uses this path when discovering shards, so repeatedly opening partitions in a wide archive pays for the same Python allocations again.

Compare already normalized member names using equality or a slash-delimited prefix. Normalize legacy backslash separators on demand and retain the original keys, detailed result order, depth rules and exact-file handling. This still scans the catalog and needs no secondary index.

End-to-end measurements

Each timed run opens a real local deflated ZIP, calls fs.glob() over the requested partition or partitions, opens and reads every matched JSONL shard with cat_file(), then closes the ZIP. The repeated case reuses one ZipFileSystem within the run. Each shard contains one synthetic JSONL record of roughly 0.5 KiB. Archive construction and output hashing are outside the timed span. Windows, Intel Core i9-14900HX, Python 3.12.14, baseline baeaac93e2688cd7bb67b35b75df6d335a42a62b, warmed OS cache, median of five measured runs after warm-up with alternating order.

Archive members Partitions requested Files read Before After
256 1 16 1.93 ms 1.61 ms
256 16 256 8.59 ms 6.16 ms
16,384 1 128 94.83 ms 91.25 ms
16,384 16 2,048 291.69 ms 138.89 ms

File paths, output order and bytes matched in every pair. The 16-partition read on the large archive improved about 52%. Initialization limited the improvement for one partition on the large archive. These figures are for local ZIPs with small shards.

Validation

  • ZIP, archive and mapping suites: 294 passed, 28 skipped.
  • A seeded differential check used 100 ZIP layouts and 4,800 detailed find calls, comparing values and insertion order against the original method with separator aliases, exact matches and depth limits.
  • Ruff check, Ruff formatting and git diff --check passed.
Reproduce the benchmark and differential checks

Run from the candidate checkout with fsspec importable.

import ast
from contextlib import closing
import hashlib
import io
import json
from pathlib import Path
import random
import statistics
import subprocess
import tempfile
import time
import zipfile

from fsspec.implementations.zip import ZipFileSystem

BASE = 'baeaac93e2688cd7bb67b35b75df6d335a42a62b'
code = subprocess.check_output(['git','show',BASE+':fsspec/implementations/zip.py'],encoding='utf-8')
cls = next(n for n in ast.parse(code).body if isinstance(n,ast.ClassDef) and n.name=='ZipFileSystem')
fn = next(n for n in cls.body if isinstance(n,ast.FunctionDef) and n.name=='find')
ns={}
exec(compile(ast.Module(body=[fn],type_ignores=[]),'<base>','exec'),ns)
versions=[ns[fn.name],ZipFileSystem.find]

if __name__ == '__main__':
    rng=random.Random(42)
    candidates=['a','a/','a/b','a/b/','a/b/c','./ab/c','/a//d','a/../x',r'a\b\z','a/bb/q','é/f','a//./b/k']
    for _ in range(100):
        b=io.BytesIO()
        with zipfile.ZipFile(b,'w') as z:
            for name in rng.sample(candidates,5):
                z.writestr(name,b'p')
        b.seek(0)
        with closing(ZipFileSystem(b)) as fs:
            for path in ('','a','a/b','a//b/',r'a\b','a/..','missing','é'):
                for depth in (None,1,2):
                    for withdirs in (False,True):
                        before,after=[f(fs,path,maxdepth=depth,withdirs=withdirs,detail=True) for f in versions]
                        assert list(before.items())==list(after.items())
    results=[]
    with tempfile.TemporaryDirectory() as directory:
        for partitions,shards in ((16,16),(128,128)):
            archive=Path(directory)/'shards.zip'
            with zipfile.ZipFile(archive,'w',zipfile.ZIP_DEFLATED) as z:
                for p in range(partitions):
                    for s in range(shards):
                        name=f'corpus/p{p:03d}/shard-{s:03d}.jsonl'
                        payload=json.dumps({'partition':p,'shard':s,'text':'sample document '*30})+'\n'
                        z.writestr(name,payload)
            for mode in ('single','repeated'):
                targets=([0] if mode=='single' else list(range(min(16,partitions))))
                samples=[[],[]]
                count=0
                digests=set()
                for run in range(6):
                    for j in (range(2) if run%2==0 else reversed(range(2))):
                        ZipFileSystem.find=versions[j]
                        start=time.perf_counter()
                        with closing(ZipFileSystem(archive)) as fs:
                            payloads=[]
                            for p in targets:
                                paths=fs.glob(f'corpus/p{p:03d}/*.jsonl')
                                assert len(paths)==shards
                                payloads.extend((path,fs.cat_file(path)) for path in paths)
                        elapsed=time.perf_counter()-start
                        assert len(payloads)==len(targets)*shards
                        count=len(payloads)
                        hasher=hashlib.sha256()
                        for path,payload in payloads:
                            hasher.update(path.encode('utf-8')+b'\0'+payload)
                        digests.add(hasher.hexdigest())
                        if run:
                            samples[j].append(elapsed)
                assert len(digests)==1
                row=dict(members=partitions*shards,mode=mode,partitions=len(targets),files_read=count,seconds=[statistics.median(x) for x in samples],samples=samples,sha256=digests.pop())
                print(row,flush=True)
                results.append(row)

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