Skip to main content

API Reference

Python API

KernelDB

from spice_kernel_db import KernelDB

The main class. Wraps a DuckDB database and provides all scanning, lookup, and rewriting operations.

Constructor

KernelDB(
    db_path: str | Path | None = None,
    read_only: bool = False,
    kernel_roots: list[str | Path] | None = None,
)

Opens (or creates) the database at the given path. When db_path is None (the default), the path is loaded from ~/.config/spice-kernel-db/config.toml; without a config file it is ~/.local/share/spice-kernel-db/kernels.duckdb. The schema is initialized automatically (unless read_only=True).

Before 0.21.0, a database found only at the pre-0.19 default ~/.spice_kernels.duckdb was opened when no config file existed, with a FutureWarning. Since 0.21.0 it is not: if one is there and the new default is not, spice-kernel-db raises LegacyDatabaseFound naming the move command, rather than quietly starting an empty database beside it.

kernel_roots is the list of kernel roots used to guess a mission from a path. When it is None (the default) the roots are read from the configuration the first time they are needed. The resolved list is available as the db.kernel_roots property. Pass it to keep a script independent of the user’s configuration.

Set read_only=True for commands that only query the database. Several read-only connections can be open at once, but DuckDB’s file lock means none can open while another process has the database open for writing (for example during get); that raises duckdb.IOException.


Mission management

add_mission

db.add_mission(
    name: str,
    server_url: str,
    mk_dir_url: str,
    dedup: bool = True,
) -> None

Register a mission. If it already exists, replaces the existing entry.

list_missions

db.list_missions() -> list[dict]

List all configured missions. Returns dicts with keys: name, server_url, server_label, mk_dir_url, dedup, added_at.

remove_mission

db.remove_mission(name: str) -> bool

Remove a mission. Returns True if found and removed, False if not found.

get_mission

db.get_mission(name: str) -> dict | None

Look up a mission by name (case-insensitive). Returns dict with same keys as list_missions, or None.


Scanning

scan_directory

db.scan_directory(
    root: str | Path,
    mission: str | None = None,
    extensions: set[str] | None = None,
    verbose: bool = False,
    archive: bool = False,
    archive_roots: dict[str, Path] | None = None,
) -> tuple[int, set[str]]

Recursively scan a directory tree and register all kernel files. Returns (count, missions_found) — the number of files registered and a set of detected mission names.

With archive=True, each file is moved into a kernel root, laid out as {root}/{mission}/{type}/{filename}, and a symlink is left at the original location. The root is the file’s own when it already sits in a configured root, else root_for of its mission. Every file’s root is settled before anything moves, so an AmbiguousKernelRoot leaves the tree untouched; archive_roots ({mission: root}) answers it on the next call. scan_roots takes the same two arguments.

If mission is not provided, it is detected from the path with guess_mission and the database’s kernel roots: under a root, the first directory below the root; elsewhere, the path structure (.../<MISSION>/kernels/...). register_file guesses the same way when it is given no mission.

extensions defaults to all known SPICE kernel extensions (.tls, .tpc, .bsp, .bc, .tf, .ti, .tsc, .bds, .tm).

scan_roots

db.scan_roots(
    verbose: bool = False,
    archive: bool = False,
    archive_roots: dict[str, Path] | None = None,
) -> tuple[int, set[str]]

Run scan_directory over every kernel root in db.kernel_roots, in order, as skd scan does with no directory. Returns the total count and the union of the missions found. A root that is not an existing directory is skipped with the message Kernel root <path> does not exist; skipped.

register_file

db.register_file(
    path: str | Path,
    mission: str | None = None,
    source_url: str | None = None,
    archive_dir: str | Path | None = None,
    expected_hash: str | None = None,
) -> str

Register a single kernel file. Returns its SHA-256 hash.

If archive_dir is provided, the file is moved into the archive and a symlink is left at the original location. If expected_hash is provided, the computed hash is verified before storing — raises ValueError on mismatch.

If the file’s content already exists in the database under a different filename, the new location is recorded pointing to the same hash. This is logged at the INFO level.


Lookup

resolve_metakernel

db.resolve_metakernel(ref: str | Path, mission: str | None = None) -> Path

