Skip to content

perf: reuse indexed tar members for file reads - #2520

Open
apex-mochen wants to merge 1 commit into
fsspec:masterfrom
apex-mochen:perf/tar-reuse-indexed-member
Open

apex-mochen wants to merge 1 commit into
fsspec:masterfrom
apex-mochen:perf/tar-reuse-indexed-member

Conversation

@apex-mochen

Copy link
Copy Markdown
Contributor

TarFileSystem finds members in its index, then passes the original name to tarfile.extractfile(). The standard library resolves that name by scanning the member list backwards. On a scan of many small shards, this repeats work for every file and can make the name lookup quadratic.

Keep the already parsed TarInfo in the index in place of the unused data offset. Pass it to extractfile() when its name matches the previous lookup key. This still uses tarfile for extraction and link resolution. For unusual regular members with a trailing slash, preserve the previous string lookup, which strips that slash before resolving the name. Exact and normalized duplicate names retain last-entry behavior.

End-to-end measurement

Each timed run opens a local archive, discovers JSONL shards with fs.glob(), reads every matched shard through fs.cat_file(), and closes the archive. The fixtures store one synthetic record of roughly 450 bytes per member. Archive creation and output hashing are outside the timer. Windows, i9-14900HX, Python 3.12.14, base baeaac93e2688cd7bb67b35b75df6d335a42a62b, warmed OS cache, median of five measured runs after warm-up, alternating order.

Format Archive members Files read Before After
tar 1,024 128 17.64 ms 15.88 ms
tar 1,024 1,024 33.56 ms 20.87 ms
tar 8,192 128 145.81 ms 124.27 ms
tar 8,192 8,192 1089.30 ms 203.77 ms
tar.gz 8,192 8,192 1157.41 ms 214.63 ms

The 8,192-member full scans improved by about 81% in both formats. Paths, order and payload bytes matched across all runs. The single-partition case includes reading the entire catalog on each open. These are ordered local reads of small members. Large payloads and random seeks in compressed archives can spend a larger share of time in I/O and decompression.

Validation

TAR and shared archive suites reported 215 passed and 28 skipped. Coverage includes direct and cached reads, compression, links, path normalization, duplicate members, missing members, and negative offsets. Added cases for repeated raw names and the trailing-slash fallback. Ruff check, Ruff formatting and git diff --check passed.

Reproduce the end-to-end measurements

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 statistics
import subprocess
import tarfile
import tempfile
import time

from fsspec.implementations import tar as mod

BASE = 'baeaac93e2688cd7bb67b35b75df6d335a42a62b'
code = subprocess.check_output(['git','show',BASE+':fsspec/implementations/tar.py'],encoding='utf-8')
cls = next(n for n in ast.parse(code).body if isinstance(n,ast.ClassDef) and n.name=='TarFileSystem')
names = ('_index','_open')
ns = vars(mod).copy()
methods = [n for n in cls.body if isinstance(n,ast.FunctionDef) and n.name in names]
exec(compile(ast.Module(body=methods,type_ignores=[]),'<base>','exec'),ns)
fs_type=mod.TarFileSystem
variants=[{name:ns[name] for name in names},{name:getattr(fs_type,name) for name in names}]

if __name__ == '__main__':
    rows=[]
    with tempfile.TemporaryDirectory() as directory:
        for fmt, partitions in [('tar',8),('tar',64),('tar.gz',64)]:
            per_part=128
            archive=Path(directory)/f'data.{fmt}'
            payload_size=0
            with tarfile.open(archive,'w:gz' if fmt.endswith('gz') else 'w') as tar:
                for p in range(partitions):
                    for q in range(per_part):
                        name=f'corpus/p{p:03d}/shard-{q:03d}.jsonl'
                        payload=(json.dumps({'partition':p,'shard':q,'text':'data '*80})+'\n').encode()
                        info=tarfile.TarInfo(name)
                        info.size=len(payload)
                        tar.addfile(info,io.BytesIO(payload))
                        payload_size+=len(payload)
            selections=['single','full'] if fmt=='tar' else ['full']
            for selection in selections:
                samples=[[],[]]
                counts=set()
                digests=set()
                for i in range(6):
                    for j in (range(2) if i%2==0 else reversed(range(2))):
                        for name in names:
                            setattr(fs_type,name,variants[j][name])
                        start=time.perf_counter()
                        with closing(fs_type(str(archive))) as fs:
                            paths=fs.glob('corpus/p000/*.jsonl' if selection=='single' else 'corpus/*/*.jsonl')
                            payloads=[fs.cat_file(path) for path in paths]
                        elapsed=time.perf_counter()-start
                        hasher=hashlib.sha256()
                        for path,payload in zip(paths,payloads):
                            hasher.update(path.encode()+b'\0'+payload)
                        digests.add(hasher.hexdigest())
                        counts.add(len(payloads))
                        if i:
                            samples[j].append(elapsed)
                assert len(digests)==1
                expected=per_part if selection=='single' else per_part*partitions
                assert counts=={expected}
                row=dict(format=fmt,archive_members=per_part*partitions,selection=selection,files_read=expected,total=[statistics.median(x) for x in samples],samples=samples,sha256=digests.pop())
                rows.append(row)
                print(row,flush=True)

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