Spool Index

A spool needs to know what patches it holds — their times, coordinates, and attributes — without loading their data. It keeps that metadata in a small SQLite database called the index. A directory spool saves it to disk as .dascore_index.sqlite3; an in-memory spool builds the same database in memory. Either way, the index holds only summaries and where to find each patch, never patch data.

Tables

The index splits its metadata across several tables so nothing is stored more than once. For example, a hundred files sharing a distance axis store that axis once, not a hundred times.

Table One row per What it holds
meta_data index Schema version and total patch count
sources file (or directory-format unit) Path, format, size, modification time, path attributes, and sort position
patches patch Patch identity, data type, sample count, and time/distance ranges
attrs patch Attribute values, one column per attribute name and value kind
attr_meta attribute name and value kind Which attrs column holds which attribute, and its canonical units
coord_defs distinct coordinate A summary of each unique coordinate
coord_runs run of a coordinate The segments of a coordinate with gaps in it
patch_coords coordinate on a patch Links each patch to its coordinates
coord_variants coordinate name, dtype, kind, units, and relativity How many patches have each variant

Two notes on these:

  • attrs gains columns as new attribute names appear, since nobody can list every attribute in advance. attr_meta records how to read each column.
  • coord_variants and meta_data.patch_count are running totals. Database triggers update them in the same transaction as the rows they count, so they stay exact even when something writes to the database directly. Asking an unfiltered spool for its length, or any spool for its coordinate names, is therefore just as fast on a huge archive as on a small one.

Writers also create a one-row patch_row_floor table when they first need it (see Updating the index). Because it is created on demand, older indexes work without a rebuild.

Coordinates

Each unique coordinate is stored once in coord_defs; patch_coords links it to every patch that uses it.

Matching ranges never imply matching values. Evenly spaced (range) coordinates are identified by an exact data_id computed from their values. Other coordinates get a value identity only when the file scan provides one; without it they are deduplicated by their summary, which saves storage but does not mark their values as equal. Units are part of the identity: the same length written in metres and in centimetres is two coordinates. A row stores its identity once, as def_key: fp: followed by the coordinate’s data_id for a value identity, or sum: followed by a hash of the summary otherwise, so the data_id is read back from the key rather than stored again. patch_coords is a WITHOUT ROWID table clustered on (patch_row, coord_name), so that key is stored once rather than in the table and again in an index.

A coord_defs row describes a coordinate the same way the coordinate describes itself (rule 12 of the coordinate guidelines):

  • its range, and its step if it is one grid (one list of labels, or several segments, states none);
  • how many segments it has (run_count).

Range coordinates also store their exact grid (step_numerator, step_denominator, origin_offset, and length, the sample count). is_exact marks rows that can rebuild every value of the coordinate without opening the file. Range columns are named by storage type: *_int for nanosecond times and durations, *_float for numbers, and *_str for text.

Segments and runs

A coordinate of several segments is stored as several runs, one per segment, each with its sample count, range, and step (none for a segment of labels). Segments share no grid, so a run says nothing of the samples a gap lacks; the gaps are the seams between runs. In-memory coordinates produce the same run records (dascore.utils.gaps.RunRecord) and the same code reads them, so a spool in memory and a directory of the same patches report identical gaps.

A coordinate with more than dascore.config.max_index_runs (256) segments is stored by range and segment count only, with a warning naming the file. Anything that needs its runs reads them from the file.

An index written by an older DASCore, whose schema version differs, is deleted and rebuilt when opened, since it is a cache of the files.

What else is kept

The index also keeps each numeric attribute’s and coordinate’s original dtype, and whether the scalar attributes fully describe the patch (history and the SEG-Y text header are per-patch provenance and are never stored). That lets DASCore tell which rows it can rebuild from metadata alone and which need the file opened. A coordinate whose values have no supported range form keeps its name, but you cannot select on it. {dim}_step is filled in only for evenly sampled coordinates.

Time queries

Absolute-time selections use the nanosecond time_min and time_max columns on patches, which are filled in from the coordinates when the index is written. These columns only narrow down which patches might match; the exact trim happens when a patch loads. Duration and numeric time coordinates leave them empty and, like every other coordinate, are selected through the coordinate tables.

Updating the index

The index is a cache, and the files are the truth. An update rescans new and changed files, replaces their rows in one transaction, and removes rows for deleted files. Removing a file removes its patches, attributes, and coordinate links with it. Coordinate definitions nothing uses any more may be kept for reuse.

Patch row numbers are never reused. If you keep a view of a spool across an update, patches that disappeared simply drop out of it; their old row numbers can never point at a newer file’s patch.