The on-disk path of the metakernel ref names. ref may be a path that exists, a registry filename, a registry mk_path, the source_url it was fetched from, or a version-stripped base name (juice_crema_5_2.tm for juice_crema_5_2_v473_20260819_001.tm), case-insensitive, with or without .tm; mission narrows the registry to one mission (prefix match). Every CLI command resolves its metakernel argument through this method, so a name works the same everywhere.

Raises MetakernelNotTracked when nothing matches or the matched file is gone, and AmbiguousMetakernel when several registry rows match; it never picks the first of several.

registry_rows

db.registry_rows(mission: str | None = None) -> list[RegistryRow]

Every tracked metakernel as a RegistryRow (mk_path, source_url, filename, mission, acquired_at, official), ordered by mission and filename; mission is a case-insensitive prefix filter. The one registry query behind the resolver and the CLI pickers. official is False for a metakernel imported with official=False and True otherwise. The column is added when a database from before this release is first opened for writing. Opened read-only (ls, show, doctor, check) before that, every row reads as official.

find_by_filename

db.find_by_filename(filename: str) -> list[dict]

Find all locations for a kernel by filename (basename). Checks both the canonical filename in the kernels table and the actual filename in locations.abs_path.

Returns a list of dicts with keys: sha256, abs_path, mission, kernel_type, size_bytes.

find_by_hash

db.find_by_hash(sha256: str) -> list[dict]

Find all locations for a kernel by its SHA-256 hash.

Returns a list of dicts with keys: abs_path, mission, filename.

resolve_kernel

db.resolve_kernel(
    filename: str,
    preferred_mission: str | None = None,
) -> tuple[str | None, list[str]]

Resolve a kernel filename to an absolute path on disk.

Returns (path, warnings) where path is the resolved absolute path (or None if not found) and warnings is a list of human-readable strings about any fallback decisions.

Resolution priority (see Mission-aware resolution):

  1. Exact filename match in preferred_mission → no warning
  2. Exact filename match in any mission → warning
  3. Path-suffix match (file on disk registered under different name) → warning
  4. Metakernel registry match, for .tm files acquired via get → warning only on a cross-mission hit
  5. Not found → (None, []) + hint to run scan

Steps 1 and 2 match on content, so a name can have several hits when two byte-identical files are registered under different names. A location actually named filename always wins; a differently-named copy is used only when no file of the requested name is registered, and says so in a warning.

aliases

db.aliases(name_or_hash: str) -> dict | None

Follow the deduplication trail for a kernel. name_or_hash may be a full or partial (≥6-char) SHA-256, the canonical filename, or any alias filename the content has been registered under.

Returns None if nothing matches, otherwise a dict:

{
    "sha256": str,
    "canonical": str,          # first-seen filename (kernels.filename)
    "kernel_type": str,
    "size_bytes": int,
    "superseded": bool,
    "aliases": list[str],      # every filename this content is known under
    "locations": list[dict],   # {"abs_path", "mission", "source_url"}
}

Aliases are derived from locations, not stored separately: the read-only view kernel_aliases (sha256, filename) exposes every distinct on-disk basename each content hash appears under, so a deduplicated kernel (identical bytes under several names) is followable with zero extra bookkeeping — the trade-off is that a name is forgotten once its file is pruned. The companion alias_counts(shas: list[str]) -> dict[str, int] maps each hash to its number of known names, and alias_counts_by_name(filenames: list[str]) -> dict[str, int] maps each filename to how many other names its content is known under (used to render the (+N aliases) annotation in kernel listings).


Metakernel operations

check_metakernel

db.check_metakernel(
    mk_path: str | Path,
    mission: str | None = None,
    verbose: bool = False,
) -> dict

Check which kernels from a metakernel are available locally.

Returns a dict with keys:

  • found: list of (raw_entry, local_path) tuples
  • missing: list of raw_entry strings
  • warnings: list of warning strings

rewrite_metakernel

db.rewrite_metakernel(
    mk_path: str | Path,
    output: str | Path,
    *,
    mission: str | None = None,
    link_root: str | Path | None = None,
) -> tuple[Path, list[str]]

Rewrite a metakernel for local use with minimal edits.

Creates a symlink tree at link_root (default: kernels/ next to the output file) that mirrors the original directory structure. Only PATH_VALUES in the output .tm file is changed — KERNELS_TO_LOAD, PATH_SYMBOLS, and all comments are preserved.

Returns (output_path, warnings).

See Minimal metakernel edits for the design rationale.

get_metakernel

