#!/usr/bin/env python3 # /// script # requires-python = ">=3.10" # dependencies = ["duckdb>=1.4", "zstandard", "huggingface_hub>=2.0", "requests[socks]", "fsspec[http]", "py7zr", # "warcio", "boto3", "tqdm", "werkzeug", "pypdf[crypto]", "tenacity", "pyrate-limiter>=4.5"] # [tool.uv] # exclude-newer = "2026-11-14T00:00:00Z" # /// """Select rows of the Training Data Foundation's public index, download the files they point to and check them against their rows. One command, no setup (uv reads the dependencies from the block above; the copy a release publishes fixes them at that release, see Requirements): uv run https://huggingface.co/datasets/Battam/training-data-foundation/resolve/main/tools/fetch.py \\ --domain D3 --form spreadsheets --sample 3 --out ./data or, with Python 3.10 or newer: pip install the packages of the block above, then python fetch.py with the same options. The index is a set of Parquet tables (one row per downloadable item). The script first resolves the sources you name (by --source, --kind, --domain, --form or --tag) from meta/catalog.parquet, then reads only those sources' data files (with --limit or --sample, only as many of them as the units taken need, see --sample below) and only their rows of the tables under meta/, applies the default profile (below) and your own conditions, rebuilds each selected row into a full pointer with meta/sources.json, downloads the item and checks it against what the row records. Before downloading it prints how many units the selection had (with --limit or --sample, in the data files read) and how many each criterion of the profile removed; a selection that ends empty says which criterion emptied it. A source, kind, domain or form name that the catalog does not have stops the run with one line naming the closest names (exit code 2). Default profile (each criterion with its own option, which keeps what it leaves out; --all turns off all of them except the two benchmark criteria, benchmark and not compared, which only their own options turn off): duplicate a duplicate copy of another row of the selection: the same content or natural key, judged over the rows the other criteria keep --keep-duplicates benchmark matched a benchmark: a copy of benchmark data (meta/bench_overlap.parquet) or a row of a collection awaiting a ruling (meta/bench_checked.parquet, scope container); --allow-benchmark also keeps the next one --allow-benchmark not compared not compared with the benchmark list yet: the row's data file is not listed as compared in meta/bench_checked.parquet --allow-not-compared language the row records a natural language (source_meta.language or source_meta.labels.language, as an ISO 639 code) and it is not English or zxx (no linguistic content); rows that record none are kept --any-language size the recorded size is above 20 MB (20,000,000 bytes); rows of unknown size are kept and their download stops at 20 MB --any-size refused the release's fetch check read the row and its site refused it (meta/sizes.parquet: status needs_auth on an answer HTTP 401 or 403, or a git host asking for a login; or status size_mismatch of a body read empty or shorter than the row's recorded size); rows the check did not read are kept --allow-refused The fetch check reads every row of a source of at most 200 rows (#2698) and a sample of a larger source's rows, anonymously (#2674: release-2026-11-12.9 and .10 found one workbook of western-australia-government-workbooks answering 401, and a take that held it ended incomplete with exit code 1; #2698: on release-2026-11-12.11 the tutorial's take still ended so, on three rows of dataverse.no answering 403 and one workbook of scotland-government-workbooks coming back empty, none of them found so by the check). Every reading the release carries counts, whatever its day: a source is read again within about a week. The refused criterion leaves aside a source whose catalog column needs_auth marks a login or a payment (such as a requester-pays bucket): this script skips such rows itself, or fetches them with what they need. The training permit and the personal-data mark are labels every row carries (#2441): by default every row comes, whatever they say. Two more criteria leave such rows out, each only when its own option is given (with --all too): license the license does not let the files be shipped: the row's training tier must be yes and its redistribution tier yes or conditional (the rule of the catalog column license.ship) --training-only personal data the catalog's pii.level of the source is present or suspected, the row's sensitive column is set, or the row's pool fields mark it pseudonymous or identifiable --no-personal-data --any-license (or --any-licence) and --allow-personal-data, which kept these rows when the default profile left them out, are still accepted and change nothing. A unit is a group of files that the upstream publishes as one thing, delivered whole; its key is unit_id: for the rows that share a unit_group (source_meta.unit_group: a test case, one workbook, one package), that unit_group; for a row of its own, the row's natural key written as its uri, then @ when it is a byte range, then !/ when it is an archive member. unit_id is unique within a source. A row of a collection without a unit_group (the README.md and LICENSE the index writes for a source) is a file of the source, not of a unit: it comes with the first unit taken from that source (with --limit or --sample, when a data file read holds it). A unit is removed when any of its files fails a criterion. Each criterion is reported with its own count and reason (benchmark and not compared apart) and names what keeps what it removed: its option, or for license and personal data a run without the option that turned it on. --ext chooses units, not files: a unit is in the selection when one of its files has one of the extensions given, and it comes with all its files and its source's files. --unit UNIT_ID chooses one unit by its unit_id (as _meta/manifest.jsonl gives it), whole, with its source's files; with --source it names the same unit in every release that has it. The line that starts the fetch, printed before the first download, counts the units and files taken and their total size (the sizes their rows record; the files whose rows record none are counted apart). Output (--out DIR): DIR//// the files of one unit, one folder per unit (a single-file unit too); is the row's pool_domain when it has one (such as D3_data), else the top-level code of the source's first domain in meta/catalog.parquet (such as D3); is unit_folder(unit_id), a file-system-safe name that stays the same on every run (the last part of unit_id cleaned by werkzeug's secure_filename, a hyphen and the first 12 hex digits of the sha256 of unit_id); is the file's path within its unit: the part of its path (pool_path, else /) under the unit_group when the path lies under it, the file name for a single-file unit, else the whole path DIR/// the source's own files (README.md, LICENSE), at their pool_path DIR/_meta/manifest.jsonl one line per file on disk: source, path (relative to DIR), url, sha256, bytes, spdx, licence_url, publisher, retrieved, origin_kind, leaf, unit_id (null for a file of the source) and verified (true when the sha256 matched the one the index records, false when the index records none and it was computed) DIR/_meta/sizes.tsv one line per source, no header: leaf, source, origin, bytes, spdx DIR/_meta/fetch_manifest.jsonl one line per selected row and run, with its status, unit_id and the row's full pointer (pointer) (appended, never rewritten) DIR/_meta/fetch_run.json repository, commit, arguments, date and summary of the last run DIR/_meta/selection.json the selection file of the last run (see --selection below; #2337: with --inbox it goes there and not here) Running again into the same DIR keeps what is there: files already present with the right size and sha256 are not downloaded again, and manifest.jsonl and sizes.tsv are rewritten to cover every file of every run. Units stored inside another file: a row of a collection whose unit is a member of a container (a zip or tar archive) or is stored compressed or encoded points at that upstream file and lists in source_meta.transform the steps that make the unit (unzip:, untar:, gunzip, bunzip2, unxz, unxxd, uudecode, uncompress, gzip). The upstream file is downloaded and checked against the row, the unit is made out of it and checked against the unit's recorded hash (source_meta.unit_sha256, or content_sha256 when the last step is gzip), and only the unit is written, at the unit's place; its manifest line says extracted and keeps the upstream file's size and sha256 (upstream_bytes, upstream_sha256). A unit that does not match fails and the upstream file is kept as .stale. The steps run in transform.py, taken from next to this script or else from tools/ of the index at the commit read (or of the local --data copy). A unit marked expand (an archive meant to be used as a folder) is delivered as the archive; tools/to_pool.py unpacks it (python to_pool.py DIR --out ./pools --name ). --sample N takes at most N units per selected source (a source with fewer gives all it has), the same ones on every run, so a category can be tried within a few MB; --limit N takes N units over the whole selection (with --sample, N of the units --sample takes), from the selected sources in turn (#2144): the first unit of each source, then the second of each, and so on, the sources of one turn in the order of the sha256 of their names, so that a sample of a few hundred units spreads over the sources (when --limit took the first units of one order over the whole selection, a run over 39 sources read the files of 15 of them and took 115 of its 200 units from one). Both take each source's units in a fixed order of two stages (#2035): first the sha256 of the path of the data file that holds the unit (the path the catalog's column data_files names, such as data/npm/all/part-00060.parquet), then within that file the unit's key, the sha256 of its source and unit_group, or of its row's natural key (source, uri, range_offset, member_path). The run reads each source's data files in that order, whole files before their rows, a round of files at a time and only as far as these units need: --limit takes the sources' files in turn as well (the first file of each source, then the second of each, the sources of one turn in the same order), a round reading the next files of one turn, as many as units are still missing, until the files read hold N units that pass your conditions and the default profile (with --sample, each source counting up to its sample), and takes the N in turn from those; --sample alone reads the next file of each source that has fewer such units than its sample. So a file is read only when the units of the files before it were not enough (--kind corpus --limit 1 reads the first file of the source whose turn comes first, not the whole layer), and a source whose files hold no unit that passes is read one file a turn, as every other. The criteria are judged over the rows of the files read: a duplicate copy that only a file not read holds does not count, and a source's own files (README.md, LICENSE) come when a file read holds them. The run prints how many of the selection's data files it read and in how long. The same command at the same revision reads the same files and takes the same units. What is checked: a row with hashes has its size (when known) and every hash checked whose algorithm the script knows (crc32, md5, sha1, sha256, sha512, git_blob_sha1; a single-part S3 ETag, an md5, is compared where the row records one); a hash under any other name is not checked and is listed in the manifest field unchecked_hashes. Some sources publish no hash; such a row has its size checked when the size is known, and its manifest line says checked "size only" and carries the sha256 computed on download (unverified says so). A row with neither a hash nor a size is downloaded within the cap and only its sha256 is computed (manifest fields size_unknown and unverified). Rolling files (files the source regenerates in place, such as the lichess puzzle and evaluation databases, or a row whose source_meta has rolling set) carry no hash and their size changes between the index and the download: a size that differs is not a failure, the manifest line says checked "rolling file, size changed" with the size the row records in expected_bytes, and the download may grow up to the cap. A row that sets source_meta.rolling and also carries hashes is checked as usual, but a size or hash that differs is not a failure either: the manifest line keeps the bytes and sha256 actually downloaded, sets differs_from_index with the recorded values in expected_bytes and expected_sha256, and every such line carries the download date in retrieved. Rows built from a selection file (a collection tag campaign:) carry their place in a task pool in source_meta (pool_domain, pool_leaf, pool_path, unit_group, origin_kind, pool_fields and the others in CAMPAIGN_KEYS); the layout above follows them, and fetch_manifest.jsonl copies them as they are. Some of these rows point at small files kept in the index repository itself (uri campaign_files/...); such a uri is read from the same commit as the tables (or from the local --data copy), and the manifests record it as its absolute URL at that commit (https://huggingface.co/datasets//resolve//campaign_files/...; for a local copy, at --revision, else at main). Examples: python fetch.py --domain D3 --form spreadsheets --sample 3 --out ./data python fetch.py --source uk-government-workbooks --unit workbooks/ukgov-uk-community-renewal-fund-index-model.xlsx python fetch.py --source apache-arrow-testing --limit 10 python fetch.py --domain D1.6 --form test-suites --ext csv --limit 50 --out ./files python fetch.py --source pypi --tier yes --max-size 1000000 --limit 20 python fetch.py --tag campaign: --all --out ./collection python fetch.py --data ./local-copy --where "media_type = 'application/pdf'" --limit 5 python fetch.py --source govdocs1-files --ext pdf --limit 20 --check-content --out ./govdocs python fetch.py --revision --domain D1.6 --limit 50 python fetch.py --selection training-data-foundation-selection-.json --sample 3 --out ./data Domains and forms: meta/catalog.parquet gives every source a domain and a form. The domain is a list of codes: D1 to D10 are the subject areas and D. their leaves (D1.6 is a leaf of D1); multi marks content that spans many domains (such as a forum or a web archive) and unclassified a source not classified yet. The form is one id of lower-case words joined by "-" (such as test-suites or forums) and says what kind of material the source is. --domain CODE selects the sources with a domain entry equal to CODE or, for a top-level code, any of its leaves (D3 matches D3 and D3.5; D3.5 matches only D3.5); multi and unclassified match only themselves. --form ID selects the sources of that form. Both options can be repeated (a source matches any of the values given); given together, a source must match both, and with --source only the named sources that also match are read. When no source matches, nothing is selected and the run says so. A code, form or source name that no source of the catalog has is an error (exit code 2) naming the closest names. The domain codes and the forms are described in catalog/domains.yaml of the pipeline repository and in the README of the index. Revisions of the index older than these columns have no form column: --form then stops with an error and names that problem. --tag campaign: selects the rows of one collection (meta/tags.parquet, read only when --tag is given). A batch the index publishes under a new name (RENAMED_BATCHES) is selected by its old name too. --kind KIND selects the sources of one layer, those whose kind in meta/catalog.parquet is KIND (the values that column holds: material_set or corpus); it can be repeated (a source matches any of the values given) and is one more condition next to --domain and --form, so --kind material_set --domain D3 takes the material sets of D3. --selection FILE reads a selection file saved by the data page (Get the data): JSON with the ids of the sources ("sources"), the commit of the index ("revision") and the page's filters ("filters", a record only). Its sources are read as --source options and its revision as --revision, so the same file selects the same sources at the same commit later. A --revision given as well must name the same commit; a file that lists no source is an error. Every run writes such a file for its own selection, _meta/selection.json (#1909), in the same format (format training-data-foundation-selection/1, dataset, revision, filters, sources) with the sample count added: the sources the run read (sources), the commit it read (revision), the options of SELECTION_OPTIONS it was given that choose its rows (filters, by option name with _ for -: where, ext, tier, limit, the profile's switches as true and the others) and its --sample (sample, null without one). --selection reads its sources and revision as above; artpool admit takes the file as candidates of the material sets' admission and chooses the same rows again with --selection, the filters and the sample (selection_argv), and a file this script read as a byte range, a record, an API body or an archive member enters with the pointer of its line of _meta/fetch_manifest.jsonl. #2337: --inbox DEST writes that file into DEST in place of _meta/selection.json: DEST is a folder given as an rclone path (remote:path), and the file goes there by rclone rcat as selection-.json, so a file written there is never written over. DEST is meant to be a line's folder pool_ of the inbox the index's admission takes its candidates from; rclone must be on PATH, signed in to DEST by its own environment (such as the managed identity of the machine it runs on). The summary gives the path written under inbox. #2643: --for NAME records NAME in that file as for: whom the selection is made for, such as the task family whose plan reads the material sets admission promotes its rows into (06_tasks/orchestration/definitions.py writes a family's selections of corpus rows so). It chooses no row; a file written without it has no such key. The repository gets new commits every day. Reading the index from the Hub (the default, hf://datasets/...) reads every table at one commit (hf://datasets/@/...), so a long query is not split across an update. --revision names that commit, so the same command selects the same rows later; a tag or branch name is also accepted and is resolved to its commit through the Hub API (with --print-sql it is pinned as given). Without it the script reads the release it was published in (RELEASE, the release tag written into tools/fetch.py when the index is published), so a command names the release once, in the script's URL; a copy with no release written (run from the code repository) asks the Hub API for the commit the main branch points to now. Either way it prints the commit on stderr and writes it into every manifest line, the summary and fetch_run.json (field revision). If the current commit cannot be read, the script prints one warning line and reads the main branch (revision is then empty). A --data root that already names a revision (@...) is read as given; --revision cannot be combined with it. With a local --data copy (or a URL prefix that is not hf://datasets/...) --revision only records which commit that copy holds: the value is written as given into the manifest lines, the summary and fetch_run.json, and are not checked against the Hub. Requirements: Python 3.10 or newer and the packages of the block above: duckdb reads the index (#2177: 1.4 or newer, whose own HTTP log counts the requests it sends, hub_requests), huggingface_hub resolves the index commit and the hf:// addresses, requests (with urllib3 and PySocks) downloads, fsspec reads archives on a server by byte ranges, py7zr reads 7z archives, warcio reads WARC and ARC records, boto3 signs requester-pays S3 requests, zstandard serves --decompress of .zst, tqdm shows the progress line and the sizes, tenacity tries a git clone or an rsync fetch again after a failure of the moment, pyrate-limiter paces sec.gov and Docker Hub's registry, and pypdf reads PDFs for --check-content (its crypto extra, cryptography, decrypts the AES-encrypted ones that open without a password, as a PDF viewer opens them). The copy published with a release (#2144) adds to the block a tool.uv table with exclude-newer, the start (00:00 UTC) of the day its release tag names: uv run then takes every package at the versions uploaded before that release, the same on every run of it, also with --no-config. pip does not read the table; uv pip install --exclude-newer with that time installs the same versions. #2337: --inbox needs rclone on PATH. Standard tool: downloads by requests (retries by urllib3 Retry, SOCKS by requests[socks]); seekable remote files by fsspec's HTTPFile and huggingface_hub's HfFileSystem; archives by zipfile, tarfile and py7zr; WARC and ARC records by warcio; requester-pays S3 GETs by boto3; anonymous registry tokens by the Bearer challenge werkzeug's WWWAuthenticate parses; git repositories by the local git (clone --mirror, show-ref) and rsync:// files by the local rsync, each tried again after a failure of the moment by tenacity; the pace of sec.gov and Docker Hub's registry by pyrate-limiter; the scanned-PDF check's fonts and text by pypdf, AES-encrypted PDFs decrypted by cryptography (pypdf's crypto extra); the progress line and short sizes by tqdm (format_sizeof); the terminal check by isatty; unit folder names by werkzeug's secure_filename; the units of --limit and --sample by whole data files before their rows, in a fixed hash order so that the sample repeats (a block sample, as DuckDB's system sampling takes whole vectors: https://duckdb.org/docs/2.0/sql/query_syntax/samples.html), each file read by DuckDB (read_units), and the turns of --limit by DuckDB (row_number() over each source's units, pick_steps); the dependencies of a release's copy fixed at that release by uv's exclude-newer in the inline script metadata (https://docs.astral.sh/uv/guides/scripts/, selecting.fetch_tool_text); #2337: the selection file written to a remote folder (--inbox) by rclone rcat (https://rclone.org/commands/rclone_rcat/). none for the fallback over a row's addresses (_fetch_one) and the run's package cache (download_package) (searched: https://tenacity.readthedocs.io/en/latest/, https://pypi.org/project/backoff/, https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html, https://www.fatiando.org/pooch/latest/, https://filesystem-spec.readthedocs.io/en/latest/features.html): the retries of one request are urllib3 Retry's; tenacity and backoff retry one call, not the next address of a list; pooch and fsspec's cache cannot use this script's requests session (SOCKS proxy, User-Agent, requester-pays signing) nor stop at the size cap. What is read: meta/catalog.parquet (one row per source) first; then, for the sources it resolves, exactly the data files its column data_files names for them (with --tag, only the files its column batch_files names for the batches that carry the tags, and of those only their rows), one read per file and no listing of data/, keeping each source's rows by their column source (a file may hold rows of several sources; a revision whose catalog has no column data_files, older than it, is not read: older_catalog), and only their rows of meta/batches.parquet, meta/bench_overlap.parquet and meta/bench_checked.parquet (these tables are sorted by source, so a filtered read over HTTP touches few of their row groups), their readings of meta/sizes.parquet that found a row refused (#2674: the refused criterion; that table is sorted by source too), and meta/sources.json. meta/tags.parquet is read only with --tag. Those reads run in parallel; a selection whose sources hold at most LOCAL_ROWS rows by the catalog is copied into memory once, a larger one is read in place. With --limit or --sample the data files are read a round at a time and only as far as the units need (--sample above): a small selection copies each round into memory, a larger one reads each round in place and then again only the files that hold the rows taken. Memory: DuckDB may use at most --memory-limit (default: the smaller of 4GB and a quarter of the machine's memory) and writes what does not fit into a spill directory, --temp-dir or else a folder .fetch_spill under --out that is removed at the end. Spill files are capped at 100GB by default; DUCKDB_MAX_TEMP changes that limit. DuckDB runs one thread per GB of the memory limit (at least one, at most the number of CPUs; --threads sets it). The rows are first picked with only the columns the conditions read, then copied whole to the spill directory and sorted in parts of at most a quarter of the limit each, so a selection larger than the limit spills to disk instead of failing. Raise --memory-limit when a large selection runs slowly because it spills. Ways of fetching that the script supports (the unit column of meta/sources.json says which one a source uses): whole files over HTTP(S) (s3:// and hf:// addresses are turned into their public HTTPS form); byte ranges (HTTP Range, the server must answer 206); WARC or ARC records (the range is one gzip member: warcio reads it, the WARC and HTTP headers are removed and the payload hash is checked); members of zip archives (zipfile reads the central directory and the member over a seekable file of HTTP byte ranges, then checks size and CRC32); API responses (the body field is taken from the JSON response). Members of packages: wheels, jars and other zip files the same way; sdists, npm .tgz and .crate files by downloading the whole package (within the cap; kept in a temporary directory for the run) and taking the member out; members of 7z archives by py7zr over the same seekable file (a solid block is decoded from its start up to the member, within the cap). A server that answers a byte-range request with the whole file fails the row. Members of tar archives stored as gzip (the arXiv source bundles): the range is one gzip member, decompressed and checked against the CRC32 and length of its trailer. Single lichess games (rows with a game id): the public export API; rows without a game id are fetched as the files they point to. One deflate-compressed member of a zip at a byte range (hash_scope zip_member_deflate): the compressed segment by HTTP Range, inflated in memory and checked against the member's size and CRC32. API responses: the body field is the dotted path source_meta.api_body_field names, $ for the whole answer as it came, base64-decoded where source_meta.api_body_decode says so, after a prefix the API puts before its JSON (source_meta.api_body_prefix, such as Gerrit's )]}') is taken off. Pages with parts that differ on every request (hash_scope html_region): the whole page is written and the stable region source_meta.html_region names is checked. Image manifests of a container registry (hash_scope registry_manifest): the manifest is fetched by its digest and its sha256 checked (size_bytes is the sum of its layers, which are not fetched). Registries that answer anonymous pulls with a token (a 401 with a Bearer challenge; access.auth oci_anonymous_token, and every registry manifest): a token for the repository is got from the challenge's realm, with no credentials, and the address is asked again with it; a Basic challenge (a login) fails the row. Whole git repositories (uri git+https://): the local git clones the repository (--mirror, within the cap) and the grokmirror fingerprint of its refs is checked against source_meta.fingerprint; the repository is written as a folder. rsync:// addresses: the local rsync fetches the file. A file the source stores gzip-compressed (source_meta.content_encoding gzip) is asked for with Accept-Encoding gzip and kept compressed, as its hashes cover it; a file a row without hashes records as gzip is decompressed once after the download and fails when it is not whole gzip. sec.gov asks every client to declare who it is: its rows need --contact, are paced at one request a second, and after an answer 401, 403 or 429 the run sends sec.gov nothing more; Docker Hub's registry is paced the same way, and after a 401, 403 or 429 to a manifest the run asks it for no more. data.humdata.org answers 202 for a file it has not got ready: such a row fails this time. The duplicate criterion has no table: it is resolved here, over your own selection (with --limit or --sample, over the rows of the data files read), after every other criterion (DuckDB window functions over the rows the others keep, so the copy kept is one you get). A snapshot holds one row per natural key (source, uri, range_offset, member_path); a revision written before that may hold more, and of those only the newest version is kept, by collection time: the latest batch, then the latest part file of the batch (part files are numbered in the order they are written; such a revision wrote a corrected row into a new part file while its old version stayed), and its manifest line says natural_key_conflict; the older versions leave the selection, so they do not remove their unit; rows of a superseded snapshot are removed; of rows with the same sha256, sha1 or md5 (md5 with the same size) one copy is kept, the first by the source's registry order, then source, batch and place. A selection of one source keeps its rows whose copy is in another source. The benchmark criterion: rows found in public benchmark tasks (meta/bench_overlap.parquet, hit classes benchmark_copy, task_file and data_address, by row or by whole collection) and rows of collections awaiting a ruling are removed as matched a benchmark; rows whose data file is not listed in meta/bench_checked.parquet as compared are removed apart, as not compared with the benchmark list yet (--allow-not-compared keeps them; every published data file is compared at every release, so a file not listed belongs to an older revision of the index, or the release has not compared it yet). Truncated rows and empty files stay in. Sizes and caps: a cap applies only when fetching, it never removes a row from the selection. By default every row has the overall cap (meta/size_caps.json: the 99th percentile of the sizes of all benchmark task files), and under the profile also at most 20 MB; --max-size N uses N bytes for every row instead. To leave large rows out of the selection, the size criterion does it at 20 MB and --max-size-filter N at N bytes (rows of unknown size stay for both). A row whose known size is above its cap is not downloaded; a row of unknown size (manifest field size_unknown) is downloaded until the cap. Both are recorded with status too_large, which is not a failure. --decompress also decompresses .gz, .bz2 and .zst files within the cap. A downloaded file that turns out to be a Git LFS pointer (a small text file naming the real object) is refused as failed. Requester-pays buckets (such as the arXiv source bundles on S3) are charged to your own AWS account: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (and AWS_SESSION_TOKEN for temporary credentials). boto3 signs those requests (get_object with RequestPayer requester); the script contains no credentials. Without them such rows are skipped with the reason. Rows that need a login, a form or an access request (field access.needs_auth of the full pointer, for example guestbook, restricted, gated or kaggle_token) are skipped: no request is sent, the manifest line has status skipped, the reason and the needs_auth value. Rows their source marks as deleted upstream (access.gone_upstream) are skipped the same way. Embargoed rows are skipped until the date in access.embargo_until and fetched from that day on. Requester-pays rows are fetched when the AWS credentials above are set. The summary printed at the end counts the skipped rows by value (needs_auth_skipped). Any other address form is reported as unsupported. Content check (--check-content): after a verified download (and after --decompress) each file gets three checks, recorded in the manifest field content_check. scanned_pdf: a PDF whose first five pages set text in no font and hold fewer than 20 characters of text per page (both read by pypdf), most likely a scanned image. error_page: an HTML, XML or plain text file whose title names an error (404, not found, access denied and the like), or whose text is under 3000 characters and names one in its first 1500 characters. ext_mismatch: the type that file --mime-type reports is not one of the types expected for the extension. Each check is flagged, clean, not_applicable or skipped; a check is skipped when what it needs (the file command, or the pypdf package of the block above) is not installed or fails on the file, and the reason is written in content_check.skipped. A flagged or skipped check is not a failure and never changes the status. Connection errors, HTTP 429 and 5xx answers are retried by urllib3 (3 more tries, waiting 2, 4 and 8 seconds, or as long as a Retry-After header asks). A whole file whose body is cut in transfer, a git clone or an rsync fetch that fails for the moment is tried again on the same address by tenacity, as often and as long (the file resumed from its .part). A download whose size or hash does not match its row fails; the next address of the row is then tried. Pages that block scripts (#2144): a server that answers a download with an HTML page (Content-Type text/html or application/xhtml+xml) where the row records its file as not HTML (by its ext, or its media_type; the extensions of pages a server makes, such as php, count as HTML), the page's bytes failing the row's check, blocks scripts such as this one: a bot check or a sign-in page stands where the file was (on 2026-11-09 dataverse.nl answered every file of dataversenl-workbooks-cc0 with a bot check of 2,289 bytes, title "Oh noes!"). Such a row fails, with the row's check in reason as for any other; its manifest line adds html_page (the page's content type and title), its per-file line says that the upstream blocks scripts, and the end of the run names each such source on stderr with how many of its files came back as a page, as does the summary (blocked). Such files can be downloaded in a web browser from the url of their manifest lines. Where files go: every file is written under --out, in the layout above. The domain, source, collection and path parts are cleaned the same way; a row whose path would still land outside --out is not written and gets status unsafe_path (the run goes on). file:// addresses are not fetched; to use a local copy pass --data. Downloads, decompression of responses, WARC and gzip members, archives and 7z blocks all stop at the cap. AWS signatures are sent only to S3, by boto3. Running again with the same --out: a file already there whose size and sha256 match its row is recorded ok without downloading it (already_present); a partly downloaded file (.part) is resumed with a Range request and started over when the server answers with the whole file. _meta/fetch_manifest.jsonl is appended to, never overwritten; each line carries run_id (the start time of its run), and the summary names this run's run_id with the DuckDB query that lists its lines that are not ok. A line records the size and sha256 the row expects (expected_size, expected_sha256) and, on failure, what was downloaded (got_bytes, got_sha256); a file that was already at the destination of a failed row is renamed to .stale (stale_path). The files of a unit are fetched together (they share its place in the fetch order). A unit some of whose files are not fetched is named on the line incomplete at the end of the run; the files fetched are kept. Local reuse: with --local-root DIR (repeatable; or the ARTPOOL_LOCAL_ROOTS variable, directories separated by ':') and --staging DIR (or ARTPOOL_STAGING, where a file fetched elsewhere was placed), a whole file whose size and every published hash match its row is copied from there with no request; the manifest line records obtained: reused or staged and local_path, and every other row obtained: fetched. A local file of the same name or size whose hashes do not match is never used and is reported on stderr. The run ends with the line "local reuse: N reused, N staged, N fetched, N refused" on stderr and local_reuse in the summary. No request is made for a reused or staged file, so its line keeps the provenance of the original fetch of the same sha256: retrieved (the day the bytes were obtained from upstream), fetched_from, fetched_at, route and provenance_record (where it was read). A reused file takes the earliest dated record among the fetch manifests (fetch_manifest.jsonl: retrieved, else the date of run_id) and pool manifests (_meta/manifest.jsonl) under the local roots; a staged file takes the line of staging_attempts.jsonl that the staging step (artpool.stage_receive) wrote when it streamed the file in. With no such record retrieved is "unknown" and retrieved_reason says why; it is never the date of this run, which is recorded apart as reused_at (UTC, YYYY-MM-DDTHH:MM:SSZ). Network: --proxy URL (or the HTTPS_PROXY, HTTP_PROXY and ALL_PROXY variables) sends every request through a proxy (socks5:// and socks5h:// through requests' PySocks). The DuckDB read of the index uses the same HTTP proxy; DuckDB cannot use a SOCKS proxy, so with one read a local copy of the index (--data). Archive members read by byte ranges go through fsspec, which has no SOCKS client: with a SOCKS proxy such rows fail with the reason. --contact TEXT adds your contact (an email or URL) to the User-Agent, as some APIs ask. Progress on stderr (--quiet turns it off): while the index is read and the selection planned, tqdm progress lines (the tables read of the total, then the planning steps done of the total, or with --limit or --sample the data files read of the selection's, with the time elapsed, redrawn every second on a terminal and every minute in a log, so a read that waits on a rate limit is not silent); before the first download, one line per selected source with what the run takes of it (#1525, #2144): its units, their files, the source's own files (README.md, LICENSE, its companion files) and the size their rows record, then the line that starts the fetch with the total (printed with --quiet too); while fetching, on a terminal, one tqdm progress line, then one line per file (status, source, path and size in short units such as 1.7 kB) sorted by source and path; otherwise one such line per file as each finishes, so a log keeps its timing. Before fetching, a run also names each selected source some or all of whose sampled rows read did not fetch, with its fetch check (the catalog column fetch_check: how many of its sampled rows read fetched and matched their record, and the day read): its upstream may not serve the files now (such bytes fail the row's check and are not kept). A source at level needs auth (#2597: its rows need a paying or signed-in reader, and the check, which reads anonymously, read none) is not named: this script skips such rows with the reason, unless it has what they need (see Requester-pays buckets above). Only the readings of the release read count (#2144): those of the day its tag names or later (the tag of --revision, else RELEASE, the tag of the release this copy was published in; with neither, no reading counts). An older reading says nothing of what the upstream serves for this release and is left out: release-2026-11-09.2 named two sources from readings five days old, whose files fetched, and not the one whose upstream had started to block scripts since. The run ends on stdout with its summary. On a terminal it is a few lines in words: how many files were fetched and checked, their total size, where they were written and that the details are in _meta/fetch_run.json; the files of units and the source's own files by status; this run's run_id with its counts by status; and, when some line is not ok, the DuckDB query that lists those lines of _meta/fetch_manifest.jsonl. With --json, or when stdout is not a terminal (a pipe, a file, an agent's tool call), it is one JSON object (also the field summary of fetch_run.json) with the same: counts, files (by unit and source, then status), run_id and not_ok_query, blocked ({source: {files, title}}, the sources whose upstream answered files with an HTML page), and (#2177) requests: the requests the run sent to the Hub ({resolver, api, other}, the classes Hugging Face counts them under: resolver a file's bytes by its /resolve/ URL, api its API), which a run reading the Hub also prints on stderr. Hugging Face token: the index tables are read from the Hub with the token in HF_TOKEN (a DuckDB huggingface secret; it overrides a token stored on the machine). Without it they are read anonymously, and the run says so once at the start: Hugging Face allows an anonymous address fewer requests per 5 minutes than a signed-in user, and once they are used up it answers 429 and each read waits and retries (HTTP_SETTINGS). A read token is made at https://huggingface.co/settings/tokens. The manifest status is one of ok, failed, too_large, skipped, unsafe_path, unsupported. The exit code is 1 when some row failed or had an unsafe path, and 2 when the index could not be read or a source, domain or form name is not in the catalog (the message says why). Deletes: .part of a download (fetch_file), on an error that cannot resume, past the size cap or failing the row's check: a temporary file fetch_file wrote; the download is fetched again from the row's url. Deletes: the package directory fetch-packages-* (tempfile.mkdtemp, download_package) and its files, one per package url named by the first 24 hex digits of the url's sha256, at the end of the run, on a failed download or when the package cache passes its cap: temporary files download_package wrote; a package is fetched again from its url. Deletes: .part of a decompression (decompress_file): a temporary file decompress_file wrote. Deletes: .unit of extract_unit, when the unit cannot be made or does not match the index: a temporary file extract_unit wrote with the transform steps. Deletes: the compressed file of a row fetched with status ok, once decompress_file has written its decompressed file: recomputable, downloaded again from the row's url by fetch_unit, which checks it against the row. Deletes: .part of a local reuse copy whose bytes changed while copied (LocalFiles.take): a temporary file take wrote, copied from the local file. Deletes: a download that is a Git LFS pointer file (fetch_one): recomputable, downloaded again from the row's url. Deletes: the spill directory .fetch_spill under --out at the end of the run (not a --temp-dir one): DuckDB's temporary files of this run. Deletes: .part/ of a git row (fetch_git): one an earlier clone left, before cloning again, and one past its cap, whose clone failed, whose refs could not be read or whose fingerprint differs: temporary files, the folder fetch_git cloned into before renaming it onto ; the repository is cloned again from the row's url. Deletes: the folder fetch-rsync-* of an rsync:// fetch (rsync_opener, tempfile.TemporaryDirectory), once the file rsync wrote in it is open: temporary files rsync_opener made. """ from __future__ import annotations import argparse import base64 import binascii import bz2 import copy import csv import datetime import functools import gzip import hashlib import http.client import io import json import logging import os import posixpath import re import shutil import subprocess import sys import tarfile import tempfile import threading import time import urllib.error import urllib.parse import urllib.request import zlib import zipfile from pathlib import Path import requests import urllib3 from pyrate_limiter import Limiter, Rate from requests.adapters import HTTPAdapter from tenacity import Retrying, retry_if_exception, stop_after_attempt, wait_exponential from urllib3.util import Retry from warcio.archiveiterator import ArchiveIterator from warcio.bufferedreaders import ChunkedDataReader from werkzeug.datastructures import WWWAuthenticate from werkzeug.http import parse_content_range_header from werkzeug.utils import secure_filename DEFAULT_REPO = "Battam/training-data-foundation" # #2403: the dataset's name before its rename, which the Hub keeps as a redirect; a command or a selection file written # before the rename names it (--repo, and the selection file's dataset that artpool admit hands on as --repo), and the # run reads it as DEFAULT_REPO (current_repo) OLD_REPO = "Battam/agentic-env-index" # #2397: batches the index publishes under another name than the one they were collected under, {the name collected # under: the name published}: the two batches of collection A, whose name promised answers the index no longer holds # (#1633). The release writes the published name into the batch, collection and campaign of their rows and tables # (artpool.removal_record.renamed, 03_data_line/steps/_publish.py published_values); a --tag campaign: given with # either name selects the batch under both (tag_names), so a command written with the old name reads a release that # publishes the new one, and the other way round. RENAMED_BATCHES = {"2026-10-a-spreadsheets-with-answers": "2026-10-a-spreadsheets", "2026-10-a-spreadsheets-with-answers-2": "2026-10-a-spreadsheets-2"} # the release tag this copy was published in, the default --revision; the projection writes it into tools/fetch.py # (selecting.fetch_tool_text), and a copy with none written reads the main branch RELEASE = "release-2026-11-14.22" # #2144: a release tag (artpool.release_tag.TAG_RE), release-.: the day of the release, from which on a # fetch check reading is the release's own (release_day, fetch_note) RELEASE_TAG_RE = re.compile(r"release-(\d{4}-\d{2}-\d{2})\.[1-9][0-9]*") TIERS = ("yes", "conditional", "no", "unknown") # hit classes of meta/bench_overlap.parquet that the default filter removes OVERLAP_REMOVE = ("benchmark_copy", "task_file", "data_address") # meta/catalog.parquet: one row per source with its domain codes (list) and its form (--domain, --form) CATALOG = "meta/catalog.parquet" # the catalog column that names, for each source, the repository paths of the data files that hold its rows; the rows # are read from exactly those files, so no request lists the folders of data/ (Hugging Face counts every listing and # every file read against an address's requests per 5 minutes) DATA_FILES = "data_files" # the folder of the repository that holds the data files (the catalog's column data_files names them under it); a # data file's name in the tables is its path under it (row_file) DATA_DIR = "data/" # the catalog column that names, for each batch of a source, the data files that hold its rows ([{batch, file}]): with # --tag only the files of the tagged batches are read BATCH_FILES = "batch_files" # #2006: the catalog column of the fetch check (#1577: level, rows, fetched, read_at; catalog_table), and its name in # release-2026-11-09.1, fetch, a reserved word of DuckDB's parser, read quoted until a release with fetch_check is # published FETCH_CHECK, FETCH_CHECK_OLD = "fetch_check", "fetch" # a revision whose catalog has no column data_files (older than #1746) names none of its data files, so it is not read: # the message (older_catalog) asks for a newer revision # a domain code (D or D.) or one of the formal values, and a form id (lower-case words joined by "-") DOMAIN_RE = re.compile(r"D[1-9][0-9]*(?:\.[1-9][0-9]*)?|multi|unclassified") FORM_RE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") HASH_COLS = (("sha256", 32), ("sha1", 20), ("md5", 16), ("crc32", 4)) LICENSE_COLS = (("license_spdx", "spdx"), ("license_training_ok", "training_ok"), ("license_redistribution_ok", "redistribution_ok"), ("license_notes", "notes")) ZIP_COLS = (("local_header_offset", "zip_local_header_offset"), ("compression_method", "zip_compression_method"), ("compressed_size", "zip_compressed_size")) TRUNC_KEY = "content_truncated" API_BODY_DEFAULT_FIELD = "items.0.body" # the default User-Agent is built only from these three; tests compare the whole string against them TOOL_NAME = "training-data-foundation-fetch" TOOL_VERSION = "1" DATASET_URL = f"https://huggingface.co/datasets/{DEFAULT_REPO}" UA = f"{TOOL_NAME}/{TOOL_VERSION} (+{DATASET_URL})" CHUNK = 1 << 20 UNKNOWN_SIZE_CAP = 100_000_000 # used only when a row carries no cap (a table without max_size_bytes) RETRIES = 3 BACKOFF = 2.0 # DuckDB memory: the smaller of this and a quarter of the machine's memory, unless --memory-limit says otherwise MEMORY_CAP = 4 << 30 # DuckDB threads: one per this much of the memory limit (a sort or join needs room per thread; with less, a query # over a large selection fails with an out-of-memory error instead of spilling) THREAD_MEMORY = 1 << 30 # the share of the memory limit one sorted part of the selection may take (see part_queries) PART_SHARE = 0.25 SPILL_DIR = ".fetch_spill" # DuckDB settings used when the tables are read over the network (hf:// or another URL). Hugging Face counts # requests in 5-minute windows and answers 429 when a window is used up; DuckDB reads one file with several # requests, and a full query touches thousands of files. Retries wait 2, 4, 8, ... 256 seconds (510 seconds # in all), so the last retry comes after a whole window has passed; each request may take up to 120 seconds; # fewer threads keep fewer requests in flight. These values are provisional: lower them if your reads never # hit a limit, raise them if they still do. HTTP_SETTINGS = {"http_retries": 8, "http_retry_wait_ms": 2000, "http_retry_backoff": 2, "http_timeout": 120} REMOTE_THREADS = 4 # #2177: the host whose requests Hugging Face counts per 5 minutes, by class (hub_class); a run counts those it sent # (hub_requests): DuckDB's in its own HTTP log, which connect enables for a remote read, and those of huggingface_hub's # client and of the download session in HUB_SENT, by their libraries' hooks (main, make_session) HUB_HOST = "huggingface.co" HUB_SENT = {"resolver": 0, "api": 0, "other": 0} # the longest a read of the index waits through its retries (510 seconds with HTTP_SETTINGS) RETRY_SECONDS = round(sum(HTTP_SETTINGS["http_retry_wait_ms"] / 1000 * HTTP_SETTINGS["http_retry_backoff"] ** i for i in range(HTTP_SETTINGS["http_retries"]))) # huggingface.co/docs/hub/rate-limits: an anonymous address gets fewer requests per 5 minutes than a signed-in user, # and passing HF_TOKEN is the easy fix; HF_TOKEN overrides a token stored on the machine (connect reads only it) ANONYMOUS = ("note: HF_TOKEN is not set, so the index is read anonymously; Hugging Face allows an anonymous address " "fewer requests per 5 minutes than a signed-in user, and once they are used up it answers 429 and each " f"read waits and retries (up to {RETRY_SECONDS} seconds a request). To read with your account, create a " "read token at https://huggingface.co/settings/tokens and set it in the environment (export " "HF_TOKEN=hf_... in a POSIX shell, $env:HF_TOKEN = 'hf_...' in PowerShell)") HELP_ENV = ("environment:\n" " HF_TOKEN a Hugging Face access token; the index tables are read with it (a DuckDB huggingface\n" " secret), so Hugging Face allows more requests per 5 minutes than to an anonymous address,\n" " which runs into HTTP 429 sooner (each read then waits and retries). It overrides a token\n" " stored on the machine. Without it the run says once that it reads anonymously. To set it,\n" " create a read token at https://huggingface.co/settings/tokens, then\n" " export HF_TOKEN=hf_... (PowerShell: $env:HF_TOKEN = 'hf_...')") # writer side (#268): the tables under meta/ that a reader filters by source (batches, bench_overlap, bench_checked, # tags) are written sorted by source in row groups of this many rows, so that a filtered read over # HTTP touches only the row groups of the sources it reads META_ROW_GROUP = 32_768 MANIFEST = "fetch_manifest.jsonl" # what was read and with which arguments (to_pool.py copies it into _meta/delivery.json, local paths as # placeholders) RUN_FILE = "fetch_run.json" # #1909: the selection file of the run, in the format of the data page's selection file (Get the data) with the sample # count; filters records the options of SELECTION_OPTIONS the run was given (selection_filters), which choose its rows SELECTION_JSON = "selection.json" SELECTION_FORMAT = "training-data-foundation-selection/1" # #2403: a selection file written before the rename has the format agentic-env-selection/1, read as this one SELECTION_FORMATS = (SELECTION_FORMAT, "agentic-env-selection/1") SELECTION_OPTIONS = ("domain", "form", "kind", "tag", "ext", "unit", "tier", "min_size", "max_size_filter", "where", "limit", "all", "keep_duplicates", "allow_benchmark", "allow_not_compared", "training_only", "any_language", "no_personal_data", "any_size", "allow_refused") SIZE_ONLY = "size only" ROLLING_CHANGED = "rolling file, size changed" NO_HASH_MEMBER = "the source publishes no hash for this member; sha256 computed on download" # files the source regenerates in place, so the size in the index goes stale (source, collection); a row can # also say so itself with source_meta.rolling ROLLING_FILES = frozenset({("lichess", "puzzle"), ("lichess", "eval")}) # fields of source_meta copied into the manifest line as they are (rows built from a selection file) CAMPAIGN_KEYS = ("campaign", "pool_domain", "pool_leaf", "pool_path", "pool_source", "pool_order", "unit_group", "origin_kind", "agency", "derived_from", "rolling", "transform", "upstream_sha256", "upstream_bytes", "unit_sha256", "unit_bytes", "content_sha256", "pool_fields", "original_name", "generated_by", "expand", "expand_rule") # a uri without a scheme that starts here names a file in the index repository, at the commit the tables are read at REPO_FILES = "campaign_files/" # ---------- SQL ---------- def sql_str(s: str) -> str: return "'" + str(s).replace("'", "''") + "'" IS_ROW = "starts_with(coalesce(p.extra, ''), '{\"_row\":')" def _absent(key: str) -> str: return f"coalesce(json_contains(json_extract(p.extra, '$._absent'), '\"{key}\"'), false)" def tier_sql(field: str = "training_ok") -> str: """License tier of a row: the row's own license_override when it has one, otherwise the batch tier.""" anycol = "(" + " OR ".join(f"p.{c} IS NOT NULL" for c, _ in LICENSE_COLS) + ")" own = (f"CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.license_override.{field}') " f"WHEN json_type(p.extra, '$.license_override') IS NOT NULL " f"THEN json_extract_string(p.extra, '$.license_override.{field}') " f"WHEN {anycol} THEN p.license_{field} " f"WHEN NOT {_absent('license_override')} THEN b.const_{field} END") v = f"coalesce(nullif({own}, ''), b.{field})" return f"(CASE WHEN {v} IN ('yes', 'conditional', 'no') THEN {v} ELSE 'unknown' END)" def truncated_sql() -> str: """Why the stored content was cut short (NULL when it was not).""" own = (f"CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.source_meta.{TRUNC_KEY}') " f"WHEN json_type(p.extra, '$.source_meta') IS NOT NULL " f"THEN json_extract_string(p.extra, '$.source_meta.{TRUNC_KEY}') " f"WHEN NOT {_absent('source_meta')} THEN b.const_truncated END") return f"nullif(coalesce(p.truncated, {own}), '')" def own_sql(key: str, const: str, *, text: bool = True) -> str: """A top-level field of the full pointer: the row's own value (in extra) when it has one, otherwise the source constant (a column of the batch table), unless the row lacks the field.""" f = "json_extract_string" if text else "json_extract" return (f"(CASE WHEN {IS_ROW} THEN {f}(p.extra, '$._row.{key}') " f"WHEN json_type(p.extra, '$.{key}') IS NOT NULL THEN {f}(p.extra, '$.{key}') " f"WHEN NOT {_absent(key)} THEN {const} END)") def source_meta_sql(key: str) -> str: """One key of source_meta; key is an SQL expression (a quoted name or a column such as b.meta_key).""" return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.source_meta.' || {key}) " f"WHEN json_type(p.extra, '$.source_meta') IS NOT NULL " f"THEN json_extract_string(p.extra, '$.source_meta.' || {key}) " f"WHEN NOT {_absent('source_meta')} THEN json_extract_string(b.const_source_meta, '$.' || {key}) END)") def meta_value_sql() -> str: """The source_meta value that some tags depend on (forum instance, mailing list, site), see b.meta_key.""" return f"(CASE WHEN b.meta_key IS NOT NULL THEN {source_meta_sql('b.meta_key')} END)" def own_content_sql() -> str: """The row's own content categories as JSON text (NULL when the row takes them from its batch).""" return f"CAST({own_sql('content', 'b.const_content', text=False)} AS VARCHAR)" def hash_scope_sql() -> str: """What the hashes cover: file (default), http_payload (a WARC record's payload) or api_body.""" return f"coalesce({own_sql('hash_scope', 'b.const_hash_scope')}, 'file')" def hash_sql(alg: str) -> str: """One hash of the row as lowercase hex (NULL when the row has none).""" hx = f"coalesce(json_contains(json_extract(p.extra, '$._hx'), '\"{alg}\"'), false)" return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.hashes.{alg}') " f"WHEN json_type(p.extra, '$.hashes.{alg}') IS NOT NULL THEN json_extract_string(p.extra, '$.hashes.{alg}') " f"WHEN {hx} THEN NULL ELSE lower(hex(p.{alg})) END)") def uri_sql() -> str: """The pointer's uri before the address swap (the uri column holds the directly downloadable address).""" t, f, s = "b.uri_swap_to", "b.uri_swap_from", "b.uri_swap_suffix" return (f"(CASE WHEN {t} IS NOT NULL AND json_extract_string(p.extra, '$._uri_orig') IS NULL THEN " f"CASE WHEN starts_with(p.uri, {t}) AND ends_with(p.uri, {s}) AND length(p.uri) >= length({t}) + length({s}) " f"THEN {f} || substr(p.uri, length({t}) + 1, length(p.uri) - length({t}) - length({s})) END " f"ELSE p.uri END)") def pid_sql() -> str: """pointer_id as written in meta/sources.json (layout.pointer_id), as one SQL expression.""" par = "p.parent_pointer_id" rest = f"substr({par}, strpos({par}, ':') + strpos(substr({par}, strpos({par}, ':') + 1), ':') + 1)" head = "p.source || ':' || p.collection || ':'" tail = (f"array_to_string(list_slice(string_split({uri_sql()}, '/'), -b.pid_segments, -1), '/') || " f"CASE WHEN b.pid_at_offset THEN '@' || CAST(p.range_offset AS VARCHAR) ELSE '' END") return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.pointer_id') " f"WHEN {_absent('pointer_id')} THEN NULL " f"WHEN json_type(p.extra, '$.pointer_id') IS NOT NULL THEN json_extract_string(p.extra, '$.pointer_id') " f"WHEN json_type(p.extra, '$.pid') IS NOT NULL THEN {head} || json_extract_string(p.extra, '$.pid') " f"WHEN {par} IS NOT NULL AND p.member_path IS NOT NULL THEN " f"CASE WHEN length({par}) - length(replace({par}, ':', '')) >= 2 " f"THEN {head} || {rest} || '!/' || p.member_path END " f"WHEN b.pid_segments IS NOT NULL THEN {head} || {tail} END)") def size_bucket_sql(col: str = "p.size_bytes") -> str: return (f"(CASE WHEN {col} IS NULL OR {col} < 0 THEN 'unknown' WHEN {col} < 10000 THEN '<10KB' " f"WHEN {col} < 1000000 THEN '10KB-1MB' WHEN {col} < 100000000 THEN '1MB-100MB' " f"WHEN {col} < 1000000000 THEN '100MB-1GB' ELSE '>1GB' END)") def same_key(a: str, b: str = "p") -> str: return (f"{a}.source = {b}.source AND {a}.uri = {b}.uri AND {a}.range_offset IS NOT DISTINCT FROM {b}.range_offset " f"AND {a}.member_path IS NOT DISTINCT FROM {b}.member_path") def row_file(rel: str) -> str: """#2286: row_file, the name of the data file at the repository path rel (as the catalog's column data_files names it): its path under data/ (DATA_DIR), such as npm/all/part-00060.parquet, _bucket/000/rows-00000.parquet, or sec-edgar-filings/rows-00000.parquet for a source laid out as a few large files (#1746). The one definition of the name: every writer of a table that carries row_file (meta/bench_checked.parquet) names a file by it, and every reader that joins on it reads it from the file's full path by row_file_sql.""" return rel[len(DATA_DIR):] def row_file_sql(root: str, path: str) -> str: """row_file in SQL: the name of the data file at path, an SQL expression for its full path under root (root/data/..., as source_files and files_sql give it; DuckDB's column filename holds a path as it was given), is what follows root/data/, with / between its parts.""" return f"replace(substr({path}, length({sql_str(root + '/' + DATA_DIR)}) + 1), '\\', '/')" def rows_from(root: str, files: str) -> str: """SELECT over the row tables files (an SQL list of their full paths under root) that adds where each row sits: row_file (the data file's path under data/, row_file_sql) and row_index (the row number in that file, from 0). The duplicate criterion orders rows by them as the last keys; reading them costs nothing extra.""" return (f"SELECT * EXCLUDE (filename, file_row_number), {row_file_sql(root, 'filename')} AS row_file, " "file_row_number AS row_index " f"FROM read_parquet({files}, union_by_name = true, filename = true, file_row_number = true)") # ---------- duplicates, resolved at read time ---------- # The duplicate criterion runs over the reader's own selection: the rows that pass every other criterion, with # DuckDB window functions (dup_sql), so the copy kept is one the reader gets. A row is a duplicate for the first of # DUP_REASONS that holds: # natural_key another row has the same natural key (source, uri, range_offset, member_path) and was collected # later: of one natural key the newest version is kept, ordered by collection time, newest first: not # superseded, then the latest batch, then the latest part file of the batch (part-.parquet are # numbered in the order they are written), then the last row # of the file (that row has natural_key_conflict true). #1300: a snapshot holds one row per key, so # this finds rows only in a revision written before that, where a corrected row went into a new part # file and its old version stayed; a selection pinned to such a revision still gets one version # superseded the row belongs to a snapshot that a newer batch of the same unit replaces (SUPERSEDE: the # source_meta key that names the unit; newer by batch_date_sql, then "revised", then batch name) # same_sha256, same_sha1, same_md5 # another row with the same hash and hash scope (md5 also the same size_bytes) comes first in keep # order: rows the first two reasons leave, then the source's registry order (registry_order of # meta/batches.parquet), then source, batch, uri, range_offset, member_path, row_file, row_index DUP_REASONS = ("natural_key", "superseded", "same_sha256", "same_sha1", "same_md5") DUP_HASHES = (("sha256", 64), ("sha1", 40), ("md5", 32)) NATURAL_KEY = ("source", "uri", "range_offset", "member_path") # source -> the source_meta key that names the unit of a snapshot; of one unit only the newest batch is kept SUPERSEDE = {"stackexchange-dump": "site"} # the row's own columns the windows read (besides DUP_INPUTS) DUP_ROW_COLS = ("source", "batch", "uri", "range_offset", "member_path", "row_file", "row_index", "size_bytes") DUP_INPUTS = ("dup_scope",) + tuple(f"dup_{a}" for a, _ in DUP_HASHES) + ("dup_unit", "dup_ord", "dup_date", "dup_sdate") # the working columns dup_sql adds and drops again DUP_WORK = ("dup_rev", "dup_sup", "dup_nk_rank", "dup_nk_n") + tuple(f"dup_r_{a}" for a, _ in DUP_HASHES) DUP_KEEP = ("dup_sup", "dup_nk_rank > 1", "dup_ord", "source", "batch", "uri", "range_offset", "member_path", "row_file", "row_index") def batch_date_sql(x: str) -> str: """The date in the text x (a batch name) as YYYYMMDD, '' when it has none: the first match of YYYY[-]MM[-]DD.""" return f"replace(regexp_extract(coalesce({x}, ''), '[0-9]{{4}}-?[0-9]{{2}}-?[0-9]{{2}}'), '-', '')" def dup_inputs_sql() -> list: """The DUP_INPUTS as SELECT items over p JOIN b: what the hashes cover (hash_scope_sql), the three hashes as lowercase hex, the unit of a SUPERSEDE source, the source's registry order, the date of the batch name and, for a SUPERSEDE source, the date its supersession compares (the batch name's, else the one in source_meta.batch).""" unit = ("CASE p.source " + " ".join(f"WHEN {sql_str(s)} THEN nullif({source_meta_sql(sql_str(k))}, '')" for s, k in sorted(SUPERSEDE.items())) + " END") srcs = ", ".join(sql_str(s) for s in sorted(SUPERSEDE)) d = batch_date_sql("p.batch") sd = (f"CASE WHEN p.source IN ({srcs}) THEN coalesce(nullif({d}, ''), " f"{batch_date_sql(source_meta_sql(sql_str('batch')))}) ELSE '' END") return ([f"{hash_scope_sql()} AS dup_scope"] + [f"{hash_sql(a)} AS dup_{a}" for a, _ in DUP_HASHES] + [f"{unit} AS dup_unit", "b.registry_order AS dup_ord", f"{d} AS dup_date", f"{sd} AS dup_sdate"]) def dup_sql(rows: str) -> str: """The rows of the relation rows (DUP_ROW_COLS, DUP_INPUTS and any other columns), each with duplicate_reason (the first of DUP_REASONS that holds, NULL for a row that is kept) and natural_key_conflict (true for the row kept of a natural key that other rows share), without DUP_INPUTS. Window functions only, over every row of rows: the caller gives the rows the other criteria keep, so the copy kept is one of them. A hash is used when it is lowercase hex of its length (md5 only with a size).""" valid = ", ".join(f"CASE WHEN length(dup_{a}) = {n} AND regexp_full_match(dup_{a}, '[0-9a-f]+')" + (" AND size_bytes IS NOT NULL" if a == "md5" else "") + f" THEN dup_{a} END AS dup_{a}" for a, n in DUP_HASHES) nk = ", ".join(NATURAL_KEY) keep = ", ".join(DUP_KEEP) ranks = ", ".join(f"CASE WHEN dup_{a} IS NOT NULL THEN row_number() OVER (PARTITION BY dup_scope, dup_{a}" + (", size_bytes" if a == "md5" else "") + f" ORDER BY {keep}) END AS dup_r_{a}" for a, _ in DUP_HASHES) nk_reason, sup_reason, *same = DUP_REASONS reason = (f"CASE WHEN dup_nk_rank > 1 THEN '{nk_reason}' WHEN dup_sup THEN '{sup_reason}' " + " ".join(f"WHEN dup_r_{a} > 1 THEN '{r}'" for (a, _), r in zip(DUP_HASHES, same)) + " END") s1 = f"SELECT * REPLACE ({valid}),\n contains(lower(batch), 'revised') AS dup_rev\nFROM ({rows})" s2 = ("SELECT *, dup_unit IS NOT NULL AND batch <> arg_max(batch, struct_pack(d := dup_sdate, r := dup_rev, " f"b := batch)) OVER (PARTITION BY source, dup_unit) AS dup_sup\nFROM ({s1})") s3 = (f"SELECT *, row_number() OVER (PARTITION BY {nk} ORDER BY dup_sup, dup_date DESC, dup_rev DESC, " f"batch DESC, row_file DESC, row_index DESC) AS dup_nk_rank,\n count(*) OVER (PARTITION BY {nk}) AS dup_nk_n\n" f"FROM ({s2})") s4 = f"SELECT *,\n {ranks}\nFROM ({s3})" return (f"SELECT * EXCLUDE ({', '.join(DUP_INPUTS + DUP_WORK)}),\n {reason} AS duplicate_reason,\n" f" dup_nk_n > 1 AND dup_nk_rank = 1 AS natural_key_conflict\nFROM ({s4})") def tag_key_sql() -> str: """Join condition between a row p and its lines in meta/tags.parquet (t).""" return ("t.source = p.source AND t.batch = p.batch AND t.collection IS NOT DISTINCT FROM p.collection " f"AND t.ext IS NOT DISTINCT FROM p.ext AND t.meta_value IS NOT DISTINCT FROM {meta_value_sql()} " f"AND t.content IS NOT DISTINCT FROM {own_content_sql()}") def checked_sql(col: str = "checked") -> str: """True for a row whose file and collection pass column col of meta/bench_checked.parquet (view c): col checked says the rows were compared with the benchmark list, col default_keep says the default filter keeps them. Every published data file is listed (the release compares every file); a file not listed belongs to a revision older than that and does not pass. A collection listed with scope container (a collection whose name matches a benchmark and that awaits a ruling) must pass too.""" return f"{checked_file_sql(col)} AND {not_pending_sql(col)}" def checked_file_sql(col: str = "checked") -> str: """True for a row whose data file passes column col of meta/bench_checked.parquet (scope file): with col checked, the file was compared with the benchmark list.""" return f"coalesce((SELECT bool_and(c.{col}) FROM c WHERE c.scope = 'file' AND c.row_file = p.row_file), false)" def not_pending_sql(col: str = "checked") -> str: """True unless the row's collection is listed in meta/bench_checked.parquet with scope container and fails column col (a collection whose name matches a benchmark and that awaits a ruling).""" return (f"NOT EXISTS (SELECT 1 FROM c WHERE c.scope = 'container' AND NOT c.{col} AND c.source = p.source AND " f"c.collection = split_part(p.collection, '@', 1))") def default_conditions() -> list: """The row conditions of the default filter, one (name, SQL condition) per rule: they remove copies of benchmark data (meta/bench_overlap.parquet) and the rows meta/bench_checked.parquet does not keep by default (column default_keep). The duplicate copies are removed after them, over the rows they keep (dup_sql). Tables: p rows, b batches, o bench_overlap, c bench_checked. License tiers, sizes and versions are not part of it.""" rem = ", ".join(sql_str(c) for c in OVERLAP_REMOVE) return [("not_in_benchmark_row", f"NOT EXISTS (SELECT 1 FROM o WHERE o.scope = 'row' AND o.hit_class IN ({rem}) " f"AND {same_key('o')})"), ("not_in_benchmark_container", f"NOT EXISTS (SELECT 1 FROM o WHERE o.scope = 'container' AND " f"o.hit_class IN ({rem}) AND o.source = p.source AND " f"o.collection = split_part(p.collection, '@', 1))"), ("checked_for_benchmarks", checked_sql("default_keep"))] def tag_condition(tags) -> str: vals = ", ".join(sql_str(t) for t in tags) return f"EXISTS (SELECT 1 FROM t WHERE {tag_key_sql()} AND t.tag IN ({vals}))" def tag_names(tags) -> list: """#2397: the --tag values tags, each campaign: of a batch of RENAMED_BATCHES followed by the same tag under the batch's other name (its published name, or its old one), in order and once each.""" other = {**RENAMED_BATCHES, **{new: old for old, new in RENAMED_BATCHES.items()}} out: list = [] for t in tags: name = t[len("campaign:"):] if t.startswith("campaign:") else None for x in (t, *([f"campaign:{other[name]}"] if name in other else [])): if x not in out: out.append(x) return out # ---------- the default profile ---------- # The criteria of the profile, in the order a removed unit is counted under (the first one it fails), each with the # option that relaxes it (RELAX) or turns it on (OPT_IN) and the reason a removed unit is reported with. --all turns # off every criterion of the default profile except the benchmark criteria (BENCHMARK_CRITERIA); --allow-benchmark also # turns off "not compared". The duplicate criterion is judged last, over the units every other criterion keeps # (dup_sql), so a unit it removes failed no other criterion and the copy it keeps is one the reader gets. CRITERIA = ("duplicate", "benchmark", "not compared", "license", "language", "personal data", "size", "refused") # #1891: the criteria --all leaves on. Rows that matched a benchmark or were not compared with the benchmark list yet # come in only by their own options (fail-safe defaults: a permission, not an exclusion another option switches off), # so evaluation data never enters a selection with a choice about how much to take. BENCHMARK_CRITERIA = ("benchmark", "not compared") RELAX = {"duplicate": "keep_duplicates", "benchmark": "allow_benchmark", "not compared": "allow_not_compared", "language": "any_language", "size": "any_size", "refused": "allow_refused"} # #2441: the criteria the default profile leaves off, each on only with its own option, --all or not: the training # permit and the personal-data mark are labels every row carries, and the fetch tool takes every row whatever they say # unless it is asked to leave such rows out (the old options that kept them, --any-license and --allow-personal-data, # change nothing) OPT_IN = {"license": "training_only", "personal data": "no_personal_data"} REASONS = {"duplicate": "a duplicate copy of another row", "benchmark": "matched a benchmark", "not compared": "not compared with the benchmark list yet", "license": "the license does not let the files be shipped", "language": "recorded in a language other than English", "personal data": "marked as carrying personal data", "size": "above 20 MB", "refused": "refused by its site when the release's fetch check read it: HTTP 401 or 403, a login, or an " "empty or short body"} PROFILE_MAX_BYTES = 20_000_000 # the size criterion and the download cap under the profile (20 MB) # #2674: the refused criterion's readings, those of the release's fetch check (index_projection.SIZES, written by # 03_data_line/steps/sizes.py): a refusal is status needs_auth on an answer of REFUSED_CODES, or on a fetch (method # REFUSED_LOGIN) that a git host answered by asking for a login, which has no HTTP status; a row the check skipped for # its own access.needs_auth was not asked and is not one. #2698: also status REFUSED_SHORT of a reading that read the # body (a method of REFUSED_BODY) and measured fewer bytes than the row records: an empty or truncated body (on # 2026-11-12 a workbook of scotland-government-workbooks came back with 0 of its 217,093 bytes, and dataverse.nl had # answered with a bot check of 2,289 bytes in place of workbooks). Table r holds them (refused_rows_sql). SIZES = "meta/sizes.parquet" REFUSED_STATUS = "needs_auth" REFUSED_CODES = (401, 403) REFUSED_LOGIN = "fetched" REFUSED_SHORT = "size_mismatch" REFUSED_BODY = ("fetched", "member") PII_REMOVE = ("present", "suspected") # catalog pii.level values the personal-data criterion removes PD_REMOVE = ("pseudonymous", "identifiable") # pool_fields personal_data values it removes # a natural-language code in source_meta.language: ISO 639-1 or 639-2 in lower case with optional subtags; several # codes are separated by spaces, commas or semicolons. Capitalised values (Python, Go, COBOL) name programming # languages and are not codes. en, eng: English; zxx: no linguistic content; und: undetermined (as if none). LANG_CODE = r"[a-z]{2,3}(-[A-Za-z0-9]{2,8})*" LANG_KEEP = ("en", "eng", "zxx", "und") _LANG_EDGE = (r"(^|[\s,;])", r"($|[\s,;])") def language_ok_sql() -> str: """True when the row records no natural-language code, or one of them is English or language-free. The code is source_meta.language, else source_meta.labels.language (the labels of collections built from the search's candidates).""" v = (f"coalesce({source_meta_sql(chr(39) + 'language' + chr(39))}, " f"{source_meta_sql(chr(39) + 'labels.language' + chr(39))}, '')") a, z = _LANG_EDGE keep = "|".join(LANG_KEEP) return (f"(NOT regexp_matches({v}, '{a}{LANG_CODE}{z}') " f"OR regexp_matches({v}, '{a}({keep})(-[A-Za-z0-9]{{2,8}})*{z}'))") def personal_ok_sql() -> str: """True when neither the source (catalog pii.level, view s) nor the row (column sensitive, pool_fields personal_data) is marked as carrying personal data.""" lv = ", ".join(sql_str(x) for x in PII_REMOVE) pf = f"coalesce({source_meta_sql(chr(39) + 'pool_fields' + chr(39))}, '')" pd = "|".join(PD_REMOVE) return (f"(p.sensitive IS NULL AND p.source NOT IN (SELECT s.source FROM s WHERE s.pii_level IN ({lv})) " f"AND NOT regexp_matches({pf}, '\"personal_data\",\\s*\"({pd})\"'))") def row_key_sql() -> str: """A row's key in its data file as the fetch check's readings name it (meta/sizes.parquet row_key; 03_data_line/ steps/sizes.py ROW_KEY_SQL): its uri column, then @range_offset for a byte range, then !/member_path for a member of a container.""" return ("concat(p.uri, coalesce('@' || CAST(p.range_offset AS VARCHAR), ''), " "coalesce('!/' || p.member_path, ''))") def refused_ok_sql() -> str: """#2674: true unless the release's fetch check read the row and its site refused it (table r, refused_rows_sql).""" return (f"NOT EXISTS (SELECT 1 FROM r WHERE r.source = p.source AND r.batch = p.batch " f"AND r.row_key = {row_key_sql()})") def refused_rows_sql(root: str, sources=None) -> str: """#2674: the SELECT of table r: (source, batch, row_key) of each row of sources (every source when None) that the release's fetch check read and found refused by its site (meta/sizes.parquet, REFUSED_*: needs_auth on a 401, a 403 or a login; #2698: a body read empty or shorter than its record), apart from the sources whose catalog column needs_auth (table s) marks a login or a payment: the check reads anonymously, and this script skips such rows itself, or fetches them with what they need (requester-pays buckets with AWS credentials).""" marked = ", ".join(sql_str(v) for v in NOT_MARKED if isinstance(v, str)) conds = [f"((status = {sql_str(REFUSED_STATUS)} " f"AND (http_status IN ({', '.join(str(c) for c in REFUSED_CODES)}) " f"OR (method = {sql_str(REFUSED_LOGIN)} AND http_status IS NULL))) " f"OR (status = {sql_str(REFUSED_SHORT)} AND method IN ({', '.join(sql_str(m) for m in REFUSED_BODY)}) " "AND measured_size_bytes < recorded_size_bytes))", f"source NOT IN (SELECT s.source FROM s WHERE coalesce(s.needs_auth, '') NOT IN ({marked}))"] if sources is not None: conds.append(f"source IN ({', '.join(sql_str(s) for s in sources) or 'NULL'})") return (f"SELECT DISTINCT source, batch, row_key FROM read_parquet({sql_str(root + '/' + SIZES)}) " f"WHERE {' AND '.join(conds)}") def profile_conditions(relaxed=()) -> list: """The criteria of CRITERIA that are on, every one not in relaxed, [(name, SQL condition that is true when the row passes)], in CRITERIA order (#2441: the default profile relaxes those of OPT_IN, main); the duplicate criterion has no row condition (None): cand_steps applies dup_sql over the rows the others keep. Tables: p rows, b batches, o bench_overlap, c bench_checked, s catalog, r the rows the release's fetch check found refused (refused_rows_sql).""" dc = dict(default_conditions()) sql = {"duplicate": None, "benchmark": " AND ".join(f"({x})" for x in (dc["not_in_benchmark_row"], dc["not_in_benchmark_container"], not_pending_sql("default_keep"))), "not compared": checked_file_sql("default_keep"), "license": f"({tier_sql('training_ok')} = 'yes' AND {tier_sql('redistribution_ok')} IN ('yes', 'conditional'))", "language": language_ok_sql(), "personal data": personal_ok_sql(), "size": f"(p.size_bytes IS NULL OR p.size_bytes <= {PROFILE_MAX_BYTES})", "refused": refused_ok_sql()} return [(n, sql[n]) for n in CRITERIA if n not in set(relaxed)] def unit_sql() -> str: """The unit a row belongs to when its files are selected together: source_meta.unit_group (shared by the files of a unit), else the row itself (row_file#row_index; the row's natural key is the same row in a snapshot); NULL for a row of a collection without a unit_group (the source's README.md and LICENSE), which belongs to its source.""" ug = f"nullif({source_meta_sql(chr(39) + 'unit_group' + chr(39))}, '')" camp = source_meta_sql(chr(39) + "campaign" + chr(39)) return (f"(CASE WHEN {ug} IS NOT NULL THEN {ug} WHEN {camp} IS NOT NULL THEN NULL " f"ELSE p.row_file || '#' || CAST(p.row_index AS VARCHAR) END)") def unit_id_sql() -> str: """unit_id (the Python unit_id) of a row in SQL: source_meta.unit_group, else (outside a collection) the row's uri, then @ for a byte range, then !/ for an archive member; NULL for a row of a collection without a unit_group (the source's README.md and LICENSE). The uri is the one restore gives unit_id: the whole row's own for a row kept whole (_row), else the uri before the address swap (uri_sql), which for a file of the index repository is the path unit_id records as repo_uri. Needs the row's batch joined as b.""" ug = f"nullif({source_meta_sql(chr(39) + 'unit_group' + chr(39))}, '')" camp = source_meta_sql(chr(39) + "campaign" + chr(39)) uri = f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.uri') ELSE {uri_sql()} END)" return (f"(CASE WHEN {ug} IS NOT NULL THEN {ug} WHEN {camp} IS NOT NULL THEN NULL " f"ELSE {uri} || coalesce('@' || CAST(p.range_offset AS VARCHAR), '') " "|| coalesce('!/' || nullif(p.member_path, ''), '') END)") def unit_key_sql() -> str: """The fixed order of units (--sample, --limit) within a data file, the second of its two stages (#2035; the first is the data file's file_key, cand_select keyed): for a row of its own its fetch order (fetch_order, the order of earlier versions of this script), for a unit_group the sha256 of source and group.""" ug = source_meta_sql(chr(39) + "unit_group" + chr(39)) return f"(CASE WHEN {ug} IS NULL THEN {fetch_order()} ELSE sha256(p.source || chr(0) || {ug}) END)" # #2035: the first stage of the fixed order of units (--limit, --sample): the data file that holds the unit, by its # file_key; table fetch_files gives it for the row_file (rows_from) of each data file of the selection (file_keys_sql) FILE_KEYS = "fetch_files" def file_key(rel: str) -> str: """The order key of the data file at the repository path rel (as the catalog's column data_files names it, such as data/npm/all/part-00060.parquet): the sha256 of the path in hex, as DuckDB's sha256 gives it in file_keys_sql.""" return hashlib.sha256(rel.encode("utf-8")).hexdigest() def file_keys_sql(root: str, files: str) -> str: """The statement that makes table fetch_files (FILE_KEYS): one line per row_file (row_file_sql, as rows_from gives it) of the data files under root that files names (an SQL query with their repository paths in its column f, as the catalog's column data_files names them), with its file_key (the sha256 of that path).""" return (f"CREATE OR REPLACE TEMP TABLE {FILE_KEYS} AS SELECT {row_file_sql(root, sql_str(root + '/') + ' || f')} " f"AS row_file, min(sha256(f)) AS file_key FROM ({files}) GROUP BY ALL") def domain_match_sql(col: str, domains) -> str: """True when the domain code in col matches one of domains: equal to it or, for a code D or D., one of its leaves (it starts with the code and a dot); multi and unclassified match only themselves.""" out = [] for d in domains: out.append(f"{col} = {sql_str(d)}") if d.startswith("D"): out.append(f"starts_with({col}, {sql_str(d + '.')})") return "(" + " OR ".join(out) + ")" def catalog_select_sql(domains=(), forms=(), kinds=()) -> str: """The sources of view s that match: any domain entry matches one of domains (when given), the form is one of forms (when given) and the kind is one of kinds (when given).""" conds = [] if domains: conds.append(f"s.source IN (SELECT e.source FROM (SELECT s.source, unnest(s.domain) AS code FROM s) e " f"WHERE {domain_match_sql('e.code', domains)})") if forms: conds.append(f"s.form IN ({', '.join(sql_str(f) for f in forms)})") if kinds: conds.append(f"s.kind IN ({', '.join(sql_str(k) for k in kinds)})") return "SELECT DISTINCT s.source FROM s WHERE " + " AND ".join(conds) def catalog_condition(domains=(), forms=(), kinds=()) -> str: """The row condition of --domain, --form and --kind: the row's source is one of the catalog sources that match.""" return f"p.source IN ({catalog_select_sql(domains, forms, kinds)})" def fetch_order() -> str: return ("sha256(concat_ws(chr(0), p.source, p.uri, coalesce(CAST(p.range_offset AS VARCHAR), ''), " "coalesce(p.member_path, '')))") def build_where(*, tags=(), sources=(), tiers=None, min_size=None, max_size=None, where=None, max_size_filter=None, domains=(), forms=(), kinds=(), units=()) -> list: """Your own WHERE conditions of the selection (the default profile is apart: profile_conditions and cand_steps; --ext chooses units, not rows: cand_steps exts). max_size is accepted for older callers and ignored: a size cap applies when fetching (cand_steps), it does not remove rows. max_size_filter removes the rows whose known size is larger (rows of unknown size stay). domains, forms and kinds keep the rows of the sources that match them in meta/catalog.parquet (view s, catalog_condition). units (--unit) keep the rows of the units with these unit_ids and the files of their sources (README.md, LICENSE), which come with a unit taken.""" conds = [] if tiers is not None: conds.append(f"{tier_sql()} IN ({', '.join(sql_str(t) for t in tiers)})") if min_size is not None: conds.append(f"p.size_bytes >= {int(min_size)}") if max_size_filter is not None: conds.append(f"(p.size_bytes IS NULL OR p.size_bytes <= {int(max_size_filter)})") if tags: conds.append(tag_condition(tags)) if sources: conds.append(f"p.source IN ({', '.join(sql_str(s) for s in sources)})") if domains or forms or kinds: conds.append(catalog_condition(domains, forms, kinds)) if units: uid = unit_id_sql() conds.append(f"({uid} IN ({', '.join(sql_str(u) for u in units)}) OR {uid} IS NULL)") if where: conds.append(f"({where})") return conds def _root(args) -> str: return args.data.rstrip("/") if args.data else f"hf://datasets/{args.repo}" def file_list(paths) -> str: """The data files paths (full paths, source_files) as a DuckDB list literal for read_parquet.""" return "[" + ", ".join(sql_str(p) for p in paths) + "]" def batch_filter(batches) -> str: """The WHERE clause that keeps only the rows of the (source, batch) pairs batches (tag_batches): a data file may hold rows of other batches, so the pairs are matched by the rows' own columns, not by file paths.""" return " WHERE " + " OR ".join(f"(source = {sql_str(s)} AND batch = {sql_str(b)})" for s, b in batches) def files_sql(root: str, sources=(), batches=None) -> str: """The statement that sets the DuckDB variable data_files to the full paths of the data files the catalog's column data_files names for sources (every source when none is given), or with batches ((source, batch) pairs) those its column batch_files names for them: the one read of meta/catalog.parquet that the rows view p takes its files from (views_sql).""" if batches: pairs = " OR ".join(f"(source = {sql_str(s)} AND x.batch = {sql_str(b)})" for s, b in batches) pick = (f"SELECT DISTINCT x.file AS f FROM (SELECT source, unnest({BATCH_FILES}) AS x FROM " f"read_parquet({sql_str(root + '/' + CATALOG)})) WHERE {pairs}") else: where = f" WHERE source IN ({', '.join(sql_str(s) for s in sources)})" if sources else "" pick = f"SELECT DISTINCT unnest({DATA_FILES}) AS f FROM read_parquet({sql_str(root + '/' + CATALOG)}){where}" return f"SET VARIABLE {DATA_FILES} = (SELECT list({sql_str(root + '/')} || f ORDER BY f) FROM ({pick}))" def views_sql(root: str, *, sources=(), batches=None, domains=(), forms=(), kinds=()) -> list: """The views p (rows), b, o, t, c, s (meta/catalog.parquet: source, domain, form, pii_level, spdx, files, needs_auth, and kind when kinds are given) and r (#2674: refused_rows_sql), as --print-sql shows them (a run reads the same tables filtered to its sources, table_steps). p reads exactly the data files the catalog's column data_files names for the sources (files_sql), no listing of data/, and keeps the rows of those sources by their column source (a file may hold rows of others). batches: (source, batch) pairs (tag_batches); when given, p reads only the files the column batch_files names for them and holds only the rows of those batches, and o, t hold only the rows of their sources (every condition of the default filter and of the tags joins them on the row's source). Duplicates have no table: dup_sql finds them among the rows read.""" names = sorted({s for s, _ in batches}) if batches else sorted(sources) mine = f" WHERE source IN ({', '.join(sql_str(s) for s in names)})" if names else "" keep = mine if batches else "" rows = rows_from(root, f"getvariable('{DATA_FILES}')") + (batch_filter(batches) if batches else mine) out = [files_sql(root, names, batches), f"CREATE OR REPLACE VIEW p AS {rows}", f"CREATE OR REPLACE VIEW b AS SELECT * FROM read_parquet({sql_str(root + '/meta/batches.parquet')})", f"CREATE OR REPLACE VIEW o AS SELECT * FROM read_parquet({sql_str(root + '/meta/bench_overlap.parquet')}){keep}", f"CREATE OR REPLACE VIEW t AS SELECT * FROM read_parquet({sql_str(root + '/meta/tags.parquet')}){keep}", f"CREATE OR REPLACE VIEW c AS SELECT * FROM read_parquet({sql_str(root + '/meta/bench_checked.parquet')})", f"CREATE OR REPLACE VIEW s AS SELECT source, domain, form, pii.level AS pii_level, license.spdx AS spdx, " f"files, needs_auth{', kind' if kinds else ''} FROM read_parquet({sql_str(root + '/' + CATALOG)})", f"CREATE OR REPLACE VIEW r AS {refused_rows_sql(root, names or None)}"] return out # ---------- reading only what the selection needs ---------- # A selection whose sources hold at most this many rows (by the catalog's files column) is copied into memory with # one read of its data files; a larger one is read in place (twice: to pick the rows, then to copy the picked ones). # #2035: with --limit or --sample the same holds for the data files read_units reads, a round of files at a time, and a # larger selection reads again only the files that hold the rows picked (picked_rows). LOCAL_ROWS = 2_000_000 READ_JOBS = 8 # parallel reads of the tables (each is one or a few HTTP requests) _SETUP: dict = {} # id(connection) -> the session settings every cursor of it repeats (connect) class UnknownName(Exception): """A source, kind, domain or form name that the catalog does not have (the message names the closest ones).""" def catalog_table(con, root: str) -> dict: """meta/catalog.parquet read once into table s: source, domain (list of codes), form, pii_level, spdx, files, kind, (#2674) needs_auth, (#1577) the fetch check fetch_level, fetch_rows, fetch_fetched, fetch_read_at (NULL where this revision of the catalog has no such column; #2006: from its column fetch_check, FETCH_CHECK, or in release-2026-11-09.1 from its column fetch), and (#1746) data_files and batch_files (DATA_FILES, BATCH_FILES: the repository paths of the source's data files, and of each batch's) only where this revision of the catalog has them (source_files). Every catalog column and struct field is read as a quoted identifier (col): fetch is a reserved word of DuckDB's parser, so an unquoted fetch.level does not parse. -> {column: present}, FETCH_CHECK for the fetch check under either name.""" con.execute(f"CREATE OR REPLACE TABLE s_raw AS SELECT * FROM read_parquet({sql_str(root + '/' + CATALOG)})") have = {str(r[0]): str(r[1]) for r in con.execute("DESCRIBE s_raw").fetchall()} def col(path, name, typ, ok): expr = ".".join(f'"{p}"' for p in path.split(".")) return f"{expr} AS {name}" if ok else f"CAST(NULL AS {typ}) AS {name}" # expand now, contract later: the read of the old name goes once a release with fetch_check is published fc = FETCH_CHECK if FETCH_CHECK in have else FETCH_CHECK_OLD fetch = "level" in have.get(fc, "") cols = ['"source"', col("domain", "domain", "VARCHAR[]", "domain" in have), col("form", "form", "VARCHAR", "form" in have), col("pii.level", "pii_level", "VARCHAR", "level" in have.get("pii", "")), col("license.spdx", "spdx", "VARCHAR", "spdx" in have.get("license", "")), col("files", "files", "BIGINT", "files" in have), col("kind", "kind", "VARCHAR", "kind" in have), col("needs_auth", "needs_auth", "VARCHAR", "needs_auth" in have), col(f"{fc}.level", "fetch_level", "VARCHAR", fetch), col(f"{fc}.rows", "fetch_rows", "BIGINT", fetch), col(f"{fc}.fetched", "fetch_fetched", "BIGINT", fetch), col(f"{fc}.read_at", "fetch_read_at", "VARCHAR", fetch)] cols += [c for c in (DATA_FILES, BATCH_FILES) if c in have] con.execute(f"CREATE OR REPLACE TABLE s AS SELECT {', '.join(cols)} FROM s_raw") con.execute("DROP TABLE s_raw") return {**{k: k in have for k in ("domain", "form", "pii", "license", "files", "kind", DATA_FILES, BATCH_FILES)}, FETCH_CHECK: fetch} def source_files(con, root: str, sources=None, batches=None) -> dict: """{source: the full paths of the data files to read for it} for the sources of table s (every source when sources is None), under root; batches: (source, batch) pairs (tag_batches), then only the files that hold those batches, of their sources. The catalog's column data_files names a source's files and batch_files the files of each of its batches (#1746), so data/ is never listed. A revision whose catalog has no column data_files (older than #1746): IndexReadError (older_catalog). For a local copy only the files it holds. A source with no file is not in the result.""" pairs = None if batches is None else {(str(s), str(b)) for s, b in batches} want = {s for s, _ in pairs} if pairs is not None else None if sources is None else set(sources) if DATA_FILES not in {str(r[0]) for r in con.execute("DESCRIBE s").fetchall()}: raise older_catalog(root) out = {} for s, rels, by in con.execute(f"SELECT source, {DATA_FILES}, {BATCH_FILES} FROM s ORDER BY source").fetchall(): s = str(s) if want is not None and s not in want: continue rels = rels if pairs is None else [x["file"] for x in by or () if (s, x["batch"]) in pairs] paths = [f"{root}/{r}" for r in sorted(set(rels or ()))] if not is_remote(root): paths = [p for p in paths if Path(p).is_file()] if paths: out[s] = paths return out def index_files(root: str, sources, batches=None) -> list: """The full paths of the data files of sources at root (of the (source, batch) pairs batches when given), sorted, for a reader that takes table_steps without main: one read of meta/catalog.parquet (catalog_table, source_files), so data/ is not listed.""" con = connect(remote=is_remote(root)) try: catalog_table(con, root) return sorted({p for ps in source_files(con, root, sources, batches).values() for p in ps}) finally: con.close() def catalog_names_files(root: str) -> bool: """Whether the catalog at root has the column data_files (#1746), from its schema alone (one read of the file's footer): --print-sql prints no statement for a revision without it (older_catalog).""" con = connect(remote=is_remote(root)) try: cols = con.execute(f"DESCRIBE SELECT * FROM read_parquet({sql_str(root + '/' + CATALOG)})").fetchall() return DATA_FILES in {str(r[0]) for r in cols} finally: con.close() def older_catalog(root: str) -> "IndexReadError": """#1769: the error for a revision whose catalog has no column data_files (older than #1746): its data files are named nowhere but in their paths, which this tool does not read.""" return IndexReadError(f"{CATALOG} at {root} has no column {DATA_FILES}: this revision of the index is older than " f"that column, which names the data files of each source, so it cannot be read; read a newer " f"revision (a later --revision, or none for the current one)") def _closest(name: str, names) -> str: import difflib near = difflib.get_close_matches(name, sorted(set(names)), n=3, cutoff=0.6) return ", ".join(near) if near else "none close" def check_names(con, *, sources=(), domains=(), forms=(), kinds=(), has_form=True, where: str = "") -> None: """Every name given must be in table s: a source name, a domain code that a source carries (a top-level code counts when one of its leaves is carried), a form, a kind. Raises UnknownName with one line naming the closest names.""" srcs = {str(r[0]) for r in con.execute("SELECT source FROM s").fetchall()} for s in sources: if s not in srcs: raise UnknownName(f"--source {s}: no such source in {CATALOG}{where}; closest: {_closest(s, srcs)}") if domains: codes = {str(r[0]) for r in con.execute("SELECT DISTINCT unnest(domain) FROM s").fetchall() if r[0]} codes |= {c.split(".")[0] for c in codes} for d in domains: if d not in codes: raise UnknownName(f"--domain {d}: no source in {CATALOG}{where} has this domain; closest: " f"{_closest(d, codes)}") if forms and has_form: fs = {str(r[0]) for r in con.execute("SELECT DISTINCT form FROM s").fetchall() if r[0]} for f in forms: if f not in fs: raise UnknownName(f"--form {f}: no source in {CATALOG}{where} has this form; closest: {_closest(f, fs)}") if kinds: ks = {str(r[0]) for r in con.execute("SELECT DISTINCT kind FROM s").fetchall() if r[0]} for k in kinds: if k not in ks: raise UnknownName( f"--kind {k}: no source in {CATALOG}{where} has this kind; closest: {_closest(k, ks)}") def resolve_sources(con, root: str, *, domains=(), forms=(), kinds=(), sources=()) -> list: """The sources of table s that match domains, forms and kinds (catalog_select_sql), limited to sources when given; every source when none of the four is given. Sorted. Sources whose catalog row names no data file (for a local copy: none it holds, source_files) are left out.""" if domains or forms or kinds: sql = catalog_select_sql(domains, forms, kinds) if sources: sql += f" AND s.source IN ({', '.join(sql_str(s) for s in sources)})" found = sorted(str(s) for (s,) in con.execute(sql).fetchall() if s is not None) elif sources: found = sorted(set(sources)) else: found = sorted(str(s) for (s,) in con.execute("SELECT source FROM s").fetchall()) have = source_files(con, root, found) return [s for s in found if s in have] def table_rows(root: str, files: list, sources, *, batches=None, everything: bool = False) -> str: """The SELECT of the selection's rows in the data files files (full paths under root, read one by one with no listing): the rows of sources (a file may also hold rows of other sources), with batches ((source, batch) pairs, tag_batches) only the rows of those batches, and every row when everything.""" names = sorted({s for s, _ in batches}) if batches else sorted(sources) w = "" if everything else f" WHERE source IN ({', '.join(sql_str(s) for s in names) or 'NULL'})" return rows_from(root, file_list(files)) + (batch_filter(batches) if batches else w) def table_steps(root: str, sources, files: list, *, batches=None, tags=(), everything: bool = False, local_rows: bool = False) -> dict: """{table: statement} that read only what the selection needs, run in parallel (read_parallel): p0 the rows (a table when local_rows, else a view; complete_rows then makes the view p over it), and of b, o, c (and t with tags) only the rows of sources, and (#2674) r, the rows of sources the release's fetch check found refused (refused_rows_sql, over table s: catalog_table runs first). files: the full paths of the selected sources' data files (source_files; with batches only the files that hold those batches), read one by one with no listing (index_files gives them to a reader without main); a file may also hold rows of other sources, so p0 keeps only the rows of sources (table_rows). batches: (source, batch) pairs (tag_batches); when given, p0 holds only their rows. everything: every source is selected, so nothing is filtered.""" names = sorted({s for s, _ in batches}) if batches else sorted(sources) w = "" if everything else f" WHERE source IN ({', '.join(sql_str(s) for s in names) or 'NULL'})" def meta(name): return f"SELECT * FROM read_parquet({sql_str(f'{root}/meta/{name}.parquet')}){w}" rows = table_rows(root, files, sources, batches=batches, everything=everything) out = {"p": f"CREATE OR REPLACE {'TABLE' if local_rows else 'VIEW'} p0 AS {rows}", "b": f"CREATE OR REPLACE TABLE b AS {meta('batches')}", "o": f"CREATE OR REPLACE TABLE o AS {meta('bench_overlap')}", "c": f"CREATE OR REPLACE TABLE c AS {meta('bench_checked')}", "r": f"CREATE OR REPLACE TABLE r AS {refused_rows_sql(root, None if everything else names)}"} if tags: out["t"] = f"CREATE OR REPLACE TABLE t AS {meta('tags')}" return out def cursor(con): """A cursor of con with con's session settings (HTTP retries, proxy, token: connect).""" cur = con.cursor() for q in _SETUP.get(id(con), ()): cur.execute(q) return cur # The optional row columns the conditions read, with their types: data files written before a column existed lack it, # and p (complete_rows) gives it as NULL there, so a condition on it reads NULL instead of failing. ROW_OPTIONAL = (("truncated", "VARCHAR"), ("license_spdx", "VARCHAR"), ("license_training_ok", "VARCHAR"), ("license_redistribution_ok", "VARCHAR"), ("license_notes", "VARCHAR"), ("sensitive", "VARCHAR"), ("member_path", "VARCHAR"), ("parent_pointer_id", "VARCHAR"), ("range_offset", "BIGINT"), ("range_length", "BIGINT"), ("media_type", "VARCHAR"), ("origin_url", "VARCHAR"), ("origin_time", "VARCHAR"), ("extra", "VARCHAR"), ("sha256", "BLOB"), ("sha1", "BLOB"), ("md5", "BLOB"), ("crc32", "BLOB"), ("zip_local_header_offset", "BIGINT"), ("zip_compression_method", "BIGINT"), ("zip_compressed_size", "BIGINT")) def complete_rows(con) -> list: """View p over p0 (the rows read by table_steps) with every column of ROW_OPTIONAL that p0 lacks added as NULL. -> the columns added.""" have = {str(r[0]) for r in con.execute("DESCRIBE p0").fetchall()} add = [(c, t) for c, t in ROW_OPTIONAL if c not in have] extra = "".join(f", CAST(NULL AS {t}) AS {c}" for c, t in add) con.execute(f"CREATE OR REPLACE VIEW p AS SELECT *{extra} FROM p0") return [c for c, _ in add] def read_parallel(con, jobs: dict, bar=None) -> dict: """Run jobs ({name: SQL statement, or a function of a cursor}) on cursors of con in parallel threads (each read waits on the network); -> {name: the function's result or None}. The first failure is raised. bar (step_bar) ticks once per job done and is redrawn while they wait.""" import concurrent.futures as cf def one(job): cur = cursor(con) try: return job(cur) if callable(job) else cur.execute(job) and None finally: cur.close() out = {} every = None if bar is None else REDRAW[sys.stderr.isatty()] with cf.ThreadPoolExecutor(max(1, min(READ_JOBS, len(jobs)))) as ex: futs = {name: ex.submit(one, job) for name, job in jobs.items()} pending = set(futs.values()) while pending: done, pending = cf.wait(pending, timeout=every, return_when=cf.FIRST_COMPLETED) if bar is not None and done: bar.update(len(done)) elif bar is not None: bar.refresh() for name, f in futs.items(): out[name] = f.result() return out # while one step of reading the index or planning the selection runs, its progress line is redrawn every this many # seconds so that its elapsed time moves: on a terminal, and in a log (stderr not a terminal), where it adds a line REDRAW = {True: 1.0, False: 60.0} def step_bar(desc: str, unit: str, total: int, quiet: bool): """A tqdm progress line on stderr for reading the index or planning the selection: the steps done of the total and the time elapsed (no rate or estimate: one step may wait minutes on a rate limit). Off with quiet.""" from tqdm import tqdm return tqdm(total=total, desc=desc, file=sys.stderr, disable=quiet, bar_format=f"{{desc}}: {{n_fmt}}/{{total_fmt}} {unit} done, {{elapsed}} elapsed") def waiting(bar, con, fn, *args): """fn(*args) run in a thread while bar is redrawn every REDRAW seconds, so a step that waits on the network shows its elapsed time; -> its result. Ctrl-C interrupts the query running on con.""" import concurrent.futures as cf every = REDRAW[sys.stderr.isatty()] ex = cf.ThreadPoolExecutor(1) fut = ex.submit(fn, *args) try: while True: try: return fut.result(timeout=every) except cf.TimeoutError: bar.refresh() except KeyboardInterrupt: con.interrupt() raise finally: ex.shutdown(wait=True) def run_steps(con, steps: list, bar) -> None: """The SQL statements steps run on con in order, bar ticking once per statement (waiting).""" for s in steps: waiting(bar, con, con.execute, s) bar.update(1) def tag_batches(con, root: str, tags, sources=()) -> list: """The (source, batch) pairs that carry any of the tags (meta/tags.parquet, three columns read), limited to sources when given. Pairs of a source with no data file of those batches (source_files; for a local copy: none it holds) are left out.""" sql = (f"SELECT DISTINCT source, batch FROM read_parquet({sql_str(root + '/meta/tags.parquet')}) " f"WHERE tag IN ({', '.join(sql_str(t) for t in tags)})") if sources: sql += f" AND source IN ({', '.join(sql_str(s) for s in sources)})" pairs = [(str(s), str(b)) for s, b in con.execute(sql + " ORDER BY 1, 2").fetchall()] have = source_files(con, root, batches=pairs) return [(s, b) for s, b in pairs if s in have] # the columns of fetch_cand that its later steps carry (cand_steps), with file_key after them when keyed CAND_BASE = ("row_file", "row_index", "source", "unit", "unit_key", "fetch_key", "size_cap_bytes", "batch_cap_bytes") def cand_select(conds: list, profile: list, max_size: int | None = None, size_cap: int | None = None, exts=(), keyed: bool = False) -> str: """The lines the selection starts from (cand_steps), as one SELECT over p and b: one line per row that passes conds (your own conditions) with where it sits, its unit (unit_sql, NULL for a file of its source), the unit's order key (unit_key_sql), its caps, fail (the 1-based number in CRITERIA of the first criterion of profile it fails; NULL: it passes all) and the columns dup_sql reads when profile has the duplicate criterion (else natural_key_conflict false); with exts, ext_ok. size_cap (the profile's 20 MB) lowers the cap of a row whose batch cap is larger; max_size replaces both. keyed (#2035, --limit and --sample): also file_key, the key of the row's data file (table fetch_files, file_keys_sql), the first stage of the fixed order of units.""" if max_size is not None: cap = str(int(max_size)) elif size_cap is not None: cap = f"least(b.max_size_bytes, {int(size_cap)})" else: cap = "b.max_size_bytes" whole = str(int(max_size)) if max_size is not None else "b.max_size_bytes" rank = {n: i + 1 for i, n in enumerate(CRITERIA)} rows = [(n, c) for n, c in profile if c is not None] fail = ("CASE " + " ".join(f"WHEN NOT coalesce({c}, false) THEN {rank[n]}" for n, c in rows) + " END" if rows else "CAST(NULL AS INTEGER)") head = (f"SELECT p.row_file, p.row_index, p.source, {unit_sql()} AS unit, " f"{unit_key_sql()} AS unit_key, {fetch_order()} AS fetch_key, {cap} AS size_cap_bytes, " f"{whole} AS batch_cap_bytes, {fail} AS fail") if keyed: head += ", fk.file_key" if len(rows) < len(profile): head += ", " + ", ".join([f"p.{c}" for c in DUP_ROW_COLS if c not in CAND_BASE] + dup_inputs_sql()) else: head += ", false AS natural_key_conflict" if exts: head += f", lower(p.ext) IN ({', '.join(sql_str(e.lower().lstrip('.')) for e in exts)}) AS ext_ok" sel = f"{head} FROM p JOIN b ON b.source = p.source AND b.batch = p.batch" if keyed: sel += f" LEFT JOIN {FILE_KEYS} fk ON fk.row_file = p.row_file" if conds: sel += "\nWHERE " + "\n AND ".join(conds) return sel def cand_steps(conds: list, profile: list, max_size: int | None = None, size_cap: int | None = None, exts=(), *, keyed: bool = False, read: str | None = None) -> list: """The first part of the selection: table fetch_cand, the lines of cand_select (one per row that passes conds, with natural_key_conflict and fail, the 1-based number in CRITERIA of the first criterion of profile it fails; NULL: it passes all); then fetch_units, one line per unit with the first criterion any of its rows fails (and, keyed, the least file_key of its rows). exts (--ext) choose units, not rows: a unit stays when one of its files has one of the extensions, and then with all its rows; a file of a source stays when its source keeps such a unit. The duplicate criterion (in profile with no row condition) is judged last: fetch_cand0 holds the rows with the other criteria and the columns dup_sql reads, and dup_sql runs over the rows whose unit (or, for a file of a source, the row itself) fails none of them, so the copy kept is one the reader gets. A row it removes as an older version of a natural key leaves the selection: the newest version stands for it, so it is no file of its unit and does not fail it (#676: a corrected row is a new version; release-2026-11-03.1 lost every unit of a set whose rows were corrected); a row it removes for another reason fails the duplicate criterion. natural_key_conflict is true only for a row whose natural key the duplicate criterion removed from other rows. read (#2035): the table that already holds the lines of cand_select over the data files read so far (read_units); the first table is copied from it, so every criterion is judged again over all the lines read, and read stays as it is for the files read next.""" rank = {n: i + 1 for i, n in enumerate(CRITERIA)} dedup = any(c is None for _, c in profile) first = "fetch_cand0" if dedup else "fetch_cand" src = f"SELECT * FROM {read}" if read else cand_select(conds, profile, max_size, size_cap, exts, keyed) out = [f"CREATE OR REPLACE TEMP TABLE {first} AS {src}"] if exts: out.append(f"DELETE FROM {first} WHERE NOT EXISTS (SELECT 1 FROM {first} k WHERE k.unit IS NOT NULL " f"AND k.ext_ok AND k.source = {first}.source AND ({first}.unit IS NULL OR k.unit = {first}.unit))") if dedup: keep = ("c.fail IS NULL AND NOT EXISTS (SELECT 1 FROM fetch_cand0 f WHERE f.fail IS NOT NULL " "AND f.source = c.source AND f.unit = c.unit)") cols = ", ".join(CAND_BASE + (("file_key",) if keyed else ())) out += [f"CREATE OR REPLACE TEMP TABLE fetch_cand AS SELECT {cols}, natural_key_conflict, " f"CASE WHEN duplicate_reason IS NOT NULL THEN {rank['duplicate']} ELSE fail END AS fail " f"FROM ({dup_sql(f'SELECT c.* FROM fetch_cand0 c WHERE {keep}')})\n" f"WHERE duplicate_reason IS DISTINCT FROM '{DUP_REASONS[0]}'\n" f"UNION ALL SELECT {cols}, false, fail FROM fetch_cand0 c WHERE NOT ({keep})", "DROP TABLE fetch_cand0"] fk = ", min(file_key) AS file_key" if keyed else "" out.append(f"CREATE OR REPLACE TEMP TABLE fetch_units AS SELECT source, unit, min(unit_key) AS unit_key{fk}, " "min(fail) AS fail, count(*) AS files FROM fetch_cand WHERE unit IS NOT NULL GROUP BY source, unit") return out def pick_steps(limit: int | None = None, sample: int | None = None, keyed: bool = False) -> list: """The second part's first statements: fetch_take, the units kept (every row passes), at most sample per source and limit in all; fetch_pick, their rows and the files of their sources (that pass). Each source's units are numbered by DuckDB's row_number() over the source in the fixed order of units (unit_key; keyed, #2035: file_key first, the key of the unit's data file): sample keeps the first sample of each source, and limit takes them from the sources in turn (#2144), the first unit of each source, then the second of each, and so on, the sources of one turn in the order of the sha256 of their names (source_turn), so that it spreads over the sources.""" cols = "source, unit, unit_key" + (", file_key" if keyed else "") order = ("file_key, " if keyed else "") + "unit_key" inner = f"SELECT {cols} FROM fetch_units WHERE fail IS NULL" if sample is not None or limit is not None: inner = (f"SELECT {cols} FROM (SELECT {cols}, row_number() OVER (PARTITION BY source ORDER BY {order}, unit) " f"AS n FROM fetch_units WHERE fail IS NULL)" + (f" WHERE n <= {int(sample)}" if sample is not None else "") + (f" ORDER BY n, sha256(source), source LIMIT {int(limit)}" if limit is not None else "")) take = f"CREATE OR REPLACE TEMP TABLE fetch_take AS {inner}" picked = ("k.unit IS NOT NULL OR (c.unit IS NULL AND c.fail IS NULL AND c.source IN " "(SELECT source FROM fetch_take))") pick = ("CREATE OR REPLACE TEMP TABLE fetch_pick AS SELECT c.row_file, c.row_index, " "coalesce(k.unit_key, c.fetch_key) AS fetch_key, c.size_cap_bytes, c.batch_cap_bytes, " "c.natural_key_conflict, c.unit FROM fetch_cand c LEFT JOIN fetch_take k ON k.source = c.source " f"AND k.unit = c.unit WHERE {picked}") return [take, pick] def rows_steps() -> list: """The second part's last statements: fetch_rows, the rows of fetch_pick whole (from p), with fetch_source_file (true for a file of the source); then fetch_pick is dropped.""" rows = ("CREATE OR REPLACE TEMP TABLE fetch_rows AS SELECT p.*, k.fetch_key, k.unit IS NULL AS fetch_source_file, " "k.size_cap_bytes, k.batch_cap_bytes, k.natural_key_conflict FROM p JOIN fetch_pick k " "ON k.row_file = p.row_file AND k.row_index = p.row_index") return [rows, "DROP TABLE fetch_pick"] def take_steps(limit: int | None = None, sample: int | None = None, keyed: bool = False) -> list: """The second part: fetch_take and fetch_pick (pick_steps), then fetch_rows (rows_steps). part_queries returns fetch_rows in fetch order, one key range at a time (one query that both picks and sorts whole rows keeps every row in memory, and DuckDB cannot sort wide rows larger than its memory limit).""" return pick_steps(limit, sample, keyed) + rows_steps() def select_steps(conds: list, limit: int | None = None, max_size: int | None = None) -> list: """The rows that pass conds with no profile and every row its own unit, as statements (cand_steps and take_steps; kept for callers of earlier versions).""" return cand_steps(conds, [], max_size) + take_steps(limit) def source_turn(source: str) -> str: """#2144: the key of a source's place in a turn of --limit (pick_steps): the sha256 of its name in hex, as DuckDB's sha256 gives it.""" return hashlib.sha256(source.encode("utf-8")).hexdigest() def turn_files(mine: dict, seen: set, have: dict, turn: dict, limit: int, sample: int | None = None) -> list: """#2144: the data files the next round of read_units reads for --limit, the selected sources' data files taken in turn: the first file of each source, then the second of each, and so on (mine: {source: its data files in their fixed order}; seen: the files read), the sources of one turn in the order of turn ({source: source_turn}). have: {source: its units that pass in the files read}, each counted up to sample when given. -> the next files of the first turn with a file not read yet, of the sources that may still give a unit, at most as many as units are still missing to limit (a file holds at least one unit); none once limit units are known. A source whose files give no unit that passes is read one file a turn, as every other, so it never holds up the rest.""" missing = limit - sum(min(have.get(s, 0), limit if sample is None else sample) for s in mine) queue = sorted((i, turn[s], p) for s in mine if sample is None or have.get(s, 0) < sample for i, p in enumerate(mine[s]) if p not in seen) out: list = [] for i, _, p in queue: if missing <= 0 or i > queue[0][0] or len(out) == missing: break if p not in out: out.append(p) return out def read_units(con, root: str, by_source: dict, rows, cand: str, judge: list, bar, *, limit: int | None = None, sample: int | None = None, local: bool = False) -> tuple: """#2035: the selection's data files read in the fixed order of units, only as far as limit (--limit) and sample (--sample) need: whole files before their rows, in a fixed hash order so that it repeats (a block sample, as DuckDB's system sampling takes whole vectors). by_source: {source: the full paths of its data files under root} (source_files); each source's files are ordered by file_key, which table fetch_files (file_keys_sql) gives the rows. Each round reads the next files: with limit (#2144), the sources' files taken in turn (turn_files), the next turn's files not read yet, as many as units are missing; with sample alone, the next file not read yet of each source with fewer than sample units. rows(paths) is the SELECT of the selection's rows in those files (table_rows): a round copies them into table fetch_p when local (a selection of at most LOCAL_ROWS rows) or makes that a view over them, makes p over it (complete_rows) and adds the lines cand (cand_select keyed) gives (table fetch_new) to table fetch_read. judge (cand_steps over fetch_read) then judges every criterion again over all the lines read: with sample alone after a round that can change which units pass, one that read a line passing every row criterion (a round with no such line changes none, as the rows of a unit lie in one data file: layout2_stream._pack_group keeps them together); with limit only once the units judged to pass before and the units whose rows all pass in the rounds since (at least as many as the units that pass) reach limit, the next files then chosen by the units judged. The lines of the rounds not judged are judged at the end. The rounds stop when enough units pass (limit in all, each source counted up to sample; else sample for every source) or no file is left, so a file is read only when the units of the files before it were not enough. bar (step_bar) counts the files read. -> (the paths read, in the order read; the number of rounds).""" rel = {p: p[len(root) + 1:] for ps in by_source.values() for p in ps} waiting(bar, con, con.execute, file_keys_sql(root, f"SELECT unnest({file_list(sorted(set(rel.values())))}) AS f")) key = {p: file_key(r) for p, r in rel.items()} mine = {s: sorted(ps, key=key.__getitem__) for s, ps in by_source.items()} turn = {s: source_turn(s) for s in mine} done: list = [] seen: set = set() # {source: its units that pass, as last judged}, and with limit {source: its units whose rows all pass in the # rounds since} kept: dict = {} since: dict = {} rounds = 0 stale = False while True: if limit is not None: nxt = turn_files(mine, seen, {s: kept.get(s, 0) + since.get(s, 0) for s in mine}, turn, limit, sample) if not nxt and stale: for q in judge: waiting(bar, con, con.execute, q) kept = {str(s): int(n) for s, n in con.execute( "SELECT source, count(*) FROM fetch_units WHERE fail IS NULL GROUP BY source").fetchall()} since, stale = {}, False continue else: short = {s for s in mine if sample is None or kept.get(s, 0) < sample} nxt = sorted({next((p for p in mine[s] if p not in seen), "") for s in short} - {""}, key=key.__getitem__) if not nxt: break part = f"fetch_p{rounds}" waiting(bar, con, con.execute, f"CREATE OR REPLACE {'TABLE' if local else 'VIEW'} {part} AS {rows(nxt)}") waiting(bar, con, con.execute, f"CREATE OR REPLACE VIEW p0 AS SELECT * FROM {part}") waiting(bar, con, complete_rows, con) waiting(bar, con, con.execute, f"CREATE OR REPLACE TEMP TABLE fetch_new AS {cand}") waiting(bar, con, con.execute, "INSERT INTO fetch_read SELECT * FROM fetch_new" if rounds else "CREATE OR REPLACE TEMP TABLE fetch_read AS SELECT * FROM fetch_new") passing = con.execute("SELECT count(*) FILTER (WHERE fail IS NULL) FROM fetch_new").fetchone()[0] done += nxt seen.update(nxt) rounds += 1 bar.update(len(nxt)) stale = True if limit is not None: for s, n in con.execute( "SELECT source, count(*) FROM (SELECT source, unit FROM fetch_new WHERE unit IS NOT NULL " "GROUP BY source, unit HAVING max(fail) IS NULL) GROUP BY source").fetchall(): since[str(s)] = since.get(str(s), 0) + int(n) elif passing: for q in judge: waiting(bar, con, con.execute, q) kept = {str(s): int(n) for s, n in con.execute( "SELECT source, count(*) FROM fetch_units WHERE fail IS NULL GROUP BY source").fetchall()} stale = False if stale: for q in judge: waiting(bar, con, con.execute, q) return done, rounds def picked_rows(con, root: str, rows, read: list, rounds: int, local: bool) -> None: """#2035: view p over what fetch_rows (rows_steps) takes whole after read_units read the data files read (full paths under root) in rounds and the units were picked (pick_steps): when local, the tables fetch_p of its rounds, held in memory; else rows (table_rows) of the files read that hold a row of fetch_pick, read again, and of no other file.""" if local: con.execute("CREATE OR REPLACE VIEW p0 AS " + " UNION ALL BY NAME ".join(f"SELECT * FROM fetch_p{i}" for i in range(rounds))) else: need = [str(r[0]) for r in con.execute( f"SELECT f FROM (SELECT unnest({file_list(read)}) AS f) WHERE {row_file_sql(root, 'f')} IN " "(SELECT row_file FROM fetch_pick) ORDER BY f").fetchall()] con.execute(f"CREATE OR REPLACE VIEW p0 AS {rows(need)}") complete_rows(con) def part_query(lo: str = "", hi: str = "") -> str: """The rows of fetch_rows whose fetch_key lies in [lo, hi) (an empty bound is open), in fetch order. The rows of a unit share its key, so they come together.""" where = [f"p.fetch_key >= {sql_str(lo)}"] if lo else [] where += [f"p.fetch_key < {sql_str(hi)}"] if hi else [] return ("SELECT * EXCLUDE (fetch_key, fetch_source_file) FROM fetch_rows p" + ("\nWHERE " + " AND ".join(where) if where else "") + "\nORDER BY p.fetch_key, p.row_file, p.row_index") def part_queries(con, memory_limit: str) -> list: """Queries that return fetch_rows in fetch order, split into key ranges so that each range holds at most PART_SHARE of the memory limit (the fetch key is a hex SHA-256, so equal ranges of its first four digits hold about equal numbers of rows). Sizes are the bytes of the text and binary values plus 8 for any other value.""" lens = [] for name, typ, *_ in con.execute("DESCRIBE fetch_rows").fetchall(): col = '"' + name.replace('"', '""') + '"' lens.append(f"coalesce(strlen({col}), 0)" if typ == "VARCHAR" else f"coalesce(octet_length({col}), 0)" if typ == "BLOB" else "8") total = con.execute(f"SELECT coalesce(sum({' + '.join(lens)}), 0) FROM fetch_rows").fetchone()[0] budget = max(1, int((memory_bytes(memory_limit) or MEMORY_CAP) * PART_SHARE)) n = max(1, min(1 << 16, -(-int(total) // budget))) bounds = ["" if i in (0, n) else format(i * (1 << 16) // n, "04x") for i in range(n + 1)] return [part_query(bounds[i], bounds[i + 1]) for i in range(n)] def is_remote(root: str) -> bool: return "://" in root HF_DATASETS = "hf://datasets/" # a tag or branch name, or (#1779) a pull request's ref refs/pr/, read before it is merged by the publish job's audit REF_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}|refs/pr/[1-9][0-9]{0,9}") def repo_revision(repo: str, *, token: str | None = None, timeout: float = 30, ref: str = "main") -> str: """The commit a branch or tag of the dataset repo (ref, default main) points to now (huggingface_hub's repo_info, field sha). The token (or huggingface_hub's own, HF_TOKEN first, when none is given) is sent when there is one.""" from huggingface_hub import HfApi if not REF_RE.fullmatch(ref) or ".." in ref: raise ValueError(f"not a branch or tag name: {ref[:60]!r}") sha = str(HfApi().repo_info(repo, repo_type="dataset", revision=ref, timeout=timeout, token=token).sha or "") if not re.fullmatch(r"[0-9a-f]{40}", sha): raise ValueError(f"the Hub API gave no commit for {repo}") return sha def pin_root(root: str, *, revision=None, warn=None, ref_ok: bool = False) -> str: """hf://datasets//[/...] -> the same root at the current commit, hf://datasets//@ [/...] (DuckDB reads hf:// paths at a revision given after @), so every file of a long query comes from one commit even when the repo gets new commits meanwhile. A root that already names a revision, and any other root, is returned as it is. When the commit cannot be read the root is returned as it is (the main branch is read) and warn gets one line saying why.""" root = root.rstrip("/") if not root.startswith(HF_DATASETS): return root parts = root[len(HF_DATASETS):].split("/", 2) if len(parts) < 2 or not all(parts[:2]) or "@" in parts[0] or "@" in parts[1]: return root repo = f"{parts[0]}/{parts[1]}" try: sha = str((revision or repo_revision)(repo) or "") if not (re.fullmatch(r"[0-9a-f]{40}", sha) or (ref_ok and REF_RE.fullmatch(sha) and ".." not in sha)): raise ValueError(f"not a commit id: {sha[:60]!r}") except Exception as e: # noqa: BLE001 any failure falls back to main (warn or _stderr)(f"could not read the current commit of {repo} ({type(e).__name__}: {e}); reading the " f"main branch, which can change while the query runs") return root return f"{HF_DATASETS}{repo}@{sha}" + (f"/{parts[2]}" if len(parts) > 2 else "") def _stderr(msg: str) -> None: print(f"warning: {msg}", file=sys.stderr) DUCKDB_MAX_TEMP = "100GB" def max_temp_size() -> str: return os.environ.get("DUCKDB_MAX_TEMP") or DUCKDB_MAX_TEMP def _cgroup_limit() -> int | None: """The memory limit of this process's cgroup (v2 memory.max, else v1 memory.limit_in_bytes), when one is set.""" for p in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"): try: v = Path(p).read_text().strip() except OSError: continue if v.isdigit() and int(v) < 1 << 60: return int(v) return None def default_memory_limit() -> str: """The DuckDB memory limit used when --memory-limit is not given: the smaller of MEMORY_CAP and a quarter of the memory this process may use (physical memory, or the cgroup limit when lower; MEMORY_CAP when neither can be read). DuckDB's own default is 80% of physical memory; a selection over a large local copy (a sort over every data file) then grows towards that instead of spilling to the temporary directory.""" try: total = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") except (AttributeError, ValueError, OSError): total = 0 cg = _cgroup_limit() if cg is not None: total = min(total, cg) if total > 0 else cg limit = min(MEMORY_CAP, total // 4) if total > 0 else MEMORY_CAP return f"{max(limit >> 20, 256)}MiB" def memory_bytes(limit: str): """A memory size such as 4GB, 512MiB or 8 GiB in bytes (GB = 1000^3, GiB = 1024^3, as DuckDB reads them); None for anything else.""" m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*(?:([KMGT])(i?)B?)?\s*B?\s*", str(limit or ""), re.I) if not m: return None unit = (1024 if m.group(3) else 1000) ** " KMGT".index((m.group(2) or " ").upper()) return int(float(m.group(1)) * unit) def default_threads(memory_limit: str): """DuckDB threads for a memory limit: one per THREAD_MEMORY of it, at least 1, at most the CPU count (None when the limit cannot be read: DuckDB's own default then).""" n = memory_bytes(memory_limit) return None if n is None else max(1, min(os.cpu_count() or 1, n // THREAD_MEMORY)) def http_settings(con, threads: int = REMOTE_THREADS) -> None: """Retries, backoff and timeout for network reads (HTTP_SETTINGS), and fewer threads. A setting this DuckDB does not know is skipped with a note on stderr.""" for key, value in [*HTTP_SETTINGS.items(), ("threads", threads)]: try: con.execute(f"SET {key} = {int(value)}") except Exception as e: # noqa: BLE001 (an older DuckDB, or the httpfs extension could not be loaded) print(f"note: could not set {key}: {type(e).__name__}: {str(e).splitlines()[0][:200]}", file=sys.stderr) def duckdb_proxy_sql(proxy) -> list: """The DuckDB settings that send its http(s):// and hf:// reads through proxy (an http:// proxy, with its user name and password). DuckDB has no SOCKS support: a socks proxy raises ValueError.""" if not proxy: return [] u = urllib.parse.urlsplit(proxy) if u.scheme.lower().startswith("socks"): raise ValueError(f"DuckDB cannot read through a SOCKS proxy ({redact_proxy(proxy)}): the table reads would " f"go out directly. Use an http:// proxy, or download the tables first and pass the copy " f"with --data") if u.scheme.lower() not in ("http", "https") or not u.hostname: raise ValueError(f"not a proxy address: {redact_proxy(proxy)}") hp = u.hostname + (f":{u.port}" if u.port else "") out = [f"SET http_proxy = {sql_str(hp)}"] if u.username: out.append(f"SET http_proxy_username = {sql_str(urllib.parse.unquote(u.username))}") if u.password: out.append(f"SET http_proxy_password = {sql_str(urllib.parse.unquote(u.password))}") return out def connect(memory_limit: str | None = None, temp_dir: str | None = None, settings: dict | None = None, *, remote: bool = False, token: str | None = None, proxy: str | None = None): """A DuckDB connection. remote: the tables are read over the network (see HTTP_SETTINGS). token: the Hugging Face token to read with; without one the HF_TOKEN environment variable is used when set.""" try: import duckdb except ImportError: sys.exit("fetch.py needs the duckdb package: pip install duckdb") con = duckdb.connect() merged = {"max_temp_directory_size": max_temp_size(), **(settings or {})} for key, value in merged.items(): con.execute(f"SET {key} = {sql_str(value)}") if memory_limit: con.execute(f"SET memory_limit = {sql_str(memory_limit)}") if temp_dir: con.execute(f"SET temp_directory = {sql_str(temp_dir)}") setup = [] if remote: con.execute("CALL enable_logging('HTTP', storage_buffer_size = 0)") # #2177: hub_requests reads it http_settings(con) for key, value in HTTP_SETTINGS.items(): setup.append(f"SET {key} = {int(value)}") for q in duckdb_proxy_sql(proxy): con.execute(q) setup.append(q) token = token or os.environ.get("HF_TOKEN") if token: try: con.execute(f"CREATE SECRET hf_token (TYPE huggingface, TOKEN {sql_str(token)})") except Exception as e: # noqa: BLE001 (keep the token out of the message) raise RuntimeError(f"could not register the Hugging Face token: {type(e).__name__}: " f"{str(e).replace(token, '***')}") from None _SETUP[id(con)] = [q for q in setup if _settable(con, q)] return con def hub_class(url) -> str | None: """#2177: the class Hugging Face counts a request to url under: resolver (a /resolve/ URL: a file's bytes, or the HEAD that asks for its size), api (/api/) or other, for a URL of HUB_HOST; None for another host (an upstream site, or the storage a /resolve/ URL redirects to).""" u = urllib.parse.urlsplit(str(url)) if (u.hostname or "").lower() != HUB_HOST: return None return "resolver" if "/resolve/" in u.path else "api" if u.path.startswith("/api/") else "other" def count_sent(url) -> None: """#2177: one request to url, counted in HUB_SENT by its class (hub_class).""" k = hub_class(url) if k is not None: HUB_SENT[k] += 1 def hub_requests(con, remote: bool) -> dict: """#2177: the requests this run sent to the Hub, by class (hub_class): those of HUB_SENT and, for a remote read, those DuckDB's own HTTP log holds (connect enables it). -> {resolver, api, other}.""" out = dict(HUB_SENT) if remote: for (url,) in con.execute("SELECT request.url FROM duckdb_logs_parsed('HTTP')").fetchall(): k = hub_class(url) if k is not None: out[k] += 1 return out def _settable(con, q: str) -> bool: """False for a setting this DuckDB does not know (http_settings already said so), so cursors skip it.""" try: con.cursor().execute(q).close() except Exception: # noqa: BLE001 return False return True def load_specs(con, root: str) -> dict: text = con.execute(f"SELECT content FROM read_text({sql_str(root + '/meta/sources.json')})").fetchone()[0] return {s["source"]: s["layout"] for s in json.loads(text)["sources"]} # ---------- one table row -> the full pointer ---------- def derive_pid(rule, source, collection, uri, offset): if not rule or not isinstance(source, str) or not isinstance(collection, str) or not isinstance(uri, str): return None tail = "/".join(uri.split("/")[-int(rule["segments"]):]) if rule.get("at_offset"): if not (isinstance(offset, int) and not isinstance(offset, bool)): return None tail += f"@{offset}" return f"{source}:{collection}:{tail}" def member_pid(source, collection, parent, member): if not all(isinstance(v, str) for v in (source, collection, parent, member)) or parent.count(":") < 2: return None return f"{source}:{collection}:{parent.split(':', 2)[2]}!/{member}" def derive_alts(rule, uri): if not rule or not isinstance(uri, str): return None out = [] for f, t, suf in rule["pairs"]: if not uri.startswith(f): return None out.append(t + uri[len(f):] + suf) return out def derive_hash(seg, uri): if not isinstance(uri, str): return None parts = uri.split("/") k, j = seg if k > len(parts): return None return "".join(parts[-k:len(parts) - j]) def unswap(rule, stored): f, t, suf = rule["pairs"][0] if not isinstance(stored, str) or not stored.startswith(t) or not stored.endswith(suf) \ or len(stored) < len(t) + len(suf): return None return f + stored[len(t):len(stored) - len(suf)] def _hex(v): return v.hex() if isinstance(v, (bytes, bytearray)) else v def restore(col: dict, spec: dict) -> dict: """One table row (column name -> value) and the source's layout from meta/sources.json -> the full pointer.""" x = json.loads(col["extra"]) if col.get("extra") else {} if "_row" in x: return x["_row"] r = copy.deepcopy(spec["constants"]) r["source"] = col["source"] for k in ("collection", "ext", "size_bytes"): r[k] = col.get(k) arule = spec.get("alt_uris") uri = col["uri"] if arule and arule["swap"] and not x.get("_uri_orig"): r["uri"] = unswap(arule, uri) r["alt_uris"] = derive_alts(arule, r["uri"]) else: r["uri"] = uri if arule and not x.get("_uri_orig"): a = derive_alts(arule, uri) if a is not None: r["alt_uris"] = a r["hashes"] = {n: _hex(col[n]) for n, _ in HASH_COLS if col.get(n) is not None} for h, seg in (spec.get("hash_from_uri") or {}).items(): v = derive_hash(seg, r["uri"]) if v is not None: r["hashes"][h] = v for h in x.pop("_hx", []): r["hashes"].pop(h, None) r["hashes"].update(x.pop("hashes", {})) for k in ("media_type", "member_path", "parent_pointer_id"): if col.get(k) is not None: r[k] = col[k] if col.get("zip_local_header_offset") is not None: r["zip_entry"] = {k: col.get(c) for k, c in ZIP_COLS} if col.get("range_offset") is not None: r["range"] = {"offset": col["range_offset"], "length": col.get("range_length")} if col.get("origin_url") is not None: r["origin"] = {"url": col["origin_url"]} if col.get("origin_time") is not None: r["origin"]["captured_at"] = col["origin_time"] lo = {k: col[c] for c, k in LICENSE_COLS if col.get(c) is not None} if lo: r["license_override"] = lo if col.get("sensitive") is not None: r["sensitive"] = col["sensitive"] if "pointer_id" in x: pid = x.pop("pointer_id") elif "pid" in x: pid = f"{r['source']}:{r['collection']}:{x.pop('pid')}" elif col.get("parent_pointer_id") is not None and col.get("member_path") is not None: pid = member_pid(r["source"], r["collection"], col["parent_pointer_id"], col["member_path"]) else: pid = derive_pid(spec.get("pointer_id"), r["source"], r["collection"], r["uri"], col.get("range_offset")) r["pointer_id"] = pid absent = x.pop("_absent", []) x.pop("_uri_orig", None) r.update(x) if col.get("truncated") is not None: sm = dict(r.get("source_meta") or {}) sm[TRUNC_KEY] = col["truncated"] r["source_meta"] = sm for k in absent: r.pop(k, None) return r # ---------- download and verify ---------- class Unsupported(Exception): pass def to_http(uri: str): """A row's address as one this script opens: http(s) and rsync:// as they are, s3:// and hf:// as their public HTTPS forms; None for any other.""" if uri.startswith(("https://", "http://", "rsync://")): return uri if uri.startswith("s3://"): bucket, _, key = uri[5:].partition("/") return f"https://s3.amazonaws.com/{bucket}/{urllib.parse.quote(key)}" if uri.startswith("hf://datasets/"): from huggingface_hub import hf_hub_url, parse_hf_uri u = parse_hf_uri(uri) # a string parser, no request to the Hub return hf_hub_url(u.id, u.path_in_repo, repo_type=u.type, revision=u.revision) return None def candidates(row: dict) -> list: out = [] for u in [row.get("uri"), *(row.get("alt_uris") or [])]: h = to_http(u) if isinstance(u, str) else None if h and h not in out: out.append(h) first = to_http(row["uri"]) if isinstance(row.get("uri"), str) else None if str(row.get("uri")).startswith("s3://") and first in out and len(out) > 1: out.remove(first) out.append(first) return out class UnsafePath(ValueError): """A row whose file would be written outside --out (or through a symbolic link); nothing is written for it.""" def _safe_parts(value, what: str) -> list: """One path value of a row (pointer_id tail, source or collection) as safe path parts: backslashes count as separators, empty and . parts are dropped, a .. part or a NUL character refuses the row.""" s = str(value) if "\0" in s: raise UnsafePath(f"unsafe {what}: contains a NUL character") parts = [p for p in s.replace("\\", "/").split("/") if p not in ("", ".")] if not parts or ".." in parts or any(re.fullmatch(r"[A-Za-z]:", p) for p in parts[:1]): raise UnsafePath(f"unsafe {what}: {s[:200]!r}") return parts def dest_path(root: Path, row: dict) -> Path: """Where the row's file is written: / when the run planned its place in the layout (layout_parts), else ///. Every segment is cleaned the same way (_safe_parts) and the resolved path must lie inside root; a path that leaves root (also through a symbolic link already on disk) raises UnsafePath.""" if row.get("_dest_parts"): parts = [x for p in row["_dest_parts"] for x in _safe_parts(p, "path part")] return _inside(root, parts) pid = row.get("pointer_id") if isinstance(pid, str) and pid.count(":") >= 2: rel = pid.split(":", 2)[2] else: rel = _pid_fallback(row) parts = (_safe_parts(row.get("source"), "source") + _safe_parts(row.get("collection"), "collection") + _safe_parts(rel, "relative path")) return _inside(root, parts) def _pid_fallback(row: dict) -> str: key = "\0".join(str(row.get(k)) for k in ("source", "uri", "range", "member_path")) return hashlib.sha256(key.encode("utf-8")).hexdigest()[:24] def _inside(root: Path, parts: list) -> Path: dest = Path(root, *parts) top = Path(root).resolve() want = top.joinpath(*parts) real = want.resolve() if top not in real.parents: raise UnsafePath(f"unsafe path: {dest} is outside {root}") if real != want: raise UnsafePath(f"unsafe path: {dest} goes through a symbolic link") return dest class Hasher: def __init__(self, size): self.h = {n: hashlib.new(n) for n in ("md5", "sha1", "sha256", "sha512")} self.git = hashlib.sha1(f"blob {size}\0".encode()) if size is not None else None self.crc = 0 self.n = 0 def update(self, b: bytes) -> None: for h in self.h.values(): h.update(b) if self.git is not None: self.git.update(b) self.crc = zlib.crc32(b, self.crc) self.n += len(b) def digests(self) -> dict: out = {n: h.hexdigest() for n, h in self.h.items()} out["git_blob_sha1"] = self.git.hexdigest() if self.git else "" out["crc32"] = f"{self.crc & 0xFFFFFFFF:08x}" return out def _etag_md5(etag): if not etag: return None e = str(etag).strip().strip('"').replace(""", "") return e if len(e) == 32 and all(c in "0123456789abcdef" for c in e) else None CHECKED_HASHES = ("crc32", "md5", "sha1", "sha256", "sha512", "git_blob_sha1") # hash names that describe something other than the bytes written (or carry no value to compare) NOT_CONTENT_HASHES = frozenset({"etag", "hash_source", "algorithm", "scope"}) SIZE, HASH, UNCHECKED = "size", "hash", "unchecked" # what a failed check found: Mismatch.kind class Mismatch(str): """The reason the check of a row's bytes failed, with what failed: kind SIZE (got: the size found), HASH (a hash, a CRC32, a fingerprint or a manifest digest) or UNCHECKED (nothing the row publishes can be checked). A failed manifest line whose reason is one carries them as check and got_bytes (_fetch_one); it is written as its text.""" kind: str got: int | None def __new__(cls, text: str, kind: str, got: int | None = None) -> "Mismatch": s = super().__new__(cls, text) s.kind, s.got = kind, got return s def prefixed(self, prefix: str) -> "Mismatch": return Mismatch(prefix + self, self.kind, self.got) def _want_hash(name: str, value) -> str: if name == "crc32" and isinstance(value, int): return f"{value & 0xFFFFFFFF:08x}" v = str(value or "").strip().lower() return v.zfill(8) if name == "crc32" and v and len(v) < 8 else v def check_hashes(hashes: dict, got: dict, names=CHECKED_HASHES): """Compare every hash the row publishes with the computed digests: crc32, md5, sha1, sha256, sha512, git_blob_sha1 and a single-part etag (an md5). -> (Mismatch or None, number checked).""" checked = 0 for name in names: want = _want_hash(name, (hashes or {}).get(name)) if want: checked += 1 if not got.get(name) or got[name] != want: return Mismatch(f"{name} differs: expected {want}, got {got.get(name) or '(not computable)'}", HASH), checked et = _etag_md5((hashes or {}).get("etag")) if et: checked += 1 if got["md5"] != et: return Mismatch(f"etag (single-part md5) differs: expected {et}, got {got['md5']}", HASH), checked return None, checked def unchecked_hashes(row: dict) -> list: """The names of hashes the row publishes that this tool cannot compute (recorded in the manifest).""" return sorted(k for k, v in (row.get("hashes") or {}).items() if v and k not in CHECKED_HASHES and k not in NOT_CONTENT_HASHES) def verify(row: dict, size: int, got: dict, names=CHECKED_HASHES): """None when the size and every published hash match, otherwise the reason (a Mismatch).""" if row.get("size_bytes") is not None and size != row["size_bytes"]: return Mismatch(f"size differs: expected {row['size_bytes']}, got {size}", SIZE, size) hashes = row.get("hashes") or {} if not hashes and row.get("hash_source") == "computed_on_fetch": return None why, checked = check_hashes(hashes, got, names) if why: return why return None if checked else Mismatch("no hash that can be checked", UNCHECKED) def is_rolling(row: dict) -> bool: """True for a file the source regenerates in place (ROLLING_FILES, or source_meta.rolling on the row).""" sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {} return bool(sm.get("rolling")) or (row.get("source"), row.get("collection")) in ROLLING_FILES def no_hash_fields(row: dict, res: dict, sha256: str, note: str) -> dict: """The manifest fields of a row without hashes: unverified, the computed sha256, and checked "size only" when its size was checked.""" if row.get("hashes"): return res res["unverified"] = note res["sha256"] = sha256 if row.get("size_bytes") is not None: res["checked"] = SIZE_ONLY return res def range_header(rng) -> str: """rng is (offset, length); offset None asks for the last length bytes.""" if rng[0] is None: return f"bytes=-{rng[1]}" return f"bytes={rng[0]}-{rng[0] + rng[1] - 1}" PROXY_SCHEMES = ("http", "https", "socks5", "socks5h", "socks4", "socks4a") def redact_proxy(proxy: str) -> str: """A proxy address without its user name and password (for messages).""" u = urllib.parse.urlsplit(proxy or "") if not u.hostname: return str(proxy) return u._replace(netloc=u.hostname + (f":{u.port}" if u.port else "")).geturl() def env_proxy(env=None): """The proxy named by the environment: HTTPS_PROXY, then HTTP_PROXY, then ALL_PROXY (either case).""" env = os.environ if env is None else env for k in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"): if env.get(k): return env[k] return None RETRY_STATUS = (429, 500, 502, 503, 504) def make_session(proxy=None, retry_status=RETRY_STATUS): """The requests session every download uses: urllib3 Retry retries connection errors and retry_status answers (RETRY_STATUS) RETRIES more times, BACKOFF seconds doubling in between (or as long as a Retry-After header asks); plus proxy (an http://, https://, socks5://, socks5h://, socks4:// or socks4a:// address, SOCKS through requests[socks]) when given. proxy None means a direct connection.""" ses = requests.Session() ses.trust_env = False ses.hooks["response"].append(lambda r, **kw: count_sent(r.url)) # each answer, a redirect's included adapter = HTTPAdapter(max_retries=Retry( total=RETRIES, backoff_factor=BACKOFF, status_forcelist=retry_status, respect_retry_after_header=True, raise_on_status=False)) ses.mount("https://", adapter) ses.mount("http://", adapter) if proxy: if urllib.parse.urlsplit(proxy).scheme.lower() not in PROXY_SCHEMES: raise SystemExit(f"error: unsupported proxy {redact_proxy(proxy)}; use one of " + ", ".join(s + "://" for s in PROXY_SCHEMES)) ses.proxies = {"http": proxy, "https": proxy} return ses class _Net: """The network set_network configured: the sessions open_url uses (sec_session for sec.gov, which retries no 429: SEC_STOP_CODES), the User-Agent, the --contact address and the proxy.""" session: requests.Session | None = None sec_session: requests.Session | None = None ua: str = UA contact: str | None = None proxy: str | None = None _NET = _Net() def user_agent(contact=None) -> str: """The User-Agent sent: UA, or with --contact the same product name and the caller's own contact.""" return f"{UA} (contact: {contact})" if contact else UA def set_network(proxy=None, contact=None) -> requests.Session: """Configure the proxy and the User-Agent (with the --contact address) that open_url and remote_file use.""" ses = make_session(proxy) _NET.session, _NET.ua, _NET.contact, _NET.proxy = ses, user_agent(contact), contact or None, proxy _NET.sec_session = make_session(proxy, SEC_RETRY_STATUS) return ses def net_session(sec: bool = False) -> requests.Session: """The session set_network configured (sec: the one for sec.gov); configured from the environment's proxy when nothing called it yet.""" if _NET.session is None: set_network(env_proxy()) return _NET.sec_session if sec else _NET.session # Hosts this script paces itself, seconds between two request starts: sec.gov (SEC EDGAR asks for at most 10 requests # a second per user; is_sec) and Docker Hub's registry and token service (the collector's pace, at most one a second) SEC_MIN_INTERVAL = 1.0 HOST_INTERVALS = {"registry-1.docker.io": 1.0, "auth.docker.io": 1.0} # after one of these from sec.gov, or from a container registry for its manifests (fetch_registry_manifest), this run # sends that host no more requests: the rows of it fail with the reason (block_host) SEC_STOP_CODES = (401, 403, 429) SEC_RETRY_STATUS = (500, 502, 503, 504) _BLOCKED: dict = {} # host -> why it refused _LIMITERS: dict = {} # (host, milliseconds) -> pyrate-limiter Limiter _LIMITERS_LOCK = threading.Lock() def pace(host: str, min_interval: float) -> None: """Wait until host may get one more request, at most one per min_interval seconds in this process: a pyrate-limiter Limiter at Rate(1, min_interval) per host; no wait for 0 or no host.""" ms = int(round(min_interval * 1000)) if ms <= 0 or not host: return with _LIMITERS_LOCK: lim = _LIMITERS.get((host, ms)) if lim is None: lim = _LIMITERS[(host, ms)] = Limiter(Rate(1, ms)) lim.try_acquire(host) def is_sec(url: str) -> bool: host = (urllib.parse.urlsplit(url).hostname or "").lower() return host == "sec.gov" or host.endswith(".sec.gov") def sec_user_agent() -> str: """The User-Agent sent to sec.gov, which asks every client to declare who it is: the one with the --contact address; without one, no request is sent to it (Unsupported).""" if not _NET.contact: raise Unsupported("sec.gov asks every client to declare who it is: give --contact ; no request " "sent to sec.gov") return _NET.ua def block_host(host: str, why: str) -> None: _BLOCKED[host.lower()] = why def check_blocked(url: str) -> None: """Raise Unsupported for an address whose host refused this run (block_host).""" host = (urllib.parse.urlsplit(url).hostname or "").lower() if host in _BLOCKED: raise Unsupported(f"{host} refused this run earlier ({_BLOCKED[host]}); no more requests sent to it") HDX_HOST = "data.humdata.org" def hdx_pending(url: str, status: int) -> bool: """#1635: data.humdata.org answers 202 Accepted with an empty body for a resource download it has not got ready, and that body read as the file is 0 bytes (an hdx unit was once stored with 0 of its 64,763 bytes). Such an answer is a failure of the moment there, raised as an HTTP error 202 (open_url); a 202 of another host is the file.""" return status == 202 and (urllib.parse.urlsplit(url).hostname or "").lower() == HDX_HOST def open_url(url: str, timeout: float, rng=None, headers=None): """rng is (offset, length), offset None for the last length bytes. HTTP gets a Range header and must answer 206. headers are extra request headers. Only http(s) addresses are opened; a local --data copy is read through local_file_opener, never through an address. sec.gov gets the User-Agent with --contact (sec_user_agent), and a host of HOST_INTERVALS or sec.gov its pace (pace). -> the undecoded response body (urllib3), with status and headers.""" if not url.startswith(("https://", "http://")): raise Unsupported(f"only http(s) addresses are fetched, not {url.split(':', 1)[0][:20]}://") sec = is_sec(url) check_blocked(url) ses = net_session(sec) # the body is read undecoded (r.raw), so no content coding is asked for: requests sends Accept-Encoding gzip by # default, and a server that compresses a text file would hand back bytes whose size and hash are not the file's # (the channel's streams do the same, channel.Http._call) headers = {"User-Agent": sec_user_agent() if sec else _NET.ua, "Accept-Encoding": "identity", **(headers or {})} if rng: headers["Range"] = range_header(rng) host = (urllib.parse.urlsplit(url).hostname or "").lower() pace(host, SEC_MIN_INTERVAL if sec else HOST_INTERVALS.get(host, 0)) r = ses.get(url, headers=headers, timeout=timeout, stream=True) try: if sec and r.status_code in SEC_STOP_CODES: block_host(host, f"HTTP {r.status_code}") r.raise_for_status() if hdx_pending(url, r.status_code): raise requests.HTTPError(f"202 Accepted: the file is not ready yet ({HDX_HOST})", response=r) if rng and r.status_code != 206: raise Unsupported(f"the server ignored the Range request (HTTP {r.status_code})") except BaseException: r.close() raise return r.raw def http_error_of(e: BaseException) -> tuple: """(status code, headers) of an HTTP error answer an opener raised (requests' HTTPError, urllib's HTTPError); (None, None) for anything else.""" if isinstance(e, requests.HTTPError) and e.response is not None: return e.response.status_code, e.response.headers if isinstance(e, urllib.error.HTTPError): return e.code, e.headers return None, None NET_ERRORS = (requests.ConnectionError, requests.Timeout, requests.exceptions.ChunkedEncodingError, urllib3.exceptions.HTTPError, urllib.error.URLError, http.client.HTTPException, ConnectionError, TimeoutError) def failure_fields(e: BaseException) -> dict: """What an address that raised says about the row, for its manifest line: http_status (the answer's HTTP status), network (no HTTP answer: a connection, timeout or transfer failure, a git or rsync failure) and blocked (a git host asked for a login).""" code, _ = http_error_of(e) if code is not None: return {"http_status": code} out = {} if isinstance(e, NET_ERRORS + (GitError,)): out["network"] = True if isinstance(e, GitError) and e.blocked: out["blocked"] = True return out class RangeIgnored(Unsupported): """A server answered a byte-range request of a remote file with the whole file (HTTP 200).""" async def _range_honoured(resp) -> None: """aiohttp raise_for_status hook of remote_file: fsspec's HTTPFile takes a 200 answer to a Range request as the range when its Content-Length is no more than the range (async_fetch_range in fsspec/implementations/http.py), and reads the whole body for a range at offset 0; such an answer fails here instead.""" if resp.status == 200 and "Range" in resp.request_info.headers: raise RangeIgnored(f"the server ignored the Range request of {resp.url.host} (HTTP 200)") def remote_source(row: dict, url: str) -> str: """What remote_file reads for the row at url: the row's hf:// address whose HTTPS form is url (alt_uris included), the local copy when url is the row's _local_file, else url.""" if row.get("_local_file") == url: return url for u in [row.get("uri"), *(row.get("alt_uris") or [])]: if isinstance(u, str) and u.startswith("hf://") and to_http(u) == url: return u return url def remote_file(src: str, timeout: float, block_size: int): """A seekable read-only file over src (see remote_source), read by byte ranges of block_size: huggingface_hub's HfFileSystem for an hf:// address, the file itself for a local copy, else fsspec's HTTPFile with the proxy and User-Agent of set_network. A server that ignores the byte ranges fails the read (RangeIgnored); fsspec has no SOCKS client, so a SOCKS proxy fails the row (Unsupported).""" if src.startswith("hf://"): from huggingface_hub import HfFileSystem return HfFileSystem().open(src, "rb", block_size=block_size) if not src.startswith(("https://", "http://")): return open(src, "rb") import aiohttp import fsspec net_session() proxy = _NET.proxy if proxy and urllib.parse.urlsplit(proxy).scheme.lower().startswith("socks"): raise Unsupported("archive members are read by byte ranges through fsspec, which cannot use a SOCKS proxy") fs = fsspec.filesystem("http", skip_instance_cache=True, **({"proxy": proxy} if proxy else {}), client_kwargs={ "raise_for_status": _range_honoured, "headers": {"User-Agent": _NET.ua}, "timeout": aiohttp.ClientTimeout(sock_connect=timeout, sock_read=timeout)}) return fs.open(src, "rb", block_size=block_size) def local_file_opener(path): """An opener for one file of the local --data copy (a repository file a campaign row names). It ignores the address and reads only that file; index rows cannot name local files, only resolve_repo_uri sets this up.""" def op(url, timeout, rng=None, headers=None): f = open(path, "rb") if not rng: return f with f: if rng[0] is None: f.seek(0, 2) f.seek(max(0, f.tell() - rng[1])) else: f.seek(rng[0]) return io.BytesIO(f.read(rng[1])) return op def transient(e: BaseException) -> bool: if isinstance(e, requests.HTTPError): return 500 <= e.response.status_code < 600 return isinstance(e, (requests.ConnectionError, requests.Timeout, urllib3.exceptions.HTTPError, ConnectionError, TimeoutError)) def _write(dest: Path, data: bytes) -> None: part = dest.with_name(dest.name + ".part") part.write_bytes(data) os.replace(part, dest) def _rng(row: dict): r = row.get("range") return (r["offset"], r["length"]) if isinstance(r, dict) and r.get("offset") is not None else None class TooLarge(Exception): """The item is larger than the row's cap; nothing is kept.""" def cap_of(row: dict) -> int: """The most bytes written for one row: its cap from the query (size_cap_bytes).""" v = row.get("_size_cap") return int(v) if v is not None else UNKNOWN_SIZE_CAP def whole_cap_of(row: dict) -> int: """The most bytes downloaded or decoded on the way to one row (a whole package, a solid 7z block, a compressed member): the larger of the row's cap and its batch cap.""" vals = [int(v) for v in (row.get("_size_cap"), row.get("_batch_cap")) if v is not None] return max(vals) if vals else UNKNOWN_SIZE_CAP def marked_rolling(row: dict) -> bool: """True for a row that says itself it is rolling (source_meta.rolling), whole file, with hashes: a size or hash that differs from the row is recorded, not a failure.""" sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {} return bool(sm.get("rolling")) and bool(row.get("hashes")) and _rng(row) is None # #2144: an answer of these types (its Content-Type) to a download of a file the row records as not HTML (by its ext, # none of HTML_EXTS, or its media_type) is a page standing where the file was: the upstream blocks scripts (a bot check # or a sign-in page). HTML_EXTS also holds the extensions of pages a server makes, which are HTML when they are fetched HTML_TYPES = ("text/html", "application/xhtml+xml") HTML_EXTS = ("html", "htm", "xhtml", "shtml", "php", "asp", "aspx", "jsp", "cgi") HTML_HEAD = 1 << 16 # the first bytes of an answer kept to read a page's title def html_page(row: dict, content_type: str, head: bytes) -> dict | None: """#2144: the page an upstream answered with in place of the row's file when it blocks scripts: an answer whose Content-Type (content_type) is one of HTML_TYPES to a download of a file that the row records as not HTML (an ext not among HTML_EXTS, or a media_type not among HTML_TYPES; a row that records neither says nothing of it) -> {content_type, title: the page's title, read from its first bytes head by _text_of}; None otherwise. fetch_file asks only of bytes that failed the row's check.""" kind = content_type.split(";", 1)[0].strip().lower() ext = str(row.get("ext") or "").lower().lstrip(".") media = str(row.get("media_type") or "").split(";", 1)[0].strip().lower() if kind not in HTML_TYPES or not (ext or media) or ext in HTML_EXTS or media in HTML_TYPES: return None return {"content_type": kind, "title": _text_of(head)[0][:120]} def blocked_words(page: dict) -> str: """#2144: html_page in words, for the line of a file whose upstream answered with it.""" title = f' ("{page["title"]}")' if page.get("title") else "" return f"the upstream answered with an HTML page{title} in place of the file: it blocks scripts such as this one" def fetch_file(row, dest, url, timeout, opener): want = row.get("size_bytes") rolling = want is not None and not row.get("hashes") and _rng(row) is None and is_rolling(row) loose = marked_rolling(row) limit = (max(want, cap_of(row)) if want is not None else cap_of(row)) if rolling or loose \ else want if want is not None else cap_of(row) h = Hasher(want) head = bytearray() part = dest.with_name(dest.name + ".part") # a row the source stores gzip-compressed (source_meta.content_encoding gzip, such as Zuul CI logs) is asked for # with Accept-Encoding gzip and its stored gzip bytes are kept as they come: without that header some CDNs # decompress on the fly, and the bytes are no longer those of the row enc = {"Accept-Encoding": "gzip"} \ if str((row.get("source_meta") or {}).get("content_encoding") or "").lower() == "gzip" else {} # a whole file of known size resumes from the .part an interrupted download left (Range: bytes=n-); a server # that answers 200 instead of 206 sends the whole file, which then starts over resumable = _rng(row) is None and want is not None and not rolling and not loose have = part.stat().st_size if resumable and part.is_file() and not part.is_symlink() else 0 if not 0 < have < (want or 0): have = 0 try: if have: src = opener(url, timeout, None, headers={"Range": f"bytes={have}-", **enc}) status = getattr(src, "status", None) or getattr(src, "code", None) or 200 crange = str((getattr(src, "headers", None) or {}).get("Content-Range") or "") cr = parse_content_range_header(crange) if status == 206 and (not cr or cr.units != "bytes" or cr.start != have): src.close() raise Unsupported(f"the server answered the resume request with Content-Range {crange[:80]!r}") if status == 206: with open(part, "rb") as old: for b in iter(lambda: old.read(CHUNK), b""): h.update(b) mode = "ab" else: mode = "wb" else: src, mode = (opener(url, timeout, _rng(row), headers=enc) if enc else opener(url, timeout, _rng(row))), "wb" content_type = str((getattr(src, "headers", None) or {}).get("Content-Type") or "") with src, open(part, mode) as out: while True: b = src.read(CHUNK) if not b: break if len(head) < HTML_HEAD: head += b[:HTML_HEAD - len(head)] h.update(b) out.write(b) if h.n > limit: break except BaseException as e: if not (resumable and transient(e) and part.is_file()): part.unlink(missing_ok=True) raise if (want is None or rolling or loose) and h.n > limit: part.unlink(missing_ok=True) raise TooLarge(f"rolling file: grew past the cap of {limit} bytes" if rolling or loose else f"unknown size: stopped after more than the cap of {limit} bytes") changed = rolling and h.n != want got = h.digests() why = verify({**row, "size_bytes": None} if changed else row, h.n, got) if why is None and not row.get("hashes") and is_gzip_row(row): why = gzip_problem(part) page = html_page(row, content_type, bytes(head)) if why or changed else None if page: part.unlink(missing_ok=True) return {"status": "failed", "reason": why or ROLLING_CHANGED, "html_page": page, "url": url, "got_bytes": h.n, "got_sha256": got["sha256"]} if loose: os.replace(part, dest) res = {"status": "ok", "path": str(dest), "bytes": h.n, "url": url, "sha256": got["sha256"], "retrieved": utc_today()} if why: res.update(differs_from_index=True, expected_bytes=want, expected_sha256=(row.get("hashes") or {}).get("sha256"), reason=why) return res if why: part.unlink(missing_ok=True) return {"status": "failed", "reason": why, "url": url, "got_bytes": h.n, "got_sha256": got["sha256"]} os.replace(part, dest) res = no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": h.n, "url": url, "sha256": got["sha256"], **({"resumed_from": have} if have and mode == "ab" else {})}, h.digests()["sha256"], "the source publishes no hash; sha256 computed on download") if changed: res["checked"] = ROLLING_CHANGED res["expected_bytes"] = want return res def is_gzip_row(row: dict) -> bool: return row.get("media_type") == "application/gzip" or row.get("ext") == "gz" def gzip_problem(p: Path) -> str | None: """A file a row without hashes records as gzip (is_gzip_row, such as a monthly mbox.gz export) decompressed once as a stream, nothing of it kept -> None when it is whole gzip, else the reason (a cut file, a page in its place).""" try: with gzip.open(p, "rb") as f: while f.read(CHUNK): pass except (OSError, EOFError, zlib.error) as e: return f"not valid gzip: {type(e).__name__}: {e}" return None # WARC / ARC records def gunzip_bounded(raw: bytes, limit: int) -> bytes: """Decompress gzip data (one or more members, by gzip.GzipFile) without ever holding more than limit + 1 output bytes; more output than limit raises TooLarge (a small compressed input can expand without bound).""" out = gzip.GzipFile(fileobj=io.BytesIO(raw)).read(limit + 1) if len(out) > limit: raise TooLarge(f"the data decompresses to more than the cap of {limit} bytes") return out def read_bounded(src, limit: int, what: str) -> bytes: """Read a whole response, at most limit bytes; a longer one raises TooLarge.""" raw = src.read(limit + 1) if len(raw) > limit: raise TooLarge(f"{what} is larger than the cap of {limit} bytes") return raw def parse_record(raw: bytes, limit: int | None = None) -> dict: """One WARC or ARC record (gzip or not), read by warcio (ARC turned into WARC) -> {"http_headers": lower-case name: value, "payload": the bytes after the HTTP headers, still chunked if they were sent so}. A payload over limit raises TooLarge.""" limit = UNKNOWN_SIZE_CAP if limit is None else limit rec = next(iter(ArchiveIterator(io.BytesIO(raw), arc2warc=True))) payload = rec.raw_stream.read(limit + 1) if len(payload) > limit: raise TooLarge(f"the record's payload is larger than the cap of {limit} bytes") heads = rec.http_headers.headers if rec.http_headers else [] return {"http_headers": {k.lower(): v for k, v in heads}, "payload": payload} def dechunk(body: bytes) -> bytes: return ChunkedDataReader(io.BytesIO(body)).read() def payload_variants(rec: dict) -> list: body = rec["payload"] if "chunked" in rec["http_headers"].get("transfer-encoding", "").lower(): return [("dechunked_payload", dechunk(body)), ("payload", body)] return [("payload", body)] def verify_payload(row: dict, data: bytes): want = row.get("payload_size_bytes") if want is not None and len(data) != want: return Mismatch(f"payload size differs: expected {want}, got {len(data)}", SIZE, len(data)) h = Hasher(len(data)) h.update(data) why, checked = check_hashes(row.get("hashes") or {}, h.digests()) return why if why or checked else Mismatch("no hash that can be checked", UNCHECKED) def fetch_payload(row, dest, url, timeout, opener): """The record at the row's byte range; its payload (dechunked first when it was sent chunked, then as it is) is checked and written. read_bytes: the record's bytes read; content_encoding: the Content-Encoding of the record's HTTP headers, not decoded (the bytes kept are those the source's digest covers).""" if _rng(row) is None or row.get("size_bytes") is None: raise Unsupported("a WARC record row needs a byte range and a size") with opener(url, timeout, _rng(row)) as src: raw = src.read(row["size_bytes"] + 1) if len(raw) != row["size_bytes"]: return {"status": "failed", "url": url, "reason": Mismatch(f"size differs: expected {row['size_bytes']}, got {len(raw)}", SIZE, len(raw))} try: rec = parse_record(raw, whole_cap_of(row)) except TooLarge: raise except Exception as e: # noqa: BLE001 (a cut or misplaced record) return {"status": "failed", "url": url, "reason": f"cannot parse the record: {type(e).__name__}: {e}"} enc = rec["http_headers"].get("content-encoding") extra = {"content_encoding": enc} if enc else {} whys = [] for label, data in payload_variants(rec): why = verify_payload(row, data) if why is None: _write(dest, data) return {"status": "ok", "path": str(dest), "bytes": len(data), "read_bytes": len(raw), "matched_on": label, "url": url, **extra} whys.append(why.prefixed(f"{label}: ")) return {"status": "failed", "url": url, "reason": Mismatch("; ".join(whys), whys[0].kind, whys[0].got), **extra} # API responses ROOT_FIELD = "$" # api_body_field of a row whose body is the whole answer API_BODY_DECODERS = ("base64",) def extract_field(doc, path: str): """A value by dotted path (numeric parts are list indexes; ROOT_FIELD is the whole document); None when it is not there.""" if path == ROOT_FIELD: return doc cur = doc for part in path.split("."): if isinstance(cur, list) and part.isdigit(): cur = cur[int(part)] if int(part) < len(cur) else None elif isinstance(cur, dict): cur = cur.get(part) else: return None if cur is None: return None return cur def decode_body(v, decode: str) -> tuple: """A field the API gives the file's content in, encoded (source_meta.api_body_decode, such as base64 in attachments..data of Bugzilla's /rest/bug/attachment/) -> (bytes, None) or (None, the reason).""" if decode not in API_BODY_DECODERS: return None, f"unknown api_body_decode {decode!r} (only {', '.join(API_BODY_DECODERS)})" if v is None: return None, "field missing" if not isinstance(v, str): return None, f"the field is not a string ({type(v).__name__}); cannot decode it as {decode}" try: return base64.b64decode("".join(v.split()), validate=True), None except (binascii.Error, ValueError) as e: return None, f"{decode} decoding failed: {e}" def fetch_api_body(row, dest, url, timeout, opener): """The API answer at the row's uri, un-gzipped; its body is the field source_meta.api_body_field names (dotted path, default API_BODY_DEFAULT_FIELD; a non-string value as json.dumps writes it, null as ""), as UTF-8, or with ROOT_FIELD the whole answer as it came (not written again: the API's 24.60 and a rewritten 24.6 differ). Where source_meta.api_body_decode is base64, the field decoded is the body. Where source_meta.api_body_prefix is set (Gerrit's )]}' before its JSON), the answer must start with it, and it and the newline after it are left out. The body is checked and written.""" limit = whole_cap_of(row) sm = row.get("source_meta") or {} with opener(url, timeout, None) as src: raw = read_bounded(src, limit, "the API response") if raw[:2] == b"\x1f\x8b": try: raw = gunzip_bounded(raw, limit) except (zlib.error, EOFError, gzip.BadGzipFile) as e: return {"status": "failed", "url": url, "reason": f"cannot decompress the API response: {e}"} prefix = sm.get("api_body_prefix") if prefix: p = str(prefix).encode("utf-8") if not raw.startswith(p): return {"status": "failed", "url": url, "reason": f"the API response does not start with {prefix} (a sign-in page or a bot check?)"} raw = raw[len(p):] raw = raw[2:] if raw.startswith(b"\r\n") else raw[1:] if raw.startswith(b"\n") else raw try: doc = json.loads(raw.decode("utf-8")) except (UnicodeDecodeError, ValueError) as e: return {"status": "failed", "url": url, "reason": f"the API response is not JSON: {e}"} path = sm.get("api_body_field") or API_BODY_DEFAULT_FIELD decode = sm.get("api_body_decode") or None if path == ROOT_FIELD: body = raw elif decode: body, bad = decode_body(extract_field(doc, path), decode) if bad: return {"status": "failed", "url": url, "reason": f"{path}: {bad}"} else: v = extract_field(doc, path) body = ("" if v is None else v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)).encode("utf-8") h = Hasher(len(body)) h.update(body) why = verify(row, len(body), h.digests()) if why: return {"status": "failed", "url": url, "reason": why.prefixed(f"{path}: ")} _write(dest, body) return no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": len(body), "matched_on": f"api_body:{path}" + (f"+{decode}" if decode else ""), "url": url}, h.digests()["sha256"], "the source publishes no hash; sha256 computed on download") # stable regions of web pages (hash_scope html_region): a page with parts that differ on every request is checked on # the region its row names (source_meta.html_region); the collectors take the same region with these functions # (artpool's regions.py), so one piece of code defines the rule. size_bytes and the hashes cover the region (UTF-8 # bytes, lines joined by \n with one trailing \n); the whole page is written. class RegionError(ValueError): pass _CTF_HEAD = b'