update(paths=...) looks only at the given files or folders. Inside them it rescans, prunes, and finds moved files, including files moved in from elsewhere. Files moved out, and changes anywhere else, wait for a full update. This also works on a brand-new index, so you can index a large archive one folder at a time. The exception is an index DASCore just rebuilt, or whose first update was interrupted: it ignores paths with a warning and scans everything once.

A directory index remembers the snap and max_shift settings it was scanned with. Open it with different settings and it rescans every file; otherwise patches load with the remembered settings.

Version checks

The index checks its schema version before writing anything:

  • Not a DASCore index, or incomplete: raises an error telling you to delete it. DASCore never tries to repair it.
  • Older schema version: rebuilt automatically from the files.
  • Newer schema version: left untouched, with an error. Upgrade DASCore, or give the older version its own index.
  • Read-only (see dc.spool’s index argument): raises on any version mismatch.

Concurrency

Many processes can read the index at once; writes take turns. Setup and updates hold the write lock for the whole transaction and wait up to 30 seconds for it. This relies on the filesystem’s locking working correctly, so network filesystems with weak locking are not supported.

Path attributes

Folder names written as key=value become attributes, hive-style. A folder name can hold several pairs separated by __. Some details:

  • The file’s own name is never parsed. A file extension looks just like the end of a value such as XX.R2D1..RAW, so there would be no way to tell them apart.
  • Paths win over files. If a path attribute and a file attribute share a name, the path’s value is used, because renaming a folder is how you correct metadata.
  • Values stay strings. They are never converted to numbers or times. Reserved and underscore-prefixed keys are skipped, the same as for file attributes.
  • They travel with the row. The parsed pairs are saved in sources.path_attrs and carried in a private _path_attrs column. Combined catalogs rewrite paths as absolute, so the pairs must be stored rather than reparsed.

Renaming a folder is cheap. During an update, a missing path and a new path with the same (mtime_ns, size_bytes) are treated as a move. (Directory-format units use their manifest signature instead.) DASCore then updates the path and its attributes in the database without opening the file. It rescans instead when the rename removes a key, since the file’s own value has to be read again, or when the match is ambiguous.

import tempfile
from pathlib import Path

import dascore as dc

root = Path(tempfile.mkdtemp())
(root / "acquisition_key=XX.R2D1..RAW" / "cable=A").mkdir(parents=True)
sub = root / "acquisition_key=XX.R2D1..RAW" / "cable=A"
dc.get_example_patch().io.write(sub / "das_file.h5", "DASDAE")

spool = dc.spool(root).update()
row = spool.get_contents().iloc[0]
assert (row["acquisition_key"], row["cable"]) == ("XX.R2D1..RAW", "A")
assert spool[0].attrs.get("cable") == "A"

# renaming a folder only rewrites metadata
sub.rename(sub.parent / "cable=B")
assert dc.spool(root).update().get_contents()["cable"].iloc[0] == "B"

Ordering

By default, patches come out in the order their sources were added, then by row: (sources.ordinal, patch_row). A replaced file keeps its place; new files go at the end. Combining spools concatenates them, and a file present in both keeps its first position but its latest metadata. In-memory spools therefore iterate in the order you built them.

Directory spools instead sort patches by time by default, with untimed patches last and ties broken by ordinal and row. Sorting by file alone can’t handle a file whose patches overlap patches in another file. This default is part of the catalog rather than a view, so the spool can still update. Calling sort(...) replaces it. After each update the indexer also renumbers file ordinals by each file’s earliest patch, with path as the tiebreak.

If a coordinate holds different kinds of values across patches, such as numbers in some and text in others, sorting groups each kind together: numbers, then text, then times.

Reading metadata cheaply

On an indexed spool:

  • spool[i] fetches just that patch’s row the first time. A second integer access on the same spool loads and caches the whole metadata table instead, so repeated lookups stay fast. An update clears the cache.
  • Forward contiguous slices are limited in SQL, so spool[:10].get_contents() is a cheap preview.
  • Regex filters, and coordinate selections that might drop rows, must still filter every row before a slice can apply.
  • split() fetches the list of patches once and reuses it for every batch. A batch can come out empty after exact filtering.

Chunk planning and full iteration still load all the metadata when they need to.

The flat table

Most spool operations work from one flat dataframe with a row per patch. It has:

  • {dim}_min, {dim}_max, and {dim}_step columns for each coordinate;
  • a dims column;
  • one column per attribute;
  • private bookkeeping columns starting with _: _patch_row, _{name}_def_key (coordinate identity), _{name}_units (units as written; the chunk planner normalizes them per dimensionality before grouping), _dtype, and _data_size.

Attributes and coordinates are separate, so an attribute can have the same name as a coordinate column, like an attribute channel_step next to a channel coordinate. When that happens, the coordinate column keeps the name, the attribute is left out with a warning, and you can still query it through _attrs.