db.get_metakernel(
    url: str,
    download_dir: str | Path | None = None,
    mission: str | None = None,
    yes: bool = False,
    force: bool = False,
    verbose: bool = False,
    dry_run: bool = False,
) -> dict

Fetch a remote metakernel, display a status table, and download missing kernels.

  1. Fetches and parses the remote .tm file
  2. Resolves kernel entries to full URLs (using PATH_VALUES relative to the metakernel URL)
  3. Checks each kernel against the local database
  4. Queries remote file sizes via parallel HTTP HEAD requests
  5. Displays a summary table with kernel names, sizes, and status (in db / missing)
  6. Prompts for confirmation (unless yes=True)
  7. Downloads missing kernels, preserving subdirectory structure, and registers them
  8. Creates symlinks for kernels already in the database so the metakernel works immediately

download_dir defaults to root_for(mission): the configured root that already holds kernels of the mission, or the only configured root. With several roots and no such fact it raises AmbiguousKernelRoot rather than guess; pass download_dir then. Downloaded files are placed under <download_dir>/<mission>/<relpath>.

verbose=True additionally lists each kernel’s resolved URL beneath the status table. The table itself is always shown — it precedes the download prompt, so it is what you decide on.

dry_run=True stops after the status table. Nothing is written to disk or to the database and no kernel is downloaded. This is what skd update runs without --execute.

Returns a dict with keys: found, missing, downloaded, warnings. After a dry run the dict also has dry_run: True, and downloaded is empty.

update_metakernel

db.update_metakernel(
    mk_path_or_name: str | Path,
    mission: str | None = None,
    download_dir: str | Path | None = None,
    yes: bool = False,
    force: bool = False,
    verbose: bool = False,
    dry_run: bool = False,
    rescan: bool = True,
) -> dict

Re-fetch a metakernel from its source URL and download new or missing kernels. Looks up the source URL from the metakernel_registry, falling back to the mission’s mk_dir_url + filename if no source URL is stored.

Raises LookupError if the metakernel is not found in the registry or was added via scan without a source URL. Raises MetakernelUnreachableError (a LookupError subclass) when the remote returns 403/404/410 — typically because NAIF rotated the file into former_versions/; use prune_metakernels() to clean up the stale registry row.

After downloading, automatically rescans the kernel directories referenced by the metakernel so newly downloaded files are immediately indexed. verbose=True names each directory as it is re-scanned; otherwise the count is reported in one line. rescan=False skips that step; update_all uses it and scans each distinct directory once at the end.

dry_run=True reports what would change and writes nothing. No rescan happens after a dry run.

Returns the same dict as get_metakernel. After a real run the dict also has scan_dirs, the set of directories the metakernel points at.

update_all

db.update_all(dry_run: bool = False, verbose: bool = False) -> list[dict]

Re-fetch every tracked metakernel from its source, as skd update does. Each one lands in the root that holds it (root_for); there is no directory argument. With dry_run=True each metakernel’s status table is shown and nothing is written. With dry_run=False the missing kernels are downloaded without a per-metakernel prompt, and the directories the metakernels point at are re-indexed once at the end. The skd update command passes dry_run=True unless --execute is given.

Alias rows, where a symlink stands next to its target, are skipped. A source that has gone from the server, a source that cannot be reached, and a row with no source URL are reported in the summary table and never raise.

Returns one dict per metakernel walked, with keys filename, mission, count and error. count is the number of missing kernels in a dry run and the number of downloaded kernels otherwise. error is None or a one-line reason.

import_metakernel

db.import_metakernel(mk_path: str | Path, mission: str | None = None, official: bool = True) -> dict

Track a metakernel that is already on disk, without a download, as skd import does. Indexes its entries, registers every kernel it resolves to that exists on disk, and adds the registry row with no source URL. mission defaults to the mission guessed from the path, with the configured kernel roots taken into account (see guess_mission).

official=False marks a metakernel assembled locally, such as a subsetter’s output or the one planetarypy builds in archived_kernels.py, as skd import --unofficial does. The flag is stored in the registry, ls appends unofficial to the name, and show prints Official: no. Importing a path again replaces its row, so the flag follows the latest call.

Returns a dict with keys mk_path, filename, mission, n_entries, n_registered and missing, the entries whose file is not on disk. Raises FileNotFoundError when mk_path is not a file.

verify_metakernel

