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 = "~/.spice_kernels.duckdb")

Opens (or creates) the database at the given path. The schema is initialized automatically.

Supports context manager usage:

with KernelDB() as db:
    ...

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,
) -> int

Recursively scan a directory tree and register all kernel files. Returns the number of files registered.

If mission is not provided, it’s auto-detected from the path structure (looks for .../<MISSION>/kernels/...).

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

register_file

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

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

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

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. Fuzzy match (prefix-based) in preferred_mission → warning
  4. Fuzzy match in any mission → warning
  5. Not found → (None, [])

Metakernel operations

check_metakernel

db.check_metakernel(
    mk_path: str | Path,
    mission: str | None = None,
) -> 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,
) -> 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 the configured kernel_dir from ~/.config/spice-kernel-db/config.toml. Downloaded files are placed under <download_dir>/<mission>/<relpath>.

Returns a dict with keys: found, missing, downloaded, warnings.

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) -> list[dict]

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

Prints a summary table and returns a list of dicts with keys: filename, mission, source_url, acquired_at, mk_path, n_kernels.

info_metakernel

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

Show detailed info about a tracked metakernel, looked up by filename. Displays per-kernel status (in db / missing) with kernel type and size.

Returns a dict with keys: filename, mission, source_url, acquired_at, mk_path, kernels, n_kernels, n_in_db, n_missing. Returns None if not found.

browse_remote_metakernels

db.browse_remote_metakernels(
    mk_dir_url: str,
    mission: 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.

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

stats

db.stats() -> dict

Print and return summary statistics.

Returns a dict with keys: n_kernels, n_locations, total_bytes, n_duplicates, 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

ensure_config

ensure_config() -> 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.

Config

Dataclass with attributes:

Attribute Type Default Description
db_path str ~/.local/share/spice-kernel-db/kernels.duckdb Path to the DuckDB database
kernel_dir str ~/.local/share/spice-kernel-db/kernels Default directory for downloaded kernels

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