get_contents, get_gaps, and get_coverage return a cleaned-up version made by present_columns. It applies the steps in dascore.utils.pd.PRESENTERS, each turning one private column public (_{name}_units becomes {name}_units, _dtype becomes dtype, _data_size becomes data_size). The last step drops any underscore columns that are left.

_dtype and _data_size (the number of samples) are private because chunking compares every public column to decide what can merge, and patches with different dtypes or lengths must still merge.

data_size is empty when the size isn’t known until load time: merged outputs, pieces cut from a patch, and rows trimmed by a selection. A row that is one whole, untrimmed patch keeps its size. Sample-index and non-range selections clear data_size on every row. See Spool Chunking and Spool Selection.

A patch’s origin_id and data_id are ordinary indexed attributes, so you can find a patch by id without loading it. patch_row is a reserved attribute name, so no attribute can collide with the row number. Neither id affects whether patches can merge, since every patch has its own. A merged patch gets ids built from its members’ data_ids, in order.

This check runs against the real catalog, so the description above can’t silently go stale:

import dascore as dc
from dascore.io.index.catalog import PatchCatalog

catalog = PatchCatalog.from_patches(list(dc.get_example_spool("random_das")))
df = catalog.to_df()
required = {
    "_patch_row",
    "origin_id",
    "_time_def_key",
    "_time_units",
    "_dtype",
    "_data_size",
    "dims",
    "time_min",
    "time_max",
    "time_step",
}
assert required.issubset(df.columns)

Patch identity

An in-memory spool is a set of patches: adding the same patch twice keeps one copy, and spool + spool is a union. Each patch gets an identity when it is created. Patches are immutable, so copies, deep copies, and unpickled patches share it, while any operation on a patch makes a new patch with a new identity. The identity is stored as the patch’s memorypatch:// source path, so deduplication and lookup always agree.

import copy

patch = dc.get_example_patch()

# the same patch twice is one entry
assert len(dc.spool([patch, patch])) == 1

# copies share identity
clone = copy.deepcopy(patch)
assert clone._instance_id == patch._instance_id
assert len(dc.spool([patch, clone])) == 1

# any operation makes a new patch
assert len(dc.spool([patch, patch.new()])) == 2

# the row's path leads back to the same object
cat = PatchCatalog.from_patches([patch, patch])
row = cat.to_df().iloc[0]
assert len(cat.to_df()) == 1
assert row["source_path"].startswith("memorypatch://")
assert cat.resolve_row(row.to_dict()) is patch

A patch whose dimensional coordinates have several segments is still one row; the index stores its runs, so reports and plans see the gaps.

Patches from files are identified by (base_uri, source_path, source_patch_key) and loaded through their readers. A source holding one patch is recorded with an empty source_patch_key unless the key is an HDF5 dataset path (starting with /), which is kept so a lazy read opens the dataset directly; dc.scan still reports the reader’s key. A file which grows from one patch to several therefore changes its first patch’s key.

Combining spools

spool + spool builds one catalog from both sides. Coordinate definitions are shared, a file in both keeps one entry, and paths become absolute so spools with different roots can combine. Each row then loads from the right place: in-memory patches from memory, planned outputs from their plans, and the rest from files.

Simple filters (attribute selections, slices, row lists) carry over as rows. State that exists only in Python, such as coordinate trims, sorts, and a directory’s default time order when transferring rows would scramble it, is first written into a new derived catalog, without loading any data. Each side then contributes exactly what it currently shows, in its current order. Because this makes new patches, a trimmed spool no longer deduplicates against its untrimmed source: its contents really are different.

Spool equality compares what each spool actually contains: trims are folded into the ranges, and internal details like coordinate keys are ignored. A trimmed spool therefore equals the result of combining it with an empty spool.

other = dc.get_example_patch().new()
union = dc.spool([patch]) + dc.spool([other])
assert len(union) == 2
assert len(dc.spool([patch]) + dc.spool([patch])) == 1  # same patch, one entry

# a trimmed spool contributes its trimmed contents
t = patch.get_coord("time")
trimmed = dc.spool([patch]).select(time=(t.min() + 10 * t.step, t.min() + 20 * t.step))
combined = trimmed + dc.spool([])
assert combined[0].shape == trimmed[0].shape
assert combined == trimmed

What the index does not do

The index handles metadata selection, finding candidate patches, and planning chunks, all without reading data. Ranges can’t prove which exact values fall inside a selection, so the exact coordinate selection runs again when a patch loads. Saving chunked results back into the index is not supported yet.

Version history lives in INDEX_VERSION in dascore/io/index/schema.py. Indexes from older versions are rebuilt automatically.