db.verify_metakernel(
    mk_path: str | Path,
    *,
    deep: bool = False,
) -> dict

Deeply cross-check a metakernel against the database. Each entry in KERNELS_TO_LOAD is substituted through PATH_VALUES/PATH_SYMBOLS to an absolute path and validated against the kernels row of the registered location at that path, or of the file a symlink there leads to. Only a path the database has not registered falls back to the kernels rows whose filename matches (case-insensitive).

Checks: traversal escape from PATH_VALUES root, dangling symlinks, missing files, size mismatch, SHA-256 mismatch (only in deep mode), AMBIGUOUS resolution (the path is not registered and multiple non-superseded kernels rows share the filename; a registered path is never ambiguous, so a same-named kernel with other content in another mission or kernel root is not flagged — see superseded_by semantics), unregistered files, and non-absolute PATH_VALUES.

Returns a dict with keys entries, ok, fail, fatal, mk_path, deep. Each entry is a dict with raw, resolved, status, detail. fatal is True if any entry is in a P0 state (e.g. TRAVERSAL, HASH_MISMATCH, AMBIGUOUS).

This is the recommended cross-check after every get/update/rewrite. Run with deep=True periodically to catch content corruption that preserves size.

prune_metakernels

db.prune_metakernels(
    dry_run: bool = True,
    delete_files: bool = False,
    timeout: float = 10.0,
) -> list[dict]

Find rows in metakernel_registry whose remote URL returns a permanent HTTP error (403/404/410) and optionally remove them. Sends a HEAD request to each URL with the given timeout.

The probe URL is derived per row: explicit source_url if set, otherwise mission.mk_dir_url + filename (same fallback as update_metakernel). Rows with neither — typically locally-created metakernels with no upstream — are noted in the output and skipped (use skd rm <name> to drop them manually).

Transient failures (timeouts, DNS errors, 5xx) are deliberately never classified as dead — leaving a registry row stale is always safer than deleting on a network blip.

With dry_run=False, the matching rows are removed from metakernel_registry and metakernel_entries. With delete_files=True, the on-disk .tm file is also unlinked; symlink trees under the mission’s download directory are shared and never auto-cleaned.

Returns a list of dicts, one per dead metakernel: {'mk_path', 'filename', 'mission', 'source_url', 'status_code'}.

index_metakernel

db.index_metakernel(mk_path: str | Path)

Parse a metakernel and store its entries in the metakernel_entries table for future reference.

list_metakernels

db.list_metakernels(mission: str | None = None, show: bool = True) -> list[dict]

List all tracked metakernels, optionally filtered by mission. Each entry includes the number of kernel entries.

Alias rows (symlink metakernels created by get) inherit their target’s entry count and content fingerprint, so the listing reads consistently — both rows show the same kernel count and one of them is annotated ↳ identical to <target>.

Prints a summary table (unless show=False) and returns a list of dicts with keys: filename, mission, source_url, acquired_at, mk_path, n_kernels, official, plus identical_to (set when another row has the same content fingerprint).

metakernels_covering

db.metakernels_covering(body_id: int, et: float | None = None, mission: str | None = None) -> list[dict]

Tracked metakernels whose SPK kernels cover a body, for code that needs to pick a metakernel rather than show one. Prints nothing and writes nothing, so it works with read_only=True. Coverage is read from the SPK files each metakernel loads (those present on disk); identical aliases are skipped. With et, only metakernels covering that ephemeris time are returned; without it, any coverage counts.

Returns the list_metakernels rows with an added intervals key, the (et_start, et_end) windows for the body. Needs SpiceyPy.

import spiceypy
db = KernelDB(read_only=True)
spiceypy.furnsh("naif0012.tls")
rows = db.metakernels_covering(-121, spiceypy.utc2et("2027-06-01"))   # BepiColombo MPO

info_metakernel

db.info_metakernel(name: str, kernel_type: str | None = None) -> dict

Show detailed info about a tracked metakernel, as skd show does. name is any form resolve_metakernel accepts. Displays per-kernel status (in db / missing) with kernel type and size. kernel_type limits the printed kernel table to one type; the counts stay whole.

Returns a dict with keys: filename, mission, source_url, acquired_at, mk_path, official, kernels, n_kernels, n_in_db, n_missing. Raises MetakernelNotTracked if nothing matches.

browse_remote_metakernels

db.browse_remote_metakernels(
    mk_dir_url: str,
    mission: str | None = None,
    show_versioned: bool = False,
    sort_by: str = "name",
    filter: str | None = None,
) -> list[dict]

Scan a remote NAIF mk/ directory and show available metakernels. Groups entries by base name (stripping version tags like _v461_20251127_001), counts versioned snapshots, and checks which base metakernels have been locally acquired.

sort_by controls row ordering: "name" (default) sorts alphabetically; "date" sorts by latest remote modification date ascending, so the most recently updated metakernels appear at the bottom.

filter is an optional case-insensitive substring applied to entry filenames before grouping. Useful for narrowing large listings such as the ~1,400-entry JUICE former_versions/ archive.

Prints a summary table and returns a list of dicts with keys: base_name, n_versions, latest_date, is_local, filenames.


Deduplication

report_duplicates

db.report_duplicates(min_copies: int = 2) -> list[dict]

Find and report kernels that exist in multiple locations.

Returns a list of dicts with keys: sha256, filename, size_bytes, count, paths, missions, wasted_bytes.

deduplicate_plan

db.deduplicate_plan() -> list[dict]

Generate a deduplication plan without executing it.

For each set of identical files, selects a canonical copy (preferring generic mission) and lists the rest as removable. Respects per-mission dedup settings from the missions table.

Returns a list of dicts with keys: filename, size_bytes, keep, remove.

Statistics

check_report

db.check_report(mk_path, *, mission=None, hash_=False, remote=False, spice=False) -> dict

Everything the check command reports, as data: mk_path, the raw results under present (check_metakernel), resolves (verify_metakernel, SHA-256 with hash_) and remote (verify_against_server, only with remote, the one network path, together with newer, the newer-version notice or None), the three verdicts as {bit, ok, line} rows and exit_code, the sum of the failed verdicts’ bits. check_metakernel itself prints nothing and touches no network.

stale_locations

db.stale_locations() -> list[tuple[str, str]]

(sha256, abs_path) of every location whose file is gone from disk; the one walk behind clean and doctor.

doctor

db.doctor() -> dict

Database health with no metakernel argument: n_kernels, n_locations, n_metakernels, poisoned (the poisoned_superseded() rows), missing_locations (location paths whose file is gone), conflicting_locations (paths with more than one locations row, that is one file registered under more than one hash) and missing_metakernels (registry filenames whose file is gone). The CLI’s doctor prints it and exits 1 only when poisoned is non-empty. A scan_directory of the directory holding a conflicting path keeps the row that matches the file on disk and supersedes the others; register_file supersedes every stale row at the path, not only one.

poisoned_superseded

db.poisoned_superseded() -> list[dict]

Kernels flagged as superseded by content that exists in no live location, while their own file is present on disk. These resolve as “not found” and re-download on every update; scan over the kernel directory repairs them. A genuine upstream update whose newer file is on disk is not listed.

Returns one dict per kernel with keys: sha256, filename, superseded_by, abs_path.

stats

db.stats() -> dict

Print and return summary statistics.

Returns a dict with keys: n_kernels, n_locations, total_bytes, n_duplicates, n_poisoned, missions.


parse_metakernel

from spice_kernel_db import parse_metakernel
parse_metakernel(path: str | Path) -> ParsedMetakernel

Parse a SPICE metakernel (.tm) file from a local path without needing a database.

parse_metakernel_text

from spice_kernel_db import parse_metakernel_text
parse_metakernel_text(text: str, source: str) -> ParsedMetakernel

Parse a SPICE metakernel from text content (e.g. fetched from a remote URL). The source string is stored as the source_path attribute for reference.

ParsedMetakernel

Dataclass with attributes:

Attribute Type Description
source_path Path Absolute path to the source file
header str Everything before the first \begindata
path_values list[str] Contents of PATH_VALUES
path_symbols list[str] Contents of PATH_SYMBOLS
kernels list[str] Contents of KERNELS_TO_LOAD

Properties and methods:

Name Returns Description
symbol_map dict[str, str] Mapping from symbol name to path value
resolve(entry) str Replace $SYMBOLs with their values
kernel_filenames() list[str] Basenames of all kernels
kernel_relpaths() list[str] Relative paths with $SYMBOL stripped

Configuration

from spice_kernel_db import (
    Config, ensure_config, kernel_roots, add_kernel_root, remove_kernel_root,
)

ensure_config

ensure_config(seed_root: str | Path | None = None) -> Config

Load configuration from ~/.config/spice-kernel-db/config.toml. If no config file exists, runs an interactive first-time setup prompting for the database path and kernel storage directory.

With seed_root and no config file yet, it prompts for nothing: it writes a configuration with the default database path and seed_root as the first kernel root, and creates both directories. An existing configuration is never changed by seed_root. A library such as planetarypy calls it this way on first run to point skd at its own store.

Config

Config(db_path=DEFAULT_DB_PATH, kernel_dirs=[DEFAULT_KERNEL_DIR])

Configuration object with these attributes:

Attribute Type Default Description
db_path str ~/.local/share/spice-kernel-db/kernels.duckdb Path to the DuckDB database
kernel_dirs list[str] ["~/.local/share/spice-kernel-db/kernels"] The kernel roots. No root is special; see root_for below. Never empty: an empty list becomes the default store.

The [storage] section of the file holds kernel_dirs, and save_config writes only that key. A file written before the list existed has only kernel_dir; it loads as a one-root list and is rewritten as kernel_dirs on the next save.

Kernel roots

kernel_roots(config: Config | None = None) -> list[Path]
add_kernel_root(directory: str | Path, config: Config | None = None) -> Config
remove_kernel_root(directory: str | Path, config: Config | None = None) -> Config

kernel_roots returns the configured roots as expanded, resolved paths. Without a config file it returns the one default root. Pass config to avoid reading the file a second time. add_kernel_root and remove_kernel_root take the same config argument and edit that object instead of loading the file.

add_kernel_root appends directory to the roots and saves. It creates the directory when missing and does not add a root twice; the order of the others is kept. It runs no prompt, and without a config file it writes one with the default database path. It returns the updated Config.

remove_kernel_root removes directory from the roots and saves. It raises ValueError when the directory is not a root or is the last one. Files on disk and database rows are untouched; clean drops rows whose file is gone. It returns the updated Config.

from spice_kernel_db import add_kernel_root, kernel_roots

add_kernel_root("~/planetarypy_data/spice_kernels")
kernel_roots()
# [PosixPath('/Users/me/.local/share/spice-kernel-db/kernels'),
#  PosixPath('/Users/me/planetarypy_data/spice_kernels')]

The CLI equivalents are skd config add-root and skd config remove-root; see Several kernel roots.

KernelDB.root_for

db.root_for(mission: str | None, mk_path: str | Path | None = None) -> Path

The one answer to “which kernel root does this download belong in”. In order: the root that contains mk_path (a tracked metakernel is re-fetched into its own store), the only configured root, and the one root that already holds kernels of mission. When several roots remain it raises AmbiguousKernelRoot (a LookupError carrying mission and roots) instead of picking the first; the CLI turns that into a picker at a terminal and exit 2 in a script. get_metakernel and update_metakernel call it when download_dir is not given (a URL that is already tracked uses that row’s root), and scan_directory(archive=True) calls it for every file outside the roots.

guess_mission

from spice_kernel_db.hashing import guess_mission

guess_mission(filepath: str, roots: list[Path] | None = None) -> str

Best-effort mission name for a kernel file, canonicalized like every stored mission name. Under one of roots (as returned by kernel_roots()) the mission is the first directory below the root, because skd’s own store is laid out as <root>/<MISSION>/<type>/<file>. A file under a root but not in a mission directory, for example directly in the root or in a type directory such as mk, is classified from its filename only. Outside every root the path heuristic applies: the directory before kernels/, then the parent of a kernel-type directory, then filename patterns.

register_file, scan_directory and import_metakernel pass db.kernel_roots. check_metakernel, rewrite_metakernel, coverage_metakernel and the server comparison do not guess for a tracked metakernel: when mission is not given they read it from the registry row, and only an untracked file is guessed from its path.


Remote utilities

from spice_kernel_db import fetch_metakernel, resolve_kernel_urls

fetch_metakernel

fetch_metakernel(url: str) -> str

Download and return the text content of a remote metakernel file.

resolve_kernel_urls

resolve_kernel_urls(mk_url: str, parsed: ParsedMetakernel) -> list[str]

Resolve each KERNELS_TO_LOAD entry in a parsed metakernel to a full URL, using PATH_VALUES relative to the metakernel’s own URL.

list_remote_missions

from spice_kernel_db.remote import list_remote_missions
list_remote_missions(server_url: str) -> list[str]

List available mission directories from a SPICE archive server (NASA NAIF or ESA SPICE). Parses the Apache directory listing.

SPICE_SERVERS

from spice_kernel_db.remote import SPICE_SERVERS

Dict mapping server labels to URLs: {"NASA": "https://naif.jpl.nasa.gov/pub/naif/", "ESA": "https://spiftp.esac.esa.int/data/SPICE/"}.

list_remote_metakernels

from spice_kernel_db import list_remote_metakernels
list_remote_metakernels(mk_dir_url: str) -> list[RemoteMetakernel]

Parse an Apache directory listing at mk_dir_url and extract .tm metakernel entries. For each file, computes a base_name by stripping NAIF version tags (e.g. _v461_20251127_001). Returns a list sorted by (base_name, filename).

RemoteMetakernel

Dataclass with attributes:

Attribute Type Description
filename str Original filename from the directory listing
url str Full URL to the file
date str Last modified date from the listing
size str Size string from the listing (e.g. "12K")
base_name str Filename with version tag stripped
version_tag str \| None Version tag (e.g. "v461_20251127_001") or None

probe_mk_candidates

from spice_kernel_db.remote import probe_mk_candidates
probe_mk_candidates(urls: list[str], *, max_workers: int = 8, timeout: float = 5.0) -> list[str]

Send parallel HEAD requests to candidate metakernel-directory URLs and return those that respond successfully, preserving the input order (which encodes priority). Duplicates are collapsed.

discover_mk_url

from spice_kernel_db.remote import discover_mk_url, DEFAULT_ALT_MK_PATHS
discover_mk_url(
    server_url: str,
    mission: str,
    *,
    registry_candidates: list[str] | None = None,
    extra_paths: tuple[str, ...] = DEFAULT_ALT_MK_PATHS,
    timeout: float = 5.0,
) -> list[str]

Discover live metakernel directory URLs for mission. Tries registry_candidates (highest priority) first, then expands the templates in extra_paths (placeholders {server} and {m}). Returns hits in priority order.

DEFAULT_ALT_MK_PATHS contains only {server}{m}/kernels/mk/. An empirical NAIF survey found that no missions use alternative templates one might expect from naming convention — alternates should be added via the curated registry or --mk-dir-url, not inferred.

Mission registry

from spice_kernel_db import registry

Reads mission_registry.toml shipped with the package. Used by mission add to find metakernel directories for missions whose layout deviates from the default.

MissionEntry

Dataclass with one field, candidates: tuple[str, ...]: URL templates with {server}/{m} placeholders.

load_registry

registry.load_registry() -> dict[str, MissionEntry]

Cached loader for the bundled registry. Clear the cache via registry.load_registry.cache_clear() after replacing the data file (only relevant in tests).

registry_candidates

registry.registry_candidates(mission: str, server_url: str) -> list[str]

Return registry-defined candidate metakernel URLs for mission with placeholders expanded. Empty list when the mission has no registry entry.

Exceptions

from spice_kernel_db import (
    AmbiguousMetakernel,
    ConcurrentModificationError,
    MetakernelNotTracked,
    MetakernelUnreachableError,
)

AmbiguousMetakernel

Raised by KernelDB.resolve_metakernel() (and so by every method that takes a metakernel reference) when the reference matches several registry rows, for example a base name while two versioned snapshots are tracked. Subclass of LookupError. Attributes: name, candidates (the matching registry filenames). The CLI lists the candidates and exits 2.

MetakernelNotTracked

Raised when a metakernel reference matches nothing in the registry and is not a path on disk, or when the matched registry row points at a file that is gone. Subclass of LookupError. Attribute: name. The message carries the spice-kernel-db get <name> hint; the CLI prints it and exits 1.

ConcurrentModificationError

Raised when KernelDB.get_metakernel() detects that another process modified the kernel records during its network I/O window (after the DB lock was released to allow parallel reads). Subclass of RuntimeError. Retry the operation after the other writer completes.

MetakernelUnreachableError

Raised by KernelDB.update_metakernel() when the remote metakernel returns HTTP 403/404/410 — typically because NAIF rotated the file into former_versions/. Subclass of LookupError. Attributes: url, status (int HTTP code), filename. Recovery: db.prune_metakernels(dry_run